Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing parameters to the BroadcastReceiver

I'm trying to pass an int value from my Service to the CallReceiver class, unfortunately the CallReceiver.value always equals 0, even after set with another value. When I'm trying to pass it as a parameter to the constructor situation is exactly the same, and so with the setter methods called from service. Is there really no way to pass there any data?

Service:

SharedPreferences settings = getSharedPreferences("SETTINGS", 0);
    int value = settings.getInt("value1", 0); // here the correct value is present, not 0.
    CallReceiver mCallReceiver = new CallReceiver();
    CallReceiver.value = value;  

Receiver:

public class CallReceiver extends BroadcastReceiver  {

public int value;

public CallReceiver(int value)  {
    this.value = value;
}

public CallReceiver()   {

}


@Override
public void onReceive(Context context, Intent intent) {


            Log.v("value", String.valueOf(value)); // here "value" = 0.


        }

     }
like image 515
XorOrNor Avatar asked Jan 17 '13 15:01

XorOrNor


1 Answers

Your CallReceiver mCallReceiver=new CallReceiver(); instance is not used for receiving intents. Instead, Android creates new instance each time. And 0 is the default value for uninitialized integer variables.

To make sure this is what happens, assign some default value to your value field:

public class RReceiver extends BroadcastReceiver {
    public int value=5;
    //...
}

and your value will always be equal 5.

As for passing data to BroadcastReceiver, add it as extra to the Intent you are broadcasting:

//in your service
Intent broadcastedIntent=new Intent(this, CallReceiver.class);
broadcastedIntent.putExtra("VALUE", 100500);
sendBroadcast(broadcastedIntent);

And then, in your CallReceiver:

@Override
public void onReceive(Context context, Intent intent) {
    int value=intent.getIntExtra("VALUE", 0);
}
like image 145
Andrii Chernenko Avatar answered Sep 29 '22 15:09

Andrii Chernenko