繁体   English   中英

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

[英]How to retrieve shared preferences into a non-activity class from an activity class in Android?

我在一个活动课上有一个价值。 我想在非活动类中使用该值。 通常,要在活动类之间共享数据,我会这样使用,

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

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

您可以通过创建自定义构造函数将您的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);
    }
}

您可以缓存全局Application上下文。

myApplicationContext.getSharedPreferences(NOTIFICATION_ID", MODE_PRIVATE)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM