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

蹲街弑〆低调 提交于 2020-01-02 08:04:33

问题


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.


回答1:


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.




回答2:


It is an application context . Same one that you get with method

getApplicationContext()

But:

This instance is a ReceiverRestrictedContext with two main functions disabled; calling registerReceiver() and bindService(). These two functions are not allowed from within an existing BroadcastReceiver.onReceive(). Each time a receiver processes a broadcast, the Context handed to it is a new instance.




回答3:


Use getApplicationContext() to send context to onReceive Method.



来源:https://stackoverflow.com/questions/25132399/what-is-the-context-passed-into-onreceive-of-a-broadcastreceiver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!