I am trying to create an Android app that increments a counter after every 24 hours. I am just making use of SharedPreferences and when it is time it increments the value in sha
You can use AlarmManager class to schedule a repeating alarm with PendingIntent
that will do your job when scheduled.
https://developer.android.com/training/scheduling/alarms
I'll give you sample of dailyAlarm doing some job when fired:
public void setDailyAlarmOn(Context context, long alarmTime, Uri reminderTask, long repeatTime) {
AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
PendingIntent operation =
yourJobHere.getReminderPendingIntent(context, reminderTask);
if (Build.VERSION.SDK_INT >= 23) {
manager.setRepeating(AlarmManager.RTC_WAKEUP, alarmTime, repeatTime, operation);
} else {
manager.setRepeating(AlarmManager.RTC_WAKEUP, alarmTime, repeatTime, operation);
}
}
alarmTime - first time in miliseconds when alarm is supposed to be fired
repeatTime - time in mili seconds - 86400000 for 24h (1000*60*60*24)
Uri reminderTask - uri that I created to not to cancel previous alarms, in short, it's a code for alarm application and it's uri from row in database.
operation - PendingIntent which you'll need to create
I did it by extending IntentService and handling job in onHandleIntent
:
YourJobHere.class:
public class YourJobHere extends IntentService {
private static final String TAG = YourJobHere.class.getSimpleName();
public static PendingIntent getReminderPendingIntent(Context context, Uri uri) {
Intent action = new Intent(context, YourJobHere.class);
action.setData(uri);
return PendingIntent.getService(context, 0, action, PendingIntent.FLAG_UPDATE_CURRENT);
}
public YourJobHere() {
super(TAG);
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
//TODO: make your job here
}
}
If you want you can refer to my full project on GitLab: https://gitlab.com/Domin_PL/SlothProfileScheduler
Hope it'll help you