[英]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. 当我按下返回按钮或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
}
I'm mostly use thread in this way.See its independent in activity 我主要以这种方式使用线程。查看其独立活动
public class TestActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.abc);
holdConnectionHandler.sendEmptyMessage(0);
}
Handler holdConnectionHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
// do some work
holdConnectionHandler.sendEmptyMessageDelayed(0, 10 * 1000);
}
};
@Override
public void onDestroy() {
super.onDestroy();
holdConnectionHandler.removeCallbacksAndMessages(null);
// or
holdConnectionHandler.removeMessages(0);
}
}
Thanks hope this will help you 谢谢,希望对您有帮助
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(); 和onDestroy()中的相同;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.