如何在Android中停止线程?

时间:2016-09-15 15:10:26

标签: android multithreading android-runonuithread

我的回调函数中有一个线程如下:

@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);
        }
    });
}

当我按下后退按钮或onDestroy时,我将关闭上面的线程。我该怎么做。谢谢

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

2 个答案:

答案 0 :(得分:1)

我主要以这种方式使用线程。参见其独立的活动

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

}
}

谢谢希望这会对你有所帮助

答案 1 :(得分:1)

请像

一样
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);
    }
});
}

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

和onDestroy();

相同