【发布时间】:2017-05-30 06:15:20
【问题描述】:
是否可以像这样创建广播接收器后设置自己的上下文:?
public class MyFragment extends Fragment(){
Button myButton;
@Override
onCreate {
myButton = (Button) findview...
myButton.setOnClickListner(myListener);
}
.
.
.
MyListener {
@Override
OnClickListner {
MyBroadCastReceiver receiver = new MyBroadCastReceiver()
receiver.setContext(mContext)
}
}
public static class MyBroadcastReceiver extends BroadcastReceiver {
Context mContext;
void setContext(Context context) {
mContext = context;
}
@Override
public void onReceive(Context context, Intent intent) {
if (mContext!= null){
log.d(TAG, "Context not null")
}
}
}
每次调用 onReceive 方法时,我的 mContext 都是 null,有什么解决方案吗?
【问题讨论】:
-
你能告诉我你想用那个上下文做什么吗?打开一个活动还是什么?
-
当然,我想使用 DialogFragment,这就是我尝试获取与 Activity 相关的上下文的原因。
-
请告诉我们您为什么需要活动上下文。一般来说,您不能假设调用接收者时 Activity 仍然存在,因此您不能安全地向其传递 Activity 上下文。这就是为什么它通过了自己的。唯一的例外是当接收者在活动中注册和取消注册时,它通常是一个匿名子类,只根据需要访问活动。
-
Gabe Sechan 感谢重播,我忘记写了。 MyBroadcastReceiver 是 Fragment 的内部类,它只在该 Fragment 存在时才存在(已注册和未注册)。
-
我同意 Gabe 的观点,但如果您仍想以这种方式处理,请尝试将值传递给 Intent,然后您可以打开任何您得到的内容,例如。如果你想打开 Mainactivity 及其方法传递它的意图,我知道这不是好方法,但它可能会工作
标签: android android-broadcast android-broadcastreceiver