我使用GCMNetworkManager
加载某些数据或将某些数据设置到数据库中。
但由于某种原因,如果我的应用程序被杀死(在任务管理器中或由于内存原因),任务就不会运行。
即使应用程序已经死了,是否有可能运行任务?
以下是启用任务的代码:
public void enableTasks(Context context) {
GcmNetworkManager networkManager = GcmNetworkManager.getInstance(context);
scheduleTask(networkManager, BackgroundTasks.WORK_THROUGH_QUEUE);
scheduleTask(networkManager, BackgroundTasks.LOAD_MONTAGEORDERS);
scheduleTask(networkManager, BackgroundTasks.UPDATE_MONIINFO);
PreferenceDao.getInstance().setTasksSet(true);
}
private void scheduleTask(GcmNetworkManager networkManager, String taskTag) {
Task task = BackgroundTasks.getTask(taskTag);
if (task != null) {
networkManager.schedule(task);
}
}
班级BackgroundTasks
@Override
public int onRunTask(TaskParams taskParams) {
Log.i(TAG, "Task runs: " + taskParams.getTag());
try {
switch (taskParams.getTag()) {
case WORK_THROUGH_QUEUE:
workThroughQueues();
return GcmNetworkManager.RESULT_SUCCESS;
case LOAD_MONTAGEORDERS:
MainController.getInstance().getMontageOrderController().refreshMontageOrders();
return GcmNetworkManager.RESULT_SUCCESS;
case UPDATE_MONIINFO:
UpdateHelper.getInstance().updateInfos();
return GcmNetworkManager.RESULT_SUCCESS;
default:
return GcmNetworkManager.RESULT_FAILURE;
}
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
return GcmNetworkManager.RESULT_FAILURE;
}
}
public static Task getTask(String taskTag) {
switch (taskTag) {
case WORK_THROUGH_QUEUE:
return buildTask(taskTag, 300L, 60L);
case LOAD_MONTAGEORDERS:
return buildTask(taskTag, 900L, 60L);
case UPDATE_MONIINFO:
return buildTask(taskTag, 1800L, 120L);
default:
return null;
}
}
private static Task buildTask(String tag, long period, long flex) {
return new PeriodicTask.Builder()
.setTag(tag)
.setPeriod(period)
.setFlex(flex)
.setService(BackgroundTasks.class)
.setRequiredNetwork(Task.NETWORK_STATE_CONNECTED)
.setPersisted(true)
.setUpdateCurrent(true)
.build();
}
AndroidManifest.xml
<service
android:name=".BroadcastReceiver.BackgroundTasks"
android:exported="true"
android:permission="com.google.android.gms.permission.BIND_NETWORK_TASK_SERVICE">
<intent-filter>
<action android:name="com.google.android.gms.gcm.ACTION_TASK_READY" />
</intent-filter>
</service>