AlarmManager的服务始终每分钟运行一次

时间:2015-10-27 23:54:18

标签: java android alarmmanager

我尝试在后台每隔5分钟设置一次服务。但它表现得很奇怪:

在onCreate of Main活动中,我安排它每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分钟跑一次测试,但每分钟都会始终。问题是什么?

我完全按照本教程:

https://guides.codepath.com/android/Starting-Background-Services#using-with-alarmmanager-for-periodic-tasks

1 个答案:

答案 0 :(得分:0)

尝试一下,它对我有用:

 alarm.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 60 * 1000 * 5, pendingIntent);