运行 应用程序关闭时来自广播接收器的任务 [Android]

Running tasks from broadcast receiver while app is closed [Android]

我有一个应用程序可以在发出通知时下载数据并将其放入 SQLite 数据库。这在应用程序正在使用时工作正常,但我也需要它在应用程序关闭时工作。

我已经在其中设置了一个 BroadcastReceiver,当应用程序关闭时会调用它,但我不确定如何让它继续添加到数据库中。

这是我使用的代码:

AndroidManifest.xml

<manifest....

   <application...

     <receiver android:name=".broadcast.PacksReceiver" >
        <intent-filter>
            <action android:name="ADD_PACK" >
            </action>
        </intent-filter>
    </receiver>

PacksReceiver

public class PacksReceiver extends BroadcastReceiver {
  @Override
  public void onReceive(Context context, Intent intent) {
    Log.d("PacksReceiver", "onReceive");

    String message = intent.getStringExtra("message");

    PacksActivity pa = new PacksActivity();
    pa.downloadPack(null, message);
  }
}

PacksActivity

public void downloadPack(View v, String thisPackID){
    Log.d("download", "pack");
    //THIS LOG IS CALLED EVERYTIME
    vRef = v;
    if(vRef != null){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                onScreenProgressBar = (ProgressBar) vRef.findViewById(R.id.onScreenProgress);
                onScreenProgressCircle = (ProgressBar) vRef.findViewById(R.id.onScreenProgressCircle);
                dlPercent = (TextView) vRef.findViewById(R.id.dlPercent);

                onScreenProgressCircle.setVisibility(View.VISIBLE);

                onScreenProgressBar.setVisibility(View.VISIBLE);
                onScreenProgressCircle.setProgress(0);
            }
        });
    }
    if(thisPackID == null){
        thisPackID = pack_id;
    }

    String url = MyApp.getAppContext().getString(R.string.serverURL) +
            MyApp.getAppContext().getString(R.string.getAppendixA) + "/" + thisPackID;
    Intent appA_Intent = new Intent(Intent.ACTION_SYNC, null, this, DownloadService.class);
    appA_Intent.putExtra("url", url);
    appA_Intent.putExtra("onCreate", "false");
    appA_Intent.putExtra("receiver", downloadPackReceiver);
    appA_Intent.putExtra("downloadType", "GET_APPENDIX_A");
    appA_Intent.putExtra("requestId", 101);
    MyApp.getAppContext().startService(appA_Intent);
}

编写代码以在 OnRecieve() 方法内的 PackReciever 中的数据库中添加数据,因为这是您接收推送通知的地方。

不要在接收器内部调用 activity。相反,使用 IntentService 下载所有包。 IntentService 在完成其工作后自动完成。

覆盖它的 onHandleIntent() 方法并下载包并保存到那里的数据库。

开始服务
onReceive()

方法因为可以得到多个广播一个接一个