0

I have this code that on a click of a button a service will be started from a new thread and the service will start my TCP Client.

The TCP client, once connected will send a count down event to inform the fragment to continue working.

the code looks like this

   connectButton = (Button) view.findViewById(R.id.connectBT);
        connectButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {



                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {

                            // ***** IntentService Way ****** //
                            Intent intent = new Intent(getActivity(), NetworkService.class);
                            getActivity().startService(intent);

                            // Once client is connected, give the server some info about client
                            mCountDown.await(3000, TimeUnit.MILLISECONDS);

                            String json = jsonMaker.toJson(new DeviceInfo());
                            DispatchToServer(json);
                        } catch (Exception ie) {
                            ie.getMessage();
                        }
                    }
                }).run();

but when I click connect, my UI still freezes for some reason, even though I'm waiting on a different thread then the UI thread. Same code worked fine when I used an AsyncTask instead of the service.

Yosi199
  • 1,745
  • 4
  • 22
  • 47

3 Answers3

4

You have written

new Thread(new Runnable() {...}).run();

Thread#run is just the Thread class's implementation of the Runnable interface. All it does is delegate to the run method of the Runnable you have passed to the constructor.

Java threads are started with the start method:

new Thread(new Runnable() {...}).start();
Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
  • Thank you, I do know this but for some reason I got a black out on this very important detail. Feel like a dumbass – Yosi199 Jun 28 '14 at 09:34
  • 1
    It's a very common pitfall. A good way to avoid it is to simply *not* use raw Threads; instead prefer an Executor Service. – Marko Topolnik Jun 28 '14 at 09:35
3

Try to call thread.start() instead of thread.run()

ucdevs
  • 49
  • 8
3

Use Thread.start() instead of Thread.run()

user3118604
  • 854
  • 6
  • 12