Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Context in an Intent Service

Here's the scenario: I have a WakefulBroadcastReceiver that does a backup to a network computer or the cloud. It's set to go off in the middle of the night, when I know the tablet will have access to the LAN. The backup will store the data to a location and a file that was "picked" by the fragment that instantiated the WakefulBroadcastReceiver, using the Storage Access Framework. So I need to be able to access the ContentResolver and to do that I need the context.

From all my reading of the documents, this is what the BroadcastReceiver is meant to be used for - a potentially long running task that should be done in the background when not much else is happening. - Like a backup. I just haven't seen any examples that puts everything together.

How do I get the context in an IntentService? Here is a snippet of the receiver and the scheduling service.

  public class BackupAlarmReceiver extends WakefulBroadcastReceiver {

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

            Intent service = new Intent(context, BackupSchedulingService.class);

        startWakefulService(context, service);

        }
}

public class BackupSchedulingService extends IntentService {
    public BackupSchedulingService() {
        super("BackupSchedulingService");
    }

 @Override
    protected void onHandleIntent(Intent intent) {

        Bundle extras = intent.getExtras(); 
        // How to get the context - it was a parameter when
        // creating the new IntentService class above? 
         }
}

The example code pretty much follows exactly the Android reference manual code here:

https://developer.android.com/reference/android/support/v4/content/WakefulBroadcastReceiver.html

like image 363
user4612159 Avatar asked Feb 26 '15 23:02

user4612159


People also ask

What is Android content context?

Definition. it's the context of current state of the application/object. It lets newly-created objects understand what has been going on. Typically, you call it to get information regarding another part of your program (activity and package/application).

How many types of context are there in Android?

There are mainly two types of Context that are available in Android.


2 Answers

So my question is how do I get the context in an IntentService?

The IntentService is the Context, as IntentService inherits from Context.

like image 149
CommonsWare Avatar answered Oct 16 '22 08:10

CommonsWare


Just call getApplicationContext()

like image 37
kleinsenberg Avatar answered Oct 16 '22 08:10

kleinsenberg