Initially i set myself a simple task to make a function to execute with delay. At first i made a runnable and executed it with new Thread(runnable).start();
, but i've read, that non-static inner classes can lead to memory leaks, so i tried to make Runnable
as static.
I followed example in Is this Runnable safe from memory leak? and ended with this code:
public class ApproxManager {
private Context mContext;
private AlarmManager mAlarmManager;
public ApproxManager(Context context){
mContext = context;
mAlarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
}
public void setPeriod(int type, long when, int extendCount){
Intent i = new Intent(mContext, OnAlarmReceiver.class);
long alarmtime = when;
i.putExtra(RReminder.PERIOD_TYPE, type);
i.putExtra(RReminder.EXTEND_COUNT, extendCount);
i.setAction(RReminder.CUSTOM_INTENT_APPROXIMATE_PERIOD_END);
PendingIntent pi = PendingIntent.getBroadcast(mContext, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
new Thread(new WeakRunnable(mContext, alarmtime,pi)).start();
}
public void setAlarm(long alarmTime, PendingIntent pi){
mAlarmManager.set(AlarmManager.RTC_WAKEUP, alarmTime, pi);
}
private static final class WeakRunnable implements Runnable {
private final WeakReference<Context> mContext;
long mAlarmtime;
PendingIntent mpi;
protected WeakRunnable(Context context, long alarmtime, PendingIntent pi){
mContext = new WeakReference<Context>(context);
mAlarmtime = alarmtime;
mpi = pi;
}
@Override
public void run() {
Context context = mContext.get();
if (context != null) {
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
ApproxManager approxManager = new ApproxManager(context);
approxManager.setAlarm(mAlarmtime,mpi);
}
}
}
}
I am unfamiliar with inner classes and referencing, so despite my code appears to be working, i am not sure, if i have suceeded with my goal to avoid memory leaks. So i would appreciate if someone could look at my code.