【问题标题】:Thread starts after onDestroy线程在 onDestroy 之后开始
【发布时间】:2018-07-06 02:36:54
【问题描述】:

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

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

【问题讨论】:

    标签: android multithreading android-activity


    【解决方案1】:

    使用onPause() 代替onDestroy()

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

    如果我理解你的话,“改变活动”意味着你从它转到另一个活动。所以您可能需要在开始活动后致电finish()

    【讨论】:

    • 谢谢,会试试的。当我最小化应用程序时会调用 onPause 吗?
    • 是的。它在 onDestroy() 之前调用 .. google image : 活动生命周期以便更好地理解。
    • 好的,谢谢。问题:我想在 onDestroy 方法中调用我的方法。我可以通过添加 handlerInBackground.removeCallbacks 来解决我的问题。但!现在我的应用程序无法正确关闭,它仍然处于后台。我如何获得这些信息? -> Android Studio 不会停止调试
    • 是您的receiveDataInBackground() 是单独线程的一部分。您只能通过将其分配为 null 来停止该线程。尝试在onPause 中执行此操作。这肯定会阻止它
    • 谢谢 试试这个。问题,如果应用程序在后台通过蓝牙在后台接收数据,我是否需要这个线程。还是有其他方法来处理这个?谢谢
    猜你喜欢
    • 1970-01-01
    • 2012-07-29
    • 2014-06-24
    • 2011-03-03
    • 1970-01-01
    • 2012-08-01
    • 2023-03-16
    相关资源
    最近更新 更多