【问题标题】:Background process (AsyncTask) still running after app closes应用程序关闭后后台进程(AsyncTask)仍在运行
【发布时间】:2021-04-20 10:40:54
【问题描述】:

我的应用有 3 或 4 个异步任务,其中两个从 sqlite 数据库获取数据并创建意图将其发送到主活动中的接收器。一切正常 - 直到我关闭应用程序然后重新启动它。然后无法正确接收数据。经过大量实验后,我发现如果在正常关闭应用程序后“强制停止”它,它会再次正常工作 - 直到我下次运行任务并再次关闭应用程序。 在调试器上运行时,此行为不会正常显示。但是,如果我在设备上启动应用程序(而不是通过 Android Studio)然后附加调试器,我可以很清楚地看到接收器每次都接收到两个广播副本,而不是只接收一个。一份是正确的,另一份包含垃圾数据。我添加了额外的行,表明任务 ID 在每种情况下都是相同的。

发送意图如下所示

private void sendRoads(ArrayList<RedRoad> roadsChunk)
{
    ArrayList<RedRoad> theseRoads = new ArrayList<>(roadsChunk);
    Intent mapIntent = new Intent("newRoads");
    mapIntent.putParcelableArrayListExtra("newRoads", theseRoads);
    mapIntent.putExtra("chunkIndex",cIndex++);

    int threadID = android.os.Process.getThreadPriority(android.os.Process.myTid());
    mapIntent.putExtra("threadID",threadID);

    LocalBroadcastManager.getInstance(ctx).sendBroadcast(mapIntent);
    // get ready for next group while we show these
    roadsChunk.clear();
}

为了尝试解决这个问题,我在 onDestroy 中添加了额外的行:

    @Override
public void onDestroy() {
    super.onDestroy();
    if (roadCreation!=null)
        roadCreation.cancel(true);
    if (parseKmlFile != null)
        parseKmlFile.cancel(true);
    Intent serviceIntent = new Intent(getApplicationContext(), LocationService.class);
    stopService(serviceIntent);
}

但这似乎没有任何区别(命名的两个类是使用上述方法的两个类。如您所见,还涉及一个服务,但我可以通过其他方式判断它正在正确停止)。

我试图捕捉错误的广播并忽略对它们的任何操作,但它们仍然会弄乱正确的数据。

我有两个测试设备;一个sdk 26(奥利奥)和一个29(Q);后者每次都会出现这个问题,前者只是偶尔出现。

【问题讨论】:

    标签: android android-asynctask


    【解决方案1】:

    感谢this 的回答,我终于解决了这个问题。 我的 onDestroy() 现在看起来像这样:

    public void onDestroy() {
        super.onDestroy();
        Intent serviceIntent = new Intent(getApplicationContext(), LocationService.class);
        stopService(serviceIntent);
        // ensure all background tasks stop correctly
        int id= android.os.Process.myPid();
        android.os.Process.killProcess(id);
    }
    

    【讨论】:

      猜你喜欢
      • 2011-04-02
      • 2021-05-17
      • 1970-01-01
      • 2020-01-03
      • 2013-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      相关资源
      最近更新 更多