Java – What is the context of onReceive() passed into BroadcastReceiver?

What is the context of onReceive() passed into BroadcastReceiver?… here is a solution to the problem.

What is the context of onReceive() passed into BroadcastReceiver?

What is the context of the onReceive method passed to BroadcastReciver:

public void onReceive (Context context, Intent intent)

According to official documentation :

The Context in which the receiver is running.

Solution

Some studies have given the following results….

For static receivers

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 the logs below

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 receivers like this (registered to Activity MainActivity).

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 the logs below

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

Therefore, when the declaration in the document is true, The Context in which the receiver is running .

Related Problems and Solutions