I have an SMS broadcast receiver in my application with a static boolean value to make the receiver active or not.
public class SmsListener extends BroadcastReceiver {
public static boolean activated = false;
@Override
public void onReceive(Context context, Intent intent)
if (activated){ //do something
}
...
}
}
I have then a widget to activate or not the sms receiver (through this static value). Everything works well but I just noticed that, if the phone memory gets low, the sms listener loses its state and the application doesn't work as expected. I guess it is related to android lifecycle. I have no service in backgr开发者_开发问答ound and the system kills the process. Should the approach I used be avoided? Should I always start a service only to avoid android process kill?
Thanks
Tobia Loschiavo
The only reliable way I have found to have globals is to put them in a service. The Android way is to use onSaveInstanceState and then recover state in all the various methods that may or may not be called with that state. Even that is not completely reliable, so you can also write state to preferences when in onPause and read them in onResume.
Note also that depending on your manifest anything can kill your activity, such as opening the keyboard or rotating the phone, not just low memory.
精彩评论