Search code examples
androidbroadcastreceiverandroid-servicealarmmanagerandroid-broadcast

AlarmManager - Am I doing it right?


I had setup AlarmManager in my MainActivity class.

A class called AlarmReceiver gets fired up for every set interval of time.

I have to perform an operation when that class is fired up. That code is in in another class Parsing.java

Now in AlarmReceiver.java, I'm doing this :

public class AlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        Parsing obj = new Parsing(context);

        obj.execute();

    }
}

I cannot write the code directly in AlarmReceiver.java, because AlarmReceiver.java is already extending BroadcastReceiverand my code which is Parsing.java is extending another class.

So, I'm creating an object for Parsing class and calling that method.

Is my approach correct?

I'll furnish further information in case needed. Please let me know if my approach is correct? Thanks in advance!

EDIT:

Parsing.java

public class Parsing extends AsyncTask<Void, Void, Void> {

//some code

}

Solution

  • Starting an AsyncTask from a BroadcastReceiver is wrong for two reasons:

    1. The thread on which onReceive() runs is terminated after the method returns, effectively ending any long-running task which may have been started from there. To quote the official docs:

    A BroadcastReceiver object is only valid for the duration of the call to onReceive(Context, Intent). Once your code returns from this function, the system considers the object to be finished and no longer active ..... anything that requires asynchronous operation is not available, because you will need to return from the function to handle the asynchronous operation, but at that point the BroadcastReceiver is no longer active and thus the system is free to kill its process before the asynchronous operation completes.

    2. The Context instance that onReceive() provides is not the same as the Context of an Activity or Service, i.e. Activity.this or Service.this. You need that proper Context for performing many of the common useful operations that we usually do from an Activity or Service. So, for example, the correct way to start a Service in
    onReceive() is:

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent i = new Intent(context.getApplicationContext(), ParsingService.class);
        context.getApplicationContext().startService(i);
    }
    

    and not

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent i = new Intent(context, ParsingService.class);
        context.startService(i);
    }