[英]Service with AlarmManager running always every minute
我正在尝试在后台设置每 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);
}
}
广告同步服务.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 分钟运行一次以进行测试,但它总是每分钟运行一次。 有什么问题?
我完全按照本教程进行操作:
试试这个,它对我有用:
alarm.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 60 * 1000 * 5, pendingIntent);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.