如何从Android中的活动类检索共享首选项到非活动类?

时间:2016-06-02 08:00:01

标签: java android android-activity sharedpreferences

我在活动类中有一个值。我想在非活动类中使用该值。通常,为了在活动类之间共享数据,我使用like,

FirstActivityClass.java

SharedPreferences notification_id = getSharedPreferences("NOTIFICATION_ID", MODE_PRIVATE);
SharedPreferences.Editor notificationIDEditor = notification_id.edit();
notificationIDEditor.putString("notification_id", notificationId)                
notificationIDEditor.apply();

并在另一个类中检索notification_id的值,

SecondActivityClass.java

SharedPreferences notificationIDSharedRetrieve = getSharedPreferences("NOTIFICATION_ID", MODE_PRIVATE);
notificationID = notificationIDSharedRetrieve .getString("notification_id", null);

但是假设第二个类是非活动类,我如何在非活动类中检索数据?

2 个答案:

答案 0 :(得分:2)

您可以通过创建自定义构造函数将您的Activity上下文发送给您的calss,例如:

class A
{
Context con;
public A(Context con)
    {
    this.con=con
    }
}



Activity B
{
Context con;
  @Override
  public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         this.con=getContext();
         A = new A(this.con);
    }
}

答案 1 :(得分:0)

您可以缓存全局应用程序上下文。

myApplicationContext.getSharedPreferences(NOTIFICATION_ID", MODE_PRIVATE)