[英]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.