I'm setting alarms in my app using AlarmManager
from multiple Activities.
To avoid redundant code, I created the following class:
public class CustomAlarmManager {
private static final String SHARED_PREF_REQUEST_CODE = "requestCode";
private static final String KEY_REQUEST_CODE = "kRequestCode";
private CustomAlarmManager() {
}
public static void setNewAlarm(Context context, long timeInMillis) {
Intent intent = new Intent(SomeOtherClass.ALARM_ACTION);
intent.putExtra(SomeOtherClass.KEY_ALARM_TIME, timeInMillis);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
context.getApplicationContext(),
getNewCode(context),
intent,
PendingIntent.FLAG_ONE_SHOT);
AlarmManager am = (AlarmManager) context.getSystemService(ALARM_SERVICE);
if (Build.VERSION.SDK_INT >= 23) {
am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,
timeInMillis, pendingIntent);
} else if (Build.VERSION.SDK_INT >= 19) {
am.setExact(AlarmManager.RTC_WAKEUP, timeInMillis, pendingIntent);
} else {
am.set(AlarmManager.RTC_WAKEUP, timeInMillis, pendingIntent);
}
}
// this method is for generating unique int values
// for the requestCode param of PendingIntent.getBroadcast()
private static int getNewCode(Context context) {
SharedPreferences prefs = context.getSharedPreferences(
SHARED_PREF_REQUEST_CODE, MODE_PRIVATE);
int oldCode = prefs.getInt(KEY_REQUEST_CODE, Integer.MIN_VALUE);
int newCode = ++oldCode;
prefs.edit().putInt(KEY_REQUEST_CODE, newCode).apply();
return newCode;
}
}
So when i'd like to set an alarm, i can just call the following from anywhere in my app:
CustomAlarmManager.setNewAlarm(aContext, someTimeInMillis);
My question:
Should I have to worry about leaking the Context
here?
I'm not storing a reference to it, so I think I'm good, but I'm not sure.
Is this a good approach?