[英]What is the Context passed into onReceive() of a BroadcastReceiver?
What is the context that is passed int the onReceive
method of a BroadcastReciver
: 在
BroadcastReciver
的onReceive
方法中传递的上下文是什么:
public void onReceive (Context context, Intent intent)
According to the official documentation : 根据官方文件 :
The Context in which the receiver is running.
接收器运行的上下文。
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 对于bynamic接收器(注册成活动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 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 . 因此,当文档中的语句表明接收器正在运行的上下文时 。
It is an application context . 这是一个应用程序上下文。 Same one that you get with method
与方法相同的一个
getApplicationContext()
But: 但:
This instance is a ReceiverRestrictedContext with two main functions disabled; 此实例是ReceiverRestrictedContext,禁用了两个主要功能; calling registerReceiver() and bindService().
调用registerReceiver()和bindService()。 These two functions are not allowed from within an existing BroadcastReceiver.onReceive().
现有的BroadcastReceiver.onReceive()中不允许这两个函数。 Each time a receiver processes a broadcast, the Context handed to it is a new instance.
每次接收者处理广播时,传递给它的上下文都是一个新实例。
使用getApplicationContext()
将上下文发送到onReceive方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.