Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Basics of LocalBroadcastManager

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 170
    Comment on it

    If you want to send broadcasts within your application, LocalBroadcastManager is a more suitable option than sending global broadcast as:

    1. The broadcasts sent by  LocalBroadCastmanager  can only be recieved inside the application so you don't have to care about security related issues such as leaking of private data.
    2.Also, other apps can't send these type of broadcast so another security concern i.e a security hole is avoided.
    3.It is more efficient.

    Here's how to create and send a broadcast via LocalBroadCastmanager:

     

    Create a BroadcastReciever

    // handler for received Intents for the "event_local_broadcast" event
    private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
    
        //Do something
    
        }
    };

    Register it on onResume()  and unregister it on onPause()

    @Override
    protected void onResume() {
        super.onResume();
      
        // Register mMessageReceiver to receive messages.
        LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
                new IntentFilter("event_local_broadcast"));
    
    }
    @Override
    protected void onPause() {
        super.onPause();
        // Unregister since the activity is not visible
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
        super.onPause();
    }

    Now to send a broadcast add this following code:

    Intent intent = new Intent("event_local_broadcast");
    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

    When the sendBroadcast() method is called, onRecieve() method of all the registered BroadcastReceiver inside the application will be called.

    Hope it helps! :)

     

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: