首页 > 解决方案 > 在销毁 BroadcastReceiver 警报之前等待 AsyncTask 完成

问题描述

我的 Android 应用程序在我设置的重复警报方面存在一些问题。AsyncTask 有时需要 5-15 秒才能完成,在较高的范围内,任务最终没有完成,因为 Android 系统onReceive在任务完成之前最终在接收器类中结束。

有没有办法让我保持警报直到任务完成,或者这是不好的做法?

这是onReceive我的意图类:

@Override
public void onReceive(Context context, Intent intent)
{
    getPrefs(context);
    color = (Color.parseColor("#FFFF4500"));
    instances = 0;

    backgroundExecute(context); //5-15 sec, sometimes doesn't get to finish

}

标签: androidandroid-asynctaskbroadcastreceiver

解决方案


So I did some reading on the BroadcastReceiver documentation on Google's page, and found that using goAsync() in my onReceive would keep the broadcast alive until the result is returned by the AsyncTask.

Found here: https://developer.android.com/reference/android/content/BroadcastReceiver.html#goAsync()


推荐阅读