Am I Comforting the Context?

I set alarms in my application using AlarmManager from several actions.

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; } } 

Therefore, when I would like to set an alarm, I can simply call the following from anywhere in my application:

 CustomAlarmManager.setNewAlarm(aContext, someTimeInMillis); 

My question is:

Should I worry about Context leak here?

I did not keep links to it, so I think I'm good, but I'm not sure.

Is this a good approach?

+5
source share
2 answers

I think there is no problem.

A leak problem usually occurs when you need to perform some task in the future, and you keep a link to the currently available object (which can be killed before this task happens).

This also happens if a non-stationary internal class object is sent as a parameter that will be used at a specific time in the future. Since the non-stationary inner class contains a reference to its father, it will be a big memory leak.

1- you did not indicate any link to your context for your future task.

2- you did not use the inner class and made your class a separate file, and the methods are static.

So be sure that you are safe and true;)

+2
source

Should I worry about a context leak here?

Definitely not.

You pass the context method to the method and do your work right there. You do not even store it or use it later, which could become the root of evil in this case.

+2
source

Source: https://habr.com/ru/post/1258012/


All Articles