+-

在BroadcastReciver的onReceive方法中传递的上下文是什么:
public void onReceive (Context context, Intent intent)
根据official documentation:
The Context in which the receiver is running.
最佳答案
一点点研究给出了以下结果……
对于静态接收器
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接收器(注册成活动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的文档.
点击查看更多相关文章
转载注明原文:java – 传递给BroadcastReceiver的onReceive()的Context是什么? - 乐贴网