Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onReceive called many times

I have a service that get data from an other application.

When I get date I send message to broadCast in order to refresh the UI.

The onReceive method is called many times and data displayed multiple times.

this is my code:

DataService.java

if(sizeLat == 1) {
                                       
   sendMessage("Alerte1;");
                                    
}
else {

   sendMessage("Alerte2;");
}


 private void sendMessage(String message) {
    Log.w("","==> send message");
    Intent intent = new Intent("my-event");
    // add data
    intent.putExtra("message", message);
    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
 }

MainActivity.java

// handler for received Intents for the "my-event" event 
    private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
      @Override
      public void onReceive(Context context, Intent intent) {
          
                      
      Log.e("","Onreceiver");
      String message = intent.getStringExtra("message");
    
        
        if(message.equals("Alerte1")){
      parentItems.add(message);
      adapter.notifyDataSetChanged();
         }}};

@Override
  protected void onResume() {
    Log.d(TAG, "On Resume");
    super.onResume();
    
    // Register mMessageReceiver to receive messages.
    
    LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
            new IntentFilter("my-event"));}

How can I resolve the problem ?

like image 483
Wafae Avatar asked Oct 19 '25 15:10

Wafae


2 Answers

Put broadcast register line in onCreate and unregister it in onDestroy() method. The line which you have to move from onResume() to onCreate is:-

LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
            new IntentFilter("my-event"));}
like image 66
Pankaj Avatar answered Oct 21 '25 05:10

Pankaj


Possibly, you have two instances of the activity living at the same time. Make a breakpoint on the message receiver and check the address of the instance of your activity class and see if they are different each time the onReceive is called.

There are a few reasons why you could have two instances living at the same time, but one of the most common is leaking context within the activity. More on this topic.

like image 27
Jose L Ugia Avatar answered Oct 21 '25 03:10

Jose L Ugia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!