从BroadcastReceiver扩展的类中无法识别getSharedPreferences()

时间:2013-05-08 15:02:35

标签: android

我喜欢在从BroadcastReceiver扩展的类中使用SharedPreferences。但是这种方法getSharedPreferences(prefName, MODE_PRIVATE);无法识别。如何在SharedPreferences课程中检索BroadcastReceiver? 感谢

2 个答案:

答案 0 :(得分:0)

您需要Context来检索SharedPreferencesonReceive为您提供了背景信息

答案 1 :(得分:0)

getSharedPreferencesContext的方法,activity扩展Context,这就是您可以按原样使用它的原因。

如果你想在其他地方使用它,你需要一个上下文。这个答案中提供了最简单的方法

Static way to get 'Context' on Android?

第1步:在AndroidManifest.xml中添加一个类

第2步:以这种方式创建课程

public class App extends Application{

    private static Context _context;

    @Override
    public void onCreate() {
        super.onCreate();
        _context = this;
    }

    public static Context getContext(){
        return _context;
    }
}

第3步:当您需要具有上下文的内容时:App.getContext()

在您的情况下App.getContext().getSharedPreferences()

相关问题