【问题标题】:What is the Context passed into onReceive() of a BroadcastReceiver?传递给 BroadcastReceiver 的 onReceive() 的 Context 是什么?
【发布时间】:2014-08-05 06:26:09
【问题描述】:

BroadcastReciveronReceive 方法中传递的上下文是什么:

public void onReceive (Context context, Intent intent)

根据official documentation

接收器运行的上下文。

【问题讨论】:

    标签: java android broadcastreceiver android-context


    【解决方案1】:

    稍作研究得出以下结果...

    对于静态接收器

    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接收器(注册到一个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());
        }
    };
    

    我得到了以下日志

    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.

    【讨论】:

      【解决方案2】:

      它是一个应用程序上下文。与您使用方法获得的相同

      getApplicationContext()
      

      但是:

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

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-11-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多