【发布时间】:2018-12-19 19:32:09
【问题描述】:
我正在尝试设置每 5 分钟在后台运行一次服务。但它的行为很奇怪:
在主要活动的 onCreate 中,我将其安排为每 5 分钟运行一次:
public void scheduleAlarm(Context context) {
Intent intent = new Intent(context, AdSyncStartReceiver.class);
final PendingIntent pIntent = PendingIntent.getBroadcast(context, AdSyncStartReceiver.REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);
long firstMillis = System.currentTimeMillis(); // alarm is set right away
AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP,
firstMillis,
5 * 60 * 1000, // 5 min
pIntent);
}
AdSyncStartReceiver.java:
public class AdSyncStartReceiver extends BroadcastReceiver {
// Triggered by the Alarm periodically (starts the service to run task)
@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, AdSyncService.class);
context.startService(i);
}
}
AdSyncService.java
public class AdSyncService extends IntentService {
public AdSyncService() {
super("AdSyncService");
}
@Override
protected void onHandleIntent(Intent intent) {
// Do the task here
Log.i("AdSyncService", "AdSyncService Service running");
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
清单:
<receiver
android:name=".AdManager.AdSyncStartReceiver"
android:process=":remote" >
</receiver>
<receiver android:name=".AdManager.BootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service
android:name=".AdManager.AdSyncService"
android:exported="false" />
日志,每分钟运行一次:
10-28 02:46:51.405 6820-7043/pack I/AdSyncService﹕ AdSyncService Service running
10-28 02:47:04.198 6820-7052/pack I/AdSyncService﹕ AdSyncService Service running
10-28 02:48:04.199 6820-7099/pack I/AdSyncService﹕ AdSyncService Service running
10-28 02:49:04.196 6820-7182/pack I/AdSyncService﹕ AdSyncService Service running
我尝试每 5 分钟运行一次以进行测试,但它始终每分钟运行一次。有什么问题?
我完全按照本教程进行操作:
【问题讨论】:
标签: java android alarmmanager