广播接收器onReceive()未被调用

时间:2017-04-19 08:06:27

标签: android broadcastreceiver kotlin android-broadcastreceiver

广播接收器

 mBroadcastReceiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context, intent: Intent) {

                Log.i(TAG,"contact list populate broadcast")

                var action = intent.action

                Log.v("Action is ",action)
                when (action) {
                    GetContactListFromServer -> {
                       println("Get contact list")


                    }
                }

            }
        }

        val filter = IntentFilter(GetContactListFromServer)
        this.registerReceiver(mBroadcastReceiver, filter)

这就是我发送广播的方式

val i = Intent(ContactListActivity.Obz.GetContactListFromServer)
i.`package` = mApplicationContext?.getPackageName()
mApplicationContext?.sendBroadcast(i)

这段代码工作正常,直到昨晚。我无法调试出错的地方?

1 个答案:

答案 0 :(得分:1)

尝试这样

在您的活动内 onCreate 方法声明

LocalBroadcastManager.getInstance(context).registerReceiver(MyBroadcastReceiver, new IntentFilter("MyFilter"));

然后在Activity中实现MyBroadcastReceiver

private final BroadcastReceiver MyBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            String Action = intent.getStringExtra("Action");
            switch (Action){
                case "updatedata":
                    String message = intent.getStringExtra("message");
                    String date_time = intent.getStringExtra("date_time");
                    break;

                default:
                    break;
            }
        }
    };

像这样发送广播

Intent intent = new Intent("MyFilter");
intent.putExtra("message", message);
intent.putExtra("date_time", date_time);
intent.putExtra("Action", "updatedata");
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);