Broadcast receiver onReceive() is not called

旧城冷巷雨未停 提交于 2021-01-29 04:16:49

问题


Broadcast receiver

 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)

This is how I am sending broadcast

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

This code is working fine till last night. I am not able to debug what is going wrong?


回答1:


Try Like this

In your activity Inside onCreate method declare

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

Then implement the MyBroadcastReceiver in Activity

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

Send the Broadcast like this

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


来源:https://stackoverflow.com/questions/43489963/broadcast-receiver-onreceive-is-not-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!