Я настраиваю будильник в своем приложении, используя AlarmManager
из нескольких видов деятельности.Я утечка Контекста?
Чтобы избежать избыточного кода, я создал следующий класс:
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;
}
}
Так что, когда я хотел бы установить сигнал, я могу просто позвонить следующее из любого места в моем приложении:
CustomAlarmManager.setNewAlarm(aContext, someTimeInMillis);
Мой вопрос:
Должен ли я беспокоиться о утечке Context
здесь?
Я не хранил ссылки на него, поэтому я думаю, что я хорош, но я не уверен.
Это хороший подход?
Вы даже использовали ApplicationContext всякий случай;) вот удивительные;) хорошо сделаны. –