运行Android应用程序时如何自动登录 [英] How to auto login when I run the Android Application
问题描述
假设我已经使用PHP + MySQL登录到系统,然后在退出应用程序后再次运行应用程序,无需再次登录并自动登录,请帮助解决问题.
Assume that I have login to system using PHP + MySQL, then, after I exit the apps, I run the apps again, no need to login again and auto login, Please help to solve the problem.
推荐答案
在首次登录时,您会以响应方式获取用户名或用户名,而不是将用户名或用户名存储在sharedpreference中,如下所示
while first time login u get something username or userid in respones than store ther username or userid in sharedpreference like as shown below
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(YourActivity.this);
prefs.edit().putInt("userid",userid).commit();
成功登录后,这将优先存储您的用户ID,您可以检查您是否已经登录
as after succesfull login this will store your userid in preference and u can check u are already login or not as
int Userid;
prefs = PreferenceManager.getDefaultSharedPreferences(YourActivity.this);
Userid= mPrefs.getInt("userid", 0); which will return defalut value 0 if u are not login
检查后
if(Userid>0){
// Means u are already logged in do here code what u want if u are login
}else{
// Means u are not logged in than go to your login pageview from here
}
这只是做您想要的事情的简单方法,如果您希望在单击按钮时比在onclick事件上需要注销功能,则必须添加以下代码以退出注销
this is just simple way for doing what u want suppose if u want logoout functionality on button click than onclick event u have to add following code for logout which will clear prefernce
prefs = PreferenceManager.getDefaultSharedPreferences(MyAccountActivity.this);
prefs.edit().clear().commit();
这篇关于运行Android应用程序时如何自动登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!