如何从普通 java class android 获取 sharedpreference 值

How to get sharedpreference value from normal java class android

我在用户登录后将电子邮件地址存储在 sharedpreference 中。我正在访问每个 activity 中的 sharedpreference activity。没关系。但是当我尝试将共享首选项变量访问到任何正常的class(非activity)时,它给出错误

我正在从 MainActivity 调用 MyLocationReceiver class..

private PendingIntent getPendingIntent() {
    Intent intent=new Intent(Home.this,MyLocationReceiver.class);
    intent.setAction(MyLocationReceiver.ACTION);
    return PendingIntent.getBroadcast(this,0,intent, PendingIntent.FLAG_UPDATE_CURRENT);
}

getSharedPreferences 需要上下文。您已经将 context 作为方法中的参数 onReceive(context, intent).

因此,只需将 getSharedPreferences 行替换为以下

context.getSharedPreferences(PREFS_NAME, 0)