Search code examples
androidgoogle-mapsbroadcastreceiver

sending broadcasts to activity having google map register/unregister best places?


My Application has a main screen containing a map ,it also contains several other screens And around 3 services sending broadcast updates to the map(polylines , markers ...).

the map updated by broadcasts from the services for register/unregister of the broadcasts i have two options :

1-register/unregister broadcast on onPause/onResume

PROS :only when the map is visible it can receives updates

CONS:when the map goes to the background and there are several updates i will need to do them all onResume which can cause some slowness in the application

2-register/unregister broadcast on onCreate/onDestroy

PROS:the map is always up to date regardless of which screen you are in

CONS:i am not sure if this will cause memory problems or any other unforeseen issues

As for the fact that the onDestroy might not be called for sometime i already took that in to consideration , and designed the application in a way that if "the application" not in foreground anymore it will shutdown all the services after 30 sec.

what is the best way to handle this ?


Solution

  • The LocalBroadcastManager class is used to register for and send broadcasts of Intents to local objects within your process. This is faster and more secure as your events don't leave your application.

    The following example shows an activity which registers for a customer event called my-event.

    @Override
    public void onResume() {
    super.onResume();
    
       // Register mMessageReceiver to receive messages.
       LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
         new IntentFilter("my-event"));
    }
    
    // handler for received Intents for the "my-event" event 
    private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
       // Extract data included in the Intent
       String message = intent.getStringExtra("message");
       Log.d("receiver", "Got message: " + message);
     }
    };
    
    @Override
    protected void onPause() {
       // Unregister since the activity is not visible
       LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
       super.onPause();
    } 
    // This method is assigned to button in the layout
    // via the onClick property
    public void onClick(View view) {
       sendMessage();
    }
    
    // Send an Intent with an action named "my-event". 
    private void sendMessage() {
      Intent intent = new Intent("my-event");
      // add data
      intent.putExtra("message", "data");
      LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }