Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BroadcastReceiver does not save local variable

In my application I have a BroadcastReceiver which looks something like this:

public class MyBroadcastReceiver extends BroadcastReceiver
{
    public static final String CUSTOM_BROADCAST_1 = "com.cilenco.application1";
    public static final String CUSTOM_BROADCAST_2 = "com.cilenco.application2";

    private boolean lastState = false;

    @Override
    public void onReceive(Context context, Intent intent) 
    {
        final String action = intent.getAction();

        boolean cb1 = CUSTOM_BROADCAST_1.equals(action);
        boolean cb2 = CUSTOM_BROADCAST_2.equals(action);

        if(cb1) lastState = true;
        else if(cb2) lastState = false;

        Toast.makeText(context, "" + lastState, Toast.LENGTH_LONG).show();
    }
}

Now my problem is that every time I receive a Broadcast the variable lastState is allways false. I'm sure that the onReceive method is called correctly. Do you have any ideas why that is? To me it looks like the BroadcastReceiver is reinitialize every time when it receives a Broadcast. Is that right and if yes how can I avoid this problem? My BroadcastReceiver is registerd in the manifest like this:

<receiver 
    android:name="service.MyBroadcastReceiver"
    android:enabled="true"
    android:exported="false" >
    <intent-filter>
        <action android:name="com.cilenco.application1"/>
        <action android:name="com.cilenco.application2"/>
    </intent-filter>
</receiver>
like image 821
Cilenco Avatar asked Sep 18 '25 02:09

Cilenco


1 Answers

BroadcastReceivers are not saved between broadcasts. Every broadcast will create a new instance of the BroadcastReceiver, at least if registered automatically via the manifest. You can work around this by making the variable static and sharing it between all instances of the class. But you can't save instance variables between broadcasts.

like image 51
Gabe Sechan Avatar answered Sep 20 '25 18:09

Gabe Sechan