应用程序类:
import android.app.Application;
import android.content.Context;
public class MyApplication extends Application {
private static Context mContext;
public void onCreate() {
super.onCreate();
mContext = getApplicationContext();
}
public static Context getAppContext() {
return mContext;
}
}
在AndroidManifest中声明应用程序:
<application android:name=".MyApplication"
...
/>
使用方法:
PreferenceManager.getDefaultSharedPreferences(MyApplication.getAppContext());
public static SharedPreferences preferences;
preferences = getSharedPreferences( getPackageName() + "_preferences", MODE_PRIVATE);
然后在 PreferenceHelper 中使用 set 和 get 方法,如下所示:
public static void setName(String value) {
MainActivity.preferences.edit().putString(KEY_DEMO_NAME, value ).commit();
}
public static String getName() {
return MainActivity.preferences.getString(KEY_DEMO_NAME,"");
}
android:name=".SGAutoApp"
SGAutoApp.kt
class SGAutoApp : Application() {
companion object {
fun getAppContext(): Context {
return this.getAppContext()
}
}
}
然后在我的实用程序类回调方法中就像下面这样。
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(SGAutoApp.getAppContext())