我尝试使用GcmNetworkManager在我的应用中安排定期任务,该任务运行到API级别17.我按照GCM网络管理器页面上的说明设置了所有内容({{3 }}):
在我的AndroidManifest.xml中,我有:
<service
android:name=".services.MyService"
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>
在我的申请中,我有:
long periodSecs = 30L; // the task should be executed every 30 seconds
long flexSecs = 15L; // the task can run as early as -15 seconds from the scheduled time
String tag = "myScan|1";
PeriodicTask periodic = new PeriodicTask.Builder()
.setService(MyService.class)
.setPeriod(periodSecs)
.setFlex(flexSecs)
.setTag(tag)
.setPersisted(false)
.setRequiredNetwork(com.google.android.gms.gcm.Task.NETWORK_STATE_ANY)
.setRequiresCharging(false)
.setUpdateCurrent(true)
.build();
GcmNetworkManager.getInstance(this).schedule(periodic);
我有MyService,看起来像:
public class MyService extends GcmTaskService {
@Override
public int onRunTask(TaskParams taskParams) {
Log.info("onRunTask: " + taskParams.getTag());
return GcmNetworkManager.RESULT_SUCCESS;
}
@Override
public int onStartCommand (Intent intent, int flags, int startId) {
Log.info("onStartCommand");
return GcmTaskService.START_STICKY_COMPATIBILITY;
}
}
当我启动应用时,我按预期记录 onStartCommand ,但 onRunTask 永远不会被调用。我错过了什么吗?我期待着,一旦启动(由启动命令触发证明),它应该每15-30秒运行一次 - 这是一个正确的假设吗?为什么它根本没有被解雇?
谢谢!
答案 0 :(得分:1)
@Override
public int onRunTask(TaskParams taskParams)
{
Log.info("onRunTask: " + taskParams.getTag());
return GcmNetworkManager.RESULT_SUCCESS;
}
@Override
public void onCreate()
{
Log.i(TAG, "in onCreate");
super.onCreate();
GcmNetworkManager.getInstance(this).schedule(createPeriodicSyncTask());
}
private PeriodicTask createPeriodicSyncTask()
{
return new PeriodicTask.Builder()
.setService(PeriodicSyncService.class)
.setPeriod(mSyncIntervalInSec)
.setFlex(mSyncIntervalInSec - 20)
.setTag(TAG)
.setPersisted(true)
.setRequiredNetwork(NETWORK_STATE_ANY)
.setUpdateCurrent(true)
.setRequiresCharging(false)
.build();
}