azrosen92
azrosen92

Reputation: 9057

Android AlarmManager and BroadcastReceiver clarfications

I am trying to write an android application that will silence the phone at a certain time, and to do that I am using a combination of an AlarmManager and BroadcastReceiver as per this tutorial. I am using a separate class that will contain the method to set up an event using the AlarmManager so that I can use the method in more than one of my activities. The code for this class is as follows:

public class EventScheduler {

    public static void schedule(Event event) {
        Calendar start = event.getStartTime();
        Calendar end = event.getEndTime();
        String status = event.getStatus();

        Context ctx;

        Intent intent = new Intent(ctx, AlarmReceiver.class);
        intent.putExtra("start_time", start);
        intent.putExtra("end_time", end);
        intent.putExtra("status", status);

        PendingIntent sender = PendingIntent.getBroadcast();
        AlarmManager am = (AlarmManager) getSystemSerivce(ALARM_SERVICE);


    }

    public static void unschedule(Event event) {

    }
}

My first question is about initializing the intent object. Since this method is defined in a class that does not extend Activity it does not have a context (ctx), but this method will be used in classes that do extend Activity, so how would I get the context of those classes to use in the initialization of the intent?

My second question is about initializing the PendingIntent. PendingIntent.getBroadcast() is supposed to take 4 parameters, so again how would I get the context of the class calling this method to use as the first parameter? Also in the documentation it says that the second parameter, the requestCode is not used, does that mean this can be 0?

My third question is about initializing the AlarmManager. Again the ALARM_SERVICE field is from a context object, so what context object would I use in this case?

Upvotes: 0

Views: 1271

Answers (2)

S.A.Norton Stanley
S.A.Norton Stanley

Reputation: 1873

Answering your question on context, you should pass the ApplicationContext and not directly the Activity in case you need the context throughout the applications lifecycle. If you pass your Activity, the GarbageCollector can't remove it from memory when it's no longer needed, which can cause memory leaks. You can get the application context using context.getApplicationContext().

Hope that helps.

Upvotes: 2

ianhanniballake
ianhanniballake

Reputation: 199805

You should pass your Context into each method (in your case, most likely your Activity):

public static void schedule(Context ctx, Event event) {
    // ...
}
public static void unschedule(Context ctx, Event event) {
    // ...
}

And yes, requestCode for PendingIntent.getBroadcast() can always be zero.

Upvotes: 1

Related Questions