Search code examples
androidbroadcastreceiver

Life Span of Android broadCastReceiver


I Have instance variables in my Android BroadCastReciver. The Receiver is defined through the manifest file.

for example something like this:

public class MyPhoneStateReceiver extends BroadcastReceiver {

String myString="string one";


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

myString= "string two";

}

//and here is the manifest definition

<receiver android:name="mypackage.receivers.MyPhoneStateReceiver" android:enabled="true">
            <intent-filter>
                <action android:name="android.intent.action.NEW_OUTGOING_CALL" />
                <action android:name="android.intent.action.PHONE_STATE" />
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>

Now lets imagine i recieve the very first intent now the myString variable will be two. But on the next event i receive will my instance variable be remembered or does it start initialized with "string one". So really what i am asking is is the broadcastReciever instantiated everytime a new event occurs or does it keep its state ? Also if it can lose state what other then a reboot could make it lose state ?


Solution

  • ...is the broadcastReciever instantiated everytime a new event occurs or does it keep its state ?

    A new instance of the BroadcastReceiver class will be created for each broadcast it's registered to receive. Your myString variable will be initialized to "string one", and will have that value at the start of each onReceive() execution.

    Also if it can lose state what other then a reboot could make it lose state ?

    I'm not quite sure what you mean, here, but any non-static members will not retain state from instance to instance, just like any other Object class. static members may retain state between broadcasts, but you shouldn't rely on that, as your process can be killed at any time. Rather, use some form of persistent storage, such as SharedPreferences, or standard Files.