什么是传递给BroadcastReceiver的onReceive()的Context?

时间:2014-08-05 06:26:09

标签: java android broadcastreceiver android-context

onReceive的{​​{1}}方法传递的上下文是什么:

BroadcastReciver

根据official documentation

  

接收器正在运行的上下文。

3 个答案:

答案 0 :(得分:5)

一点研究给出了以下结果......

对于静态接收器

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());
    }
}

我得到了以下日志

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

对于bynamic接收者(已注册为活动主要活动),如

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());
    }
};

我得到了以下日志

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

因此,当文档中的语句 The Context in which the receiver is running 时,它会成立。

答案 1 :(得分:1)

这是一个应用程序上下文。与方法

相同的一个
getApplicationContext()

可是:

此实例是ReceiverRestrictedContext,禁用了两个主要功能;调用registerReceiver()和bindService()。现有的BroadcastReceiver.onReceive()中不允许这两个函数。每次接收者处理广播时,传递给它的上下文都是一个新实例。

答案 2 :(得分:0)

使用getApplicationContext()向onReceive方法发送上下文。