Reputation: 386
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
Upvotes: 2
Views: 2484
Reputation: 913
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>
Upvotes: 1
Reputation: 1020
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.
Upvotes: 2
Reputation: 8826
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);
Upvotes: 0
Reputation: 2572
Store your variable into SQLite
or SharedPreferences
. Then restore it's state on Activity
restart.
Upvotes: 0