Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Am I leaking Context?

Tags:

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?

like image 489
justanoob Avatar asked Oct 11 '16 09:10

justanoob


1 Answers

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

like image 91
Amir Ziarati Avatar answered Sep 24 '22 17:09

Amir Ziarati