Android - Running a background task every 15 minutes, even when application is not running

后端 未结 5 765
灰色年华
灰色年华 2020-12-05 05:35

I need to build a background task that runs every 10/15 minutes (doesn\'t really matter, either is good), even when the application is not running.

How can I accompl

5条回答
  •  情话喂你
    2020-12-05 05:59

    You have have detemined the amount of time (interval) to execute a snippet of code, its better to use AlarmManager because its more energy effient. If your app needs to listen to some sort of a event , then Service is what you need.

    public static void registerAlarm(Context context) {
        Intent i = new Intent(context, YOURBROADCASTRECIEVER.class);
    
        PendingIntent sender = PendingIntent.getBroadcast(context,REQUEST_CODE, i, 0);
    
        // We want the alarm to go off 3 seconds from now.
        long firstTime = SystemClock.elapsedRealtime();
        firstTime += 3 * 1000;//start 3 seconds after first register.
    
        // Schedule the alarm!
        AlarmManager am = (AlarmManager) context
                .getSystemService(ALARM_SERVICE);
        am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime,
                600000, sender);//10min interval
    
    }
    

提交回复
热议问题