带有 AlarmManager 的服务始终每分钟运行一次 [英] Service with AlarmManager running always every minute
本文介绍了带有 AlarmManager 的服务始终每分钟运行一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将服务设置为每 5 分钟在后台运行一次.但它的表现很奇怪:
I'm trying to set a service run every 5 minutes in background. But it's acting weird:
在主要活动的 onCreate 时,我将其安排为每 5 分钟运行一次:
At onCreate of Main activity, I'm scheduling it to run every 5 minute:
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:
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
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" />
日志,它每分钟都在运行:
Logs, it's running every minute:
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 分钟运行一次以进行测试,但它总是每分钟运行一次.有什么问题?
I'm trying to run every 5 minute to test but it's always running every minute. What's the problem?
我完全遵循了本教程:
推荐答案
试试这个,它对我有用:
Try this, it worked for me:
alarm.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 60 * 1000 * 5, pendingIntent);
这篇关于带有 AlarmManager 的服务始终每分钟运行一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文