BroadcastReceiver设置自己的上下文

时间:2017-05-30 06:15:21

标签: android android-broadcast android-broadcastreceiver

可以在创建broadcastreceiver之后设置自己的上下文:?

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,是否有任何解决方案?

2 个答案:

答案 0 :(得分:0)

试试我的朋友

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);

答案 1 :(得分:0)

问题在于在清单中声明接收器,而它应该只在片段中声明,在更改它之后,一切都按预期工作。 谢谢你的帮助。