简体   繁体   中英

android BroadcastReceiver called twice

i am working on chat project

what i did here is service with the connection staff and i set a broadcast receiver to get the data from the service

this is the receiver code

mMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                final String code = intent.getExtras().get("code").toString();
                final JSONObject Message = new JSONObject(intent.getExtras().get("msg").toString());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.d("test","test");
                    }
                });
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,new IntentFilter("data"));

the problem is when i close the activity the code inside runOnUiThread called more than one time

if i close the activity and open it it called 2 times if i did it again it called 3 times and so on

You need to unregister the broadcast receiver after your activity is paused. in onPause() method of your activity. LocalBroadcastManager.getInstance(this).unregisterReceiver(m‌​MessageReceiver)

The correct way for using LocalBroadcastManager is as follows:

 public static String REPORTBOOK_BROADCAST = "REPORTBOOK_BROADCAST";

    @Override
    protected void onResume() {
        super.onResume();
        recreateLists();
        LocalBroadcastManager.getInstance(mContext).registerReceiver(reportBookReceiver, new IntentFilter(REPORTBOOK_BROADCAST));
    }

    @Override
    protected void onPause() {
        super.onPause();
        LocalBroadcastManager.getInstance(mContext).unregisterReceiver(reportBookReceiver);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LocalBroadcastManager.getInstance(mContext).unregisterReceiver(reportBookReceiver);
    }

In this way LocalBroadcastManager will be called only once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM