如何在Activity之外使用sharedPreferences?

Cod*_*ate 10 android mvvm

我已经坚持这个非常简单的问题几个小时了,我一直无法通过谷歌找到任何合适的解决方案.

我试图在我的应用程序的模型层中使用SharedPreferences类.具体来说,我希望能够在应用程序启动时保存或获取用户名和相应的令牌(如果用户将应用程序设置为自动登录).

有没有办法让我使用SharedPreferences来解决这个问题,还是我被迫使用FileInput/Output?

Blu*_*ell 28

你在哪里实例化你的Model类?

只需将上下文或SharedPreferences传递给构造函数:

public class Model {
    private final Context context;
    private final SharedPreferences sharedPrefs;

    public Model(Context context) {
        this.context = context;
        sharedPrefs = context.getSharedPreferences("name", 0);
    }

    private String doSomething(){
        return sharedPrefs.getString("key", "defValue");
    }
}
Run Code Online (Sandbox Code Playgroud)


MBy*_*ByD 5

SharedPreferences不仅从 from 调用Activity,还从 from Context(Activity扩展)调用,因此您也可以使用应用程序上下文。