How to run service in background every 10 minute?

后端 未结 5 1001
独厮守ぢ
独厮守ぢ 2021-02-10 03:04

I want to use a service that run in background indefinitely and call a method every 10 minute and its running even app killed

How to create it?

5条回答
  •  醉梦人生
    2021-02-10 04:04

    you could write a background Service: Running in a Background Service

    and start the service every 10-11 min (cause of AlarmManager power saving behaviour), or with exact timing (needs to shedule next execution every time) with AlarmManager.setExact

    Example:

    private static PendingIntent createClockIntent(Context context) {
            Intent intent = new Intent(context.getString(R.string.widget_broadcast_clock_update));
            PendingIntent pendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(), 1,
                    intent, PendingIntent.FLAG_UPDATE_CURRENT);
            return pendingIntent;
        }
    
        public static void startClockAlarm(Context context) {
            AlarmManager alarmManager = (AlarmManager) context
                    .getSystemService(Context.ALARM_SERVICE);
            clockIntent = createClockIntent(context);
            alarmManager.setRepeating(AlarmManager.RTC, 0,
                    600000, clockIntent);
        }
    

提交回复
热议问题