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?
I think there isnt any problem.
The leak problem normally happens when you need some task to be done in the future and you hold a reference to a currenctly available object (which may be killed before that task happens).
This also happens if a non static inner class object is sent as a parameter to be used in a specific time in the future. Since the non static inner class holds a reference to its father its gonna be a big memory leak.
1- you didnt hold any reference to your context for your future task
2- you didnt use a inner class and made your class as a separate file and methods are static.
So be sure you are safe and sound ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With