user8264 user8264 - 2 months ago 14
Android Question

How to stop the thread in Android?

I have a thread in my callback function as follows:

@Override
public void onConnectError(final BluetoothDevice device, String message) {
Log.d("TAG","Trying again in 3 sec.");
runOnUiThread(new Runnable() {
@Override
public void run() {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
//Do something
}
}, 2000);
}
});
}


I will to close the the above thread when I press the back button or onDestroy. How can I do it. Thank you

@Override
public void onBackPressed() {
// Close or distroy the thread
}
@Override
public void onDestroy() {
// Close or distroy the thread
}

Answer

Please do this like

private Handler handler;
private Runnable runnable;

@Override
public void onConnectError(final BluetoothDevice device, String message) {
Log.d("TAG","Trying again in 3 sec.");
runOnUiThread(new Runnable() {
    @Override
    public void run() {
        handler = new Handler();
runnable = new Runnable() {
        @Override
        public void run() {
//Do something
        }
    };
handler.postDelayed(runnable, 2000);
    }
});
}

and

@Override
public void onBackPressed() {
if (handler != null && runnable != null) {
        handler.removeCallbacks(runnable);
    }
 }

and same in onDestroy();

Comments