What is the context that is passed int the onReceive
method of a BroadcastReciver
:
public void onReceive (Context context, Intent intent)
According to the official documentation:
The Context in which the receiver is running.
A little research gives below result...
For static receiver
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.e("PANKAJ", "Context class " + context.getClass().getName());
Log.e("PANKAJ", "Application Context class "
+ context.getApplicationContext().getClass().getName());
}
}
I got below log
08-05 06:51:33.448: E/PANKAJ(2510): Context class android.app.ReceiverRestrictedContext
08-05 06:51:33.448: E/PANKAJ(2510): Application Context class android.app.Application
For bynamic receiver (registered into an Activity MainActivity) like
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
public void onReceive(android.content.Context context, Intent intent) {
Log.e("PANKAJ", "Context class " + context.getClass().getName());
Log.e("PANKAJ", "Activity Context class "
+ MainActivity.this.getClass().getName());
Log.e("PANKAJ", "Application Context class "
+ context.getApplicationContext().getClass().getName());
}
};
I got below log
08-05 06:53:33.048: E/PANKAJ(2642): Context class com.example.testapp.MainActivity
08-05 06:53:33.048: E/PANKAJ(2642): Activity Context class com.example.testapp.MainActivity
08-05 06:53:33.048: E/PANKAJ(2642): Application Context class android.app.Application
So when it make true the statement given into documentation that The Context in which the receiver is running.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With