在没有上下文的情况下访问SharedPreferences

Niy*_*wan 12 android

我已阅读的问题:这个这个有关读取共享偏好.但是他们仍然需要Context才能访问SharedPreferences.我想知道如何在没有上下文的情况下访问SharedPreferences.提前致谢

Niy*_*wan 13

我通过首先检索ApplicationContext(this)来解决我的问题,然后使用该上下文来获取SharedPreferences.谢谢K-ballo.


Cod*_*Spy 6

我们可以在具有 Getters 和 Setters 的辅助类中使用 SharedPreference 实例,而不涉及此处解释的上下文

MainActivity中添加

public static SharedPreferences preferences;
preferences = getSharedPreferences( getPackageName() + "_preferences", MODE_PRIVATE);
Run Code Online (Sandbox Code Playgroud)

然后在PreferenceHelper中使用 set 和 get 作为

public static void setName(String value) {
    MainActivity.preferences.edit().putString(KEY_DEMO_NAME, value ).commit();
}
public static String getName() {
    return MainActivity.preferences.getString(KEY_DEMO_NAME,"");
}
Run Code Online (Sandbox Code Playgroud)


Ode*_*ner 5

应用类别:

import android.app.Application;
import android.content.Context;

public class MyApplication extends Application {

    private static Context mContext;

    public void onCreate() {
        super.onCreate();
        mContext = getApplicationContext();
    }

    public static Context getAppContext() {
        return mContext;
    }

}
Run Code Online (Sandbox Code Playgroud)

在AndroidManifest中声明应用程序:

<application android:name=".MyApplication"
    ...
/>
Run Code Online (Sandbox Code Playgroud)

用法:

PreferenceManager.getDefaultSharedPreferences(MyApplication.getAppContext());
Run Code Online (Sandbox Code Playgroud)

  • 上下文是一个大数据,作为静态对象不好(内存泄漏和......) (6认同)