线程在onDestroy之后启动

时间:2018-01-26 17:40:03

标签: android multithreading android-activity

我创建了一个新的线程,用于在后台接收蓝牙数据。当我关闭应用程序时,线程正确关闭。但是当我改变活动时,线程会再次打开。

private void receiveDataInBackground() {
Log.d(TAG, "receive Data in Background");
handlerInBackground = new Handler();
handlerInBackground.postDelayed(myRunnableInBackground = new Runnable() {
    @Override
    public void run() {
        dataReceived=false;
        Log.d(TAG, "in receiveBackground");
        openBT();
         //
            if(dataReceived==true){closeBT();}
            handlerInBackground.postDelayed(this, 60000);
        }
    }, 60000);
}

这是我的onDestroy

public void onDestroy(){
super.onDestroy();
saveArrayList(btDataList, "btDataList");
btAdapter.disable();
Log.d(TAG, "finishing APP");
handlerInBackground.removeCallbacksAndMessages(myRunnableInBackground);
finish();

有人知道这个问题还是可以帮助我?非常感谢!

编辑: 可以在github上找到完整的代码: https://github.com/LongDong279/AppGeruest3

1 个答案:

答案 0 :(得分:0)

使用onPause()代替onDestroy()

public void onPause(){
     super.onPause();
     saveArrayList(btDataList, "btDataList");
     btAdapter.disable();
     Log.d(TAG, "finishing APP");
     handlerInBackground.removeCallbacksAndMessages(myRunnableInBackground);
}

如果我理解你并且#34;改变活动"意味着你从它去另一个活动。因此,您可能需要在开始活动后致电finish()