在非Activity類下使用SharedPreferences

本文介绍了一种在非Activity类中使用SharedPreferences的方法。通过在一个Activity类中创建并初始化静态上下文变量,然后在其他类中通过调用该Activity类的静态方法获取上下文,进而使用PreferenceManager获取SharedPreferences变量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SharedPreferenced are related to context. You can only reference it through a context.

You can simply pass context as a parameter to your class. For example in the constructor.

In your activity do:

MyClass myClass = new MyClass(this);

The solution i found to this was:

1-In an Activity class (project must have at least one for this solution to work) create a static variable for the context:

public static Context contextOfApplication;

2-In an importante method of this class (Such as onCreate, the constructor, etc) initialize this variable using the getApplicationContext method:

public void onCreate() {
    contextOfApplication = getApplicationContext();
}

3-In the same class Create a "getter" method for this variable (it must also be static):

public static Context getContextOfApplication(){
    return contextOfApplication;
}

4-In the non-activity class get the context by calling the created method statically:

Context applicationContext = MyActivityClass.getContextOfApplication();

5-Use the PreferenceManager Class to get the SharedPreferences variable:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(applicationContext);

Try using default preferences with an Application context. A context is similar to the environment an application runs in on linux or windows (e.g. environment variables like PATH windowing style or console size). Each Activity and Service has its own Context too for example screen orientation, theme, and label, etc. but for your application you don't want the context of the Activity, you want something global to the app, this is where context.getApplicationContext() is useful. This the same throughout the app and will always give you the same default preferences.

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值