Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple Example of using LocalBroadcastManager in Android
import android.app.Activity;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class LocalBroadcastExampleActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.log_list);
Button buttonStartService = (Button)findViewById(R.id.button_ok);
buttonStartService.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Register MessageService in Manifest to work
startService(new Intent(LocalBroadcastExampleActivity.this, MessageService.class));
}
});
}
@Override
protected void onPause() {
// Unregister since the activity is paused.
LocalBroadcastManager.getInstance(this).unregisterReceiver(
mMessageReceiver);
super.onPause();
}
@Override
protected void onResume() {
// Register to receive messages.
// We are registering an observer (mMessageReceiver) to receive Intents
// with actions named "custom-event-name".
LocalBroadcastManager.getInstance(this).registerReceiver(
mMessageReceiver, new IntentFilter("custom-event-name"));
super.onResume();
}
// Our handler for received Intents. This will be called whenever an Intent
// with an action named "custom-event-name" is broadcasted.
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
// Get extra data included in the Intent
String message = intent.getStringExtra("message");
Log.d("receiver", "Got message: " + message);
}
};
public class MessageService extends Service {
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
sendMessage();
return super.onStartCommand(intent, flags, startId);
}
// Send an Intent with an action named "custom-event-name". The Intent
// sent should
// be received by the ReceiverActivity.
private void sendMessage() {
Log.d("sender", "Broadcasting message");
Intent intent = new Intent("custom-event-name");
// You can also include some extra data.
intent.putExtra("message", "This is my message!");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
}
}
@deibid
Copy link

deibid commented Nov 11, 2015

Useful and simple.. Thanks, just what i needed

@sarn
Copy link

sarn commented Nov 26, 2015

Thanks for sharing!

@samboy51
Copy link

samboy51 commented Nov 27, 2015

The code here Has no sense.

How you send local broadcast from service if your service class not embedded in Activity?

LocalBroadcastManager.getInstance(this) - would not work, because "this" is Activity context

I stuck on this problem when tried to send local broadcast from non UI thread

@Antarix
Copy link
Author

Antarix commented Dec 23, 2015

@samboy51 android service has its own context here, you must be calling this from some other class

@dnadeau-quatral
Copy link

dnadeau-quatral commented Feb 2, 2016

Do you have an example of the manifest ?

I tried

            <service
                android:name=".MessageService"
                android:exported="false" />

But it doesn't seems to work.

@rafaelcgo
Copy link

rafaelcgo commented Feb 23, 2016

Thanks for sharing, I was registering the broadcast receiver at onCreate, it was stacking receivers...

@john1jan
Copy link

john1jan commented Apr 27, 2016

Thanks.for this piece

@aravindputrevu
Copy link

aravindputrevu commented May 22, 2016

Perfect one to understand the concept...

@mdalikazi
Copy link

mdalikazi commented Jun 20, 2016

The biggest problem with these receivers is that if you want to receive the broadcast when your activity is Paused or in Background, then you cant do that in a clean way. You have to unregister the receiver in onDestroy not onPause so broadcast can be received when the activity is in the background. Sure, there are ways like using AsyncTask for such things or ForegroundService but it would be nice to have such a functionality for BroadcastReceivers so that you wont have to set up certain parts of the app differently.

Copy link

ghost commented Jun 30, 2016

the above code didnot run for me asswell but it was helpful
here is what i did to make it run below is full tutrial

mainactivity
`package com.javacodegeeks.android.androidserviceexample;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {
private IntentFilter receiveFilter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    receiveFilter = new IntentFilter("custom-event-name");
    LocalBroadcastManager.getInstance(this).
            registerReceiver(handler, receiveFilter);

}

// Start the  service
public void startNewService(View view) {
    Intent intent=new Intent(this,MyService.class);
    intent.putExtra("string","string_value");
    this.startService(intent);
}

// Stop the  service
public void stopNewService(View view) {

    stopService(new Intent(this, MyService.class));
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

private BroadcastReceiver handler = new BroadcastReceiver() {

    int i =0 ;
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d("TAGS", "BroadcastReceiver() {...}.onReceive()");
        Log.d("TAGS", String.valueOf(i));
        i=i+1;
        Toast.makeText(MainActivity.this,
                "Message received", Toast.LENGTH_LONG).show();



    }
`};`

}

`Myservice.java
package com.javacodegeeks.android.androidserviceexample;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service {
public MyService() {
}

@Override
public IBinder onBind(Intent intent) {
    // TODO: Return the communication channel to the service.
    throw new UnsupportedOperationException("Not yet implemented");
}



@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    if (intent !=null){
        Log.d("TAGS_service_data", String.valueOf(intent.getExtras().getString("string")));

    }

    Toast.makeText(this, " Service Started", Toast.LENGTH_LONG).show();

    Log.d("TAGS", "MainActivity.send()");
    //Intent sendableIntent = new Intent(getClass().getName());
    Intent sendableIntent = new Intent("custom-event-name");

    sendableIntent.putExtra("result", "risult");

    LocalBroadcastManager.getInstance(this).
            sendBroadcast(sendableIntent);
    Log.d("TAGS", "sended_data");


    return Service.START_STICKY;

}

@Override
public void onCreate() {
    Toast.makeText(this, "The new Service was Created", Toast.LENGTH_LONG).show();

}

/* @OverRide
public void onStart(Intent intent, int startId) {
// For time consuming an long tasks you can launch a new thread here...
Toast.makeText(this, " Service Started", Toast.LENGTH_LONG).show();

    Log.d("TAGS", "MainActivity.send()");
    //Intent sendableIntent = new Intent(getClass().getName());
    Intent sendableIntent = new Intent("custom-event-name");

    sendableIntent.putExtra("result", "risult");

    LocalBroadcastManager.getInstance(this).
            sendBroadcast(sendableIntent);
    Log.d("TAGS", "sended_data");


}*/

@Override
public void onDestroy() {
    Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();

}

}`

android manifest.xml
add the service name under the application tag

@einverne
Copy link

einverne commented Sep 5, 2016

Better to call super.onPause(); and super.onResume(); at the beginning of method. According this.

@RGU5Android
Copy link

RGU5Android commented Dec 14, 2016

@dnadeau-quatral MessageService is inside Activity. Write the code for MessageService in separate file, do the manifest entry and then it will work properly.

@Antarix Thanks.

@0xtuytuy
Copy link

0xtuytuy commented Apr 7, 2017

Simple and to the point thanks ! 😃

@pishguy
Copy link

pishguy commented Sep 20, 2017

Thanks

@juanmendez
Copy link

juanmendez commented Jan 7, 2018

This is the most self descriptive straight to the core demo.

@chemiadel
Copy link

chemiadel commented Jan 27, 2018

@dnadeau-quatral it should be ".LocalBroadcastExampleActivity$MessageService" , just type . and it will suggest ".LocalBroadcastExampleActivity$MessageService"

@kasarameya
Copy link

kasarameya commented May 24, 2018

Nice work, thanks.

@sinanceylan
Copy link

sinanceylan commented Dec 10, 2018

Thank you

@goodibunakov
Copy link

goodibunakov commented Jun 14, 2020

Thanks! I searched a reason why not working many hours. LocalBroadcastManager.getInstance(this).registerReceiver() - this is an answer! )))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment