Yosi199
Yosi199

Reputation: 1804

UI Thread gets stuck even though I'm working on another

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.

Upvotes: 0

Views: 1162

Answers (3)

Marko Topolnik
Marko Topolnik

Reputation: 200306

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();

Upvotes: 4

user3118604
user3118604

Reputation: 864

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

Upvotes: 3

ucdevs
ucdevs

Reputation: 49

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

Upvotes: 3

Related Questions