可能重复:
Android中的单身人士与应用程序上下文?
我不太明白这个:
当您的应用程序实现在清单中注册时,它将在创建应用程序进程时实例化.因此,您的应用程序实现本质上是一个单例,应该这样实现,以提供对其方法和成员变量的访问.
public class MyApplication extends Application {
private static MyApplication singleton;
// Returns the application instance
public static MyApplication getInstance() {
return singleton;
}
public final void onCreate() {
super.onCreate(); singleton = this;
}
}
Run Code Online (Sandbox Code Playgroud)
我正在阅读这是推荐的...但我的应用程序对象MyApp扩展应用程序工作正常...我没有这样的代码.
我只是通过强制转换getApplication()来获取MyApp对象
有人可以解释实现这样的代码的好处吗?我错过了一些明显的东西吗?
我正在开发中,我在存储应用username和password在SharedPreferences.所有的东西都适合我,存储以及检索值.但我发现当我重新启动设备或应用程序强制关闭时,存储的值将SharedPreferences被重置.当我再次启动我的应用程序时,我在SharedPreferences键中获得空值.在这里,我正在做什么来存储值:
SharedPreferences emailLoginSP;
emailLoginSP = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
emailLoginSP.edit().putString("prefEmailId", email_text).commit();
emailLoginSP.edit().putString("prefUserId", userIDToken).commit();
emailLoginSP.edit().putString("prefAccess_token", accessToken).commit();
Intent i = new Intent(LoginWithEmail.this,UserInfoActivity.class);
i.putExtra("acess_token", accessToken);
i.putExtra("user_id", userIDToken);
i.putExtra("emailID", email_text);
startActivity(i);
Run Code Online (Sandbox Code Playgroud)
而且,这就是我正在重温它的方式:
SharedPreferences emailLoginSP = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
loginEmail = emailLoginSP.getString("prefEmailId", null);
loginUserId = emailLoginSP.getString("prefUserId", null);
loginAccessToken = emailLoginSP.getString("prefAccess_token", null);
Run Code Online (Sandbox Code Playgroud)
到目前为止,一切正常.我再次说明我的问题,当我强制关闭或重启我的设备时,我得到空值.我们可以将它永久存储在应用程序内存中吗?或者,我在这里做错了什么?
任何帮助将不胜感激.