Service with AlarmManager running always every minute

半腔热情 提交于 2021-01-28 04:12:30

问题


I'm trying to set a service run every 5 minutes in background. But it's acting weird:

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:

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;
    }
}

Manifest:

<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

I'm trying to run every 5 minute to test but it's always running every minute. What's the problem?

I followed this tutorial exactly:

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


回答1:


Try this, it worked for me:

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


来源:https://stackoverflow.com/questions/33380567/service-with-alarmmanager-running-always-every-minute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!