如何在Android中的整个应用程序中进行全局更改?

ask*_*ask 1 android global

我的应用程序中有一个设置菜单,用于控制整个应用程序中使用的单位 - 公制或美制单位.因此,当用户在菜单中的选项中选择其中一个时,我希望我的应用程序在显示和计算过程中使用所选单位.

我计划通过在sharedpreferences中存储布尔值来执行此操作,然后在每次打开活动时检查布尔值,然后进行适当的更改.

有没有更好的方法来做这个?

谢谢

Ven*_*nky 5

是的,您可以使用Getter和setter 扩展Applications类并将数据存储在那里.

这样您的数据将在整个应用程序中保留.

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;
}
}
Run Code Online (Sandbox Code Playgroud)

在Activity中访问它,如:

  SocketManager socketManager = SocketManager.getInstance(this);
  socketManager.setState(10);
  socketManager.getState();
Run Code Online (Sandbox Code Playgroud)

将您的应用程序添加到Maanifest文件,如下所示:

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

   <activity .... />

 </application>
Run Code Online (Sandbox Code Playgroud)

编辑:

您应该添加将Application扩展到Application Tag而不是Activity Tag的类名

如需进一步参考,请查看此链接