【问题标题】:BroadcastReceiver setting own contextBroadcastReceiver 设置自己的上下文
【发布时间】: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


【解决方案1】:

我的朋友试试这个

public class MyReceiver extends BroadcastReceiver {
        Context mContext;

         public MyReceiver() {
        super();
       }

        @Override
        public void onReceive(Context context, Intent intent) {
            mContext = context;
            if (mContext != null) {
                log.d(TAG, "Context not null")
            }else{
            log.d(TAG, "  null Context ")
               }
        }
    }

像这样创建广播的新对象

MyReceiver receiver = new MyReceiver(this);

【讨论】:

  • 嗨,感谢重播,但这只会将 mContext 从 onReceive 方法参数更改为上下文,我不想要这个上下文,我真的需要 Activity 上下文。
  • 从活动中调用您的广播并传递例如 MainActivity.this 作为上下文
  • 当我尝试这样做时,我收到消息说 BroadCastReceiver 必须具有默认构造函数。
  • 据我了解,您建议创建两个构造函数:1. 默认,调用 super() 2. 以上下文作为参数对吗?
  • 是的兄弟@Nimdokai
【解决方案2】:

问题在于在清单中声明接收者,而它应该只在片段中声明,在更改它之后,一切都可以正常工作。 感谢您的帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-26
    • 1970-01-01
    • 2020-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多