没有上下文如何访问SharedPreferences

17

我已经阅读了有关读取SharedPreferences的问题:这个这个。但是它们仍然需要Context才能访问SharedPreferences。我想知道如何在没有Context的情况下访问SharedPreferences。提前感谢您。


6
你根本“无法”做到,但只要你的应用程序在运行,就会有一个可供使用的“应用程序上下文”…… - K-ballo
你不能这样做。它需要上下文。 - Cruceo
如果您能详细说明为什么需要那样做,也许我们可以更好地帮助您。 - Erol
我很久以前建立了自己的库,里面充满了静态方法。但现在,我想修改那个库以保存一些用户首选项。我可以在每个静态方法调用时传递上下文,但这将迫使我重构应用程序中的整个类。 - Niyoko
@K-ballo:如何获取<i>ApplicationContext</i>? - Niyoko
我认为你不需要重构代码。在你的类中,使用getApplicationContext()方法并将其存储为静态类变量。然后,在使用SharedPreferences的静态方法中使用这个Context变量。 - Erol
4个回答

15

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


8

应用程序类:

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;
    }

}

在AndroidManifest中声明应用程序:

<application android:name=".MyApplication"
    ...
/>

使用方法:

PreferenceManager.getDefaultSharedPreferences(MyApplication.getAppContext());

11
上下文是一个大数据,它不适合作为静态对象(会出现内存泄漏等问题)。 - Abbas Torabi
1
如果没有上下文,就无法生成SharePrefs。 - Ivor

5
我们可以创建一个SharedPreference实例并在带有Getter和Setter的辅助类中使用,而不需要涉及上下文。具体内容请参考这里
MainActivity中添加:
public static SharedPreferences preferences;
preferences = getSharedPreferences( getPackageName() + "_preferences", MODE_PRIVATE);

然后在 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,"");
}

0
Oded的回答为我的实用类中的回调方法提供了所需的内容。在我的情况下,我需要一个Kotlin版本,它看起来像这样。
清单
android:name=".SGAutoApp"

SGAutoApp.kt

class SGAutoApp : Application() {
    companion object {
        fun getAppContext(): Context {
            return this.getAppContext()
        }
    }
}

然后在我的实用程序类回调方法中就像下面这样。

            val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(SGAutoApp.getAppContext())

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接