You can schedule an alarm using the AlarmManager and run your code from the BroadcastReceiver/Service. The alarm will trigger weather your app is dead or alive. (If it's dead it will be awaken)
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Intent intent = new Intent(getApplicationContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0);
You can use this method to register a one time alarm. So if you want the alarm to trigger in 5 mins, the delayMillis
value should be 5 * 1000 * 60
void registerOneTimeAlarm(PendingIntent pendingIntent, long delayMillis) {
int SDK_INT = Build.VERSION.SDK_INT;
long timeInMillis = System.currentTimeMillis() + delayMillis;
if (SDK_INT < Build.VERSION_CODES.KITKAT) {
alarmManager.set(AlarmManager.RTC_WAKEUP, timeInMillis, pendingIntent);
} else if (SDK_INT < Build.VERSION_CODES.M) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, timeInMillis, pendingIntent);
} else {
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, timeInMillis, pendingIntent);
}
}
Let's say you will use a receiver, it will look like this:
public class AlarmReceiver
extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// Your code here
}
}
And don't forget to add it in the Manifest:
<receiver android:name="your.package.AlarmReceiver"/>
IMPORTANT
Registered alarms are cleared when the device reboots, you need to re-register the alarm after the device boots. (If this is what you really need)