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



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

我在里面设置了一个BroadcastReceiver,当应用程序关闭时会调用它,但我不知道如何让它继续添加到数据库中。

这是我正在使用的代码:

AndroidManifest.xml

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

数据包接收器

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);
  }
}

数据包活动

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);
}

从启动服务

onReceive()

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

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

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

重写它的onHandleIntent((方法并下载包并保存到那里的数据库中。

最新更新