Save variable value

My application has only one service class (not activity), in which I save the value of one variable, dynamically calculated by one method. Then I need to save this value for further comparison. For instance:

class MyClass extends Service{ static int number1; private void Method(){ int number 2; /// some calculations for number2 /// if number2 != number1 { number1 = number2 } } 

I need to compare this variable (number1) with some other variable (number2) that my application computed. This works well, but when the Android OS kills my service and launches this service for a specific purpose (even after rebooting the phone), the value of number1 is lost, and I can not use it for comparison. So how to do this? I was thinking of writing a simple TXT file in which I could save the value of number1 after killing the service,

Is there another way?

+4
source share
2 answers

The fastest way is to store the value of the variable in SharedPreferences and get it for later use.

For instance:

 public class Calc extends Activity { public static final String PREFS_NAME = "MyPrefsFile"; @Override protected void onCreate(Bundle state){ super.onCreate(state); . . . // Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); boolean silent = settings.getBoolean("silentMode", false); setSilent(silent); } @Override protected void onStop(){ super.onStop(); // We need an Editor object to make preference changes. // All objects are from android.context.Context SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("silentMode", mSilentMode); // Commit the edits! editor.commit(); } } 

this code is taken from the Android developers page , which is intended for Activity, but you can easily adapt it in your service by changing it

+3
source

You must save this value in a file or database, since Android users usually monitor services and applications and can close the service so save it in the database, and then when your service is running, you can check the saved value.

+1
source

Source: https://habr.com/ru/post/1395923/


All Articles