0

When I am working with broadcast receivers, I get a little confused about methods like sendBroadcast and registerReciever. Both gives the same result, and working functionality are also the same. But, what is the reason behind to work with both?

For example, If I try to get the result of my battery level, I am using the coding like

public void onButtonClick(View view)
{
IntentFilter intentFilter=new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
BraodcastReceiver br=new BroadcastReceiver();
registerReceiver(br,intentFilter);
}

or

public void onButtonClick(View view)
{
Intent intent=new Intent(Intent.ACTION_BATTERY_CHANGED);
sendBroadcast(intent);
}

What are the differences between this two methods? How they will work? Can you please give me the reasons?

My BroadcastReceiver class:

public class MyBroadcastClass extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        int level= intent.getIntExtra(BatteryManager.EXTRA_LEVEL,0);
       Log.d("BatteryLevel",level);

    }
}  
Felipe
  • 150
  • 1
  • 16
sreeku24
  • 320
  • 3
  • 5
  • 16
  • http://stackoverflow.com/questions/18842517/broadcast-receiver-class-and-registerreceiver-method – Vinodh Dec 05 '16 at 05:49

2 Answers2

3

First of all you have to understand what is broadcast receiver in android.

This one example

I will explain shortly.

The first example is registering as the name indicates. So after registering a particular broadcast , it will listen for any broadcast with that ACTION you provided with intentFilter. The working is same as the callback mechanism.

The second example is sending broadcast . Sending broadcast means you broadcast something, say battery change(OS Level) ,It will broadcast with an ACTION.

SO send broadcast will send some data with Action , if we listen a broadcast with Action then it will trigger on BroadcastRecicver class

noobEinstien
  • 3,147
  • 4
  • 24
  • 42
1

I suggest you to go through the developer docs https://developer.android.com/reference/android/content/BroadcastReceiver.html

you will get the clear idea.

coming to your question

registerReceiver() is used to register your broadcast receiver to a particular action eg- Intent.ACTION_BATTERY_CHANGED or you can define your own.

What it mean is that whenever any APP will send a broadcast (send using a sendBroadcast() method) to this action your broadcast receivers onReceive() method will get called.

Gaurav
  • 3,615
  • 2
  • 27
  • 50