0

I am developing a Bluetooth application.In that I have 1 button, on click of the button I am starting a thread.Inside the thread, I am discovering and connecting ble devices.Repeated click of the button causing the UI to hang.

Code I am using to create the thread is:

new Thread(new Runnable() {
            @Override
            public void run() {
//do bluetooth stuffs

            }
        }).start();

I am not stopping this thread anywhere.

I don't know what is causing the UI to hang please help me.

Pravitha V
  • 3,308
  • 4
  • 33
  • 51

3 Answers3

0

Do you mean that if you keep smashing the button repeatedly (without waiting for the task to finish), then the ui lags? Or when you press the button, wait a bit, then press again.

If it's the first case (where you're mashing the button in quick succession), try this: If you set some boolean flag when you first start the process, then each time you press the button check if that flag is set to true, and only execute the search if the flag is false. Not sure if this is your issue but it's worth a shot?

swerly
  • 2,015
  • 1
  • 14
  • 14
  • Thank you for the quick reply.The button is used to retry connecting ble device.If it fails.The connection process is running in thread.And If user clicks repeatedly with 1s pause also the ui hang.My doubt the started thread was not completed and on thread request has sent i guess.So do i need to check whther the thread is running before starting one more thread if I am using the above code. – Sachin Gururaj Acharya Aug 22 '17 at 06:21
0

I would advise you to use a thread pool instead. Resources are limited.I didn't understand why are you creating a new thread for every button press. a bunch of threads banging for a resource might freeze Your app, or there could be implementation related issues like a deadlock, thread contention, or thread starvation which will definately prompts to freeze your application.

Yohannes Gebremariam
  • 2,225
  • 3
  • 17
  • 23
  • The usecase is onclick of button check whther the devices are connected or not else connect.These things I am doing in thread son how can i avoid creating new thread here.I am using the above code. – Sachin Gururaj Acharya Aug 22 '17 at 06:34
0

For the Android, you can use handler instead thread or handle your thread using handler is a better way, for example, you can use like

new Handler().post(new Runnable() {
            @Override
            public void run() {

            }
        });

if you want to use the main thread then use like.

new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {

            }
        });

for information, you can refer this link difference between Thread and Handler

Kishan Donga
  • 2,851
  • 2
  • 23
  • 35