How do I make global changes throughout my app in

2019-01-26 02:06发布

问题:

I have a settings menu in my app which controls the units used throughout the app - metric or US units. So when the user selects one of these in the options in the menu, I want my app to use the chosen units throughout in display and calculations.

I plan to do this by storing a boolean in sharedpreferences, then check the value of the boolean every time an activity is opened, and then make the appropriate changes.

Is there a better method to go about doing this?

Thanks

回答1:

Yes you can extends Applications class and store your data over there using Getter and setter.

So that your data will be retained throughout the Application.

public class SocketManager extends Application {
private static SocketManager singleton;
public int mBluetoothState;


public synchronized static SocketManager getInstance(Context context) {
    if (null == singleton) {
        singleton = new SocketManager();
    }
    return singleton;
}

public synchronized void setState(int state) {
    mBluetoothState = state;
}

public synchronized int getState() {
    return mBluetoothState;
}
}

Access it in Activity like :

  SocketManager socketManager = SocketManager.getInstance(this);
  socketManager.setState(10);
  socketManager.getState();

Add your Application to Maanifest file like this :

 <application
  android:name=".SocketManager"
  android:icon="@drawable/first_aid"
  android:label="@string/app_name" >

   <activity .... />

 </application>

Edit :

You should add your class name that extends Application into Application Tag not on Activity Tag

For further refrence check this link



回答2:

You can have a look at Android Storage options: http://developer.android.com/guide/topics/data/data-storage.html

However, it seems like for your case SharedPreferences is OK



回答3:

For just a boolean? If its just a single activity calling SharedPreferencesand assigning it would be fine.

If you have multiple activities in an application you could call it once and load it into a static class and call it that way or subclass the Application class.

But even then it's just a boolean and you should do whatever is most convenient for you.