Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Context passed into onReceive() of a BroadcastReceiver?

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.

like image 281
Daniel Avatar asked Aug 05 '14 06:08

Daniel


1 Answers

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.

like image 146
Pankaj Kumar Avatar answered Oct 08 '22 00:10

Pankaj Kumar