3

I am working on a service that can start at device boot completion, i am setting a preference file to store service running state so i can retrieve it when i need it, in my broadcast receiver :

public class MyServiceBootReceiver extends BroadcastReceiver {
public MyServiceBootReceiver() {super();}

@Override
public void onReceive(Context context, Intent intent) {
    if(intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
        if(MyService.isRunning(context)) //static method to get shared preferences value
        context.startService(new Intent(context, MyService.class));
    }
}

}

Now i am confused about the "context" parameter in onReceive() method, since the application and all its components will be destroyed when device is shutdown, which context is passed in the receiver, and wich component of my application is actually receiving it ?

Ankita Shah
  • 1,866
  • 16
  • 31
Altaiir
  • 477
  • 1
  • 5
  • 16
  • As the documentation says (https://developer.android.com/reference/android/content/BroadcastReceiver.html#onReceive(android.content.Context, android.content.Intent)) _Context: The Context in which the receiver is running._ – fsnasser Nov 25 '16 at 11:09
  • on boot nothing of my app components are running no ? except if android os is keeping some reference to my app even when it's destroyed ! – Altaiir Nov 25 '16 at 11:15

1 Answers1

4

Before calling your BroadcastReceiver, Android will create your app's Application context. You can actually see this happenning if you have your own class that inherits Application and put up a Log on it's onCreate.

However, the context you receive in your Receiver is restricted: it cannot call registerReceiver() or bindService().

More information about different types of contexts can be found here.

BMacedo
  • 768
  • 4
  • 10
  • ok , but on device boot, is application context still kept somehow by android system ? – Altaiir Nov 25 '16 at 11:20
  • The application context is destroyed when Android removes your app from the background, meaning that when the device restarts, your app's context is also destroyed. – BMacedo Nov 25 '16 at 11:33
  • exactly, so what is that context is ? note please that the code is working great, tested on device many times and working , so that context can actually access my "MODE_PRIVATE" shared preference file and get if service was running and restarts it. – Altaiir Nov 25 '16 at 11:36
  • 1
    Like I said in the answer, Android recreates your application context before calling your broadcast receiver. That's why it works. – BMacedo Nov 25 '16 at 11:43
  • it's ok now , as a beginner i want to do things right thank you for the answer – Altaiir Nov 25 '16 at 12:51