I have developed an application which makes use of a toggle button to decide the enabling/disabling of my app. I store the toggle button state as a static variable so that it retains it value on stop and resume. However on a reboot, the static variables will be reinitialised into its default state. Is there any way I can get my app to resume its state even after a reboot?
Specifically, what my app does is that on toggle On it enables a "Service". SO I want that service to be started automatically on a phone reboot. Is that possible?
Thanks
save the variables in SharedPreferences
see how it works, http://developer.android.com/reference/android/content/SharedPreferences.html
then on start of your activity just restore them
not so important but if youre using toggle you may save boolean
tutorial: http://www.vogella.com/tutorials/AndroidFileBasedPersistence/article.html
GL
EDIT: on other Q about services, well dont really know what you made so far but maybe this: Android -Starting Service at Boot Time can help, if not provide some code what you made.
Well,that's possible when you your app starts as the phone reboots.Service will be called via main activity. You can start the app as soon as the phone boots via a broadcastrecievir which looks like this .:-
public class BootUpReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
This needs to be added in AndroidManifest as :-
<receiver
android:name="com.example.xyz.BootUpReceiver"
android:enabled="true" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
Store your variable into SQLite
or SharedPreferences
. Then restore it's state on Activity
restart.
You can store your variables into sharedpreferences, this will be much easier
http://developer.android.com/reference/android/content/SharedPreferences.html
// to save it
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putString("your_key", "your_value");
editor.commit();
//to retrieve it back
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
String your_value= prefs.getString("your_key", null);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.