我正在创建一个项目,其中有一个登录屏幕,用户可以使用该屏幕登录到
应用程序。这个登录屏幕应该只在第一次可见,所以用户可以填充它并登录,但是当用户第二次打开应用程序时,应用程序必须显示main.activity。如何使用Shared preference。
我不知道该怎么做。
发布于 2012-04-01 21:27:35
要使用SharedPreferences实现这一点,您可以执行以下操作:
在您认为更合适的类中插入以下代码。假设您将此代码插入到Example类中。
//Give your SharedPreferences file a name and save it to a static variable
public static final String PREFS_NAME = "MyPrefsFile";现在,在评估用户是否成功登录的方法中使用,执行以下操作。注意Example类,您必须将其更改为与您的代码匹配。
//User has successfully logged in, save this information
// We need an Editor object to make preference changes.
SharedPreferences settings = getSharedPreferences(Example.PREFS_NAME, 0); // 0 - for private mode
SharedPreferences.Editor editor = settings.edit();
//Set "hasLoggedIn" to true
editor.putBoolean("hasLoggedIn", true);
// Commit the edits!
editor.commit();最后,当您的应用程序启动时,您现在可以评估用户是否已经登录。请仍然注意您必须更改的Example类。
SharedPreferences settings = getSharedPreferences(Example.PREFS_NAME, 0);
//Get "hasLoggedIn" value. If the value doesn't exist yet false is returned
boolean hasLoggedIn = settings.getBoolean("hasLoggedIn", false);
if(hasLoggedIn)
{
//Go directly to main activity.
}希望这能有所帮助
编辑:为了防止用户使用后退按钮返回登录活动,您必须在启动新活动后编辑该活动。
以下代码取自Forwarding.java | Android developers
// Here we start the next activity, and then call finish()
// so that our own will stop running and be removed from the
// history stack
Intent intent = new Intent();
intent.setClass(Example.this, ForwardTarget.class);
startActivity(intent);
Example.this.finish();因此,您在代码中要做的就是在调用startActivity()之后,在Login活动上调用finish()函数。
发布于 2012-04-01 20:48:10
使用SharedPreferences。例如,保存一些值,并在登录活动中读取它。
在我们的项目中,我们保存了token和用户id。因此,如果用户已经登录,我们将跳过授权活动。
附注:如果你的登录活动是你的应用程序中的第一个活动,那么在开始另一个活动之前,不要忘记完成它,以防止在其他活动中按“后退”键。
发布于 2012-04-01 21:53:41
使用SharedPreferences。例如,有一个布尔变量,并在应用程序启动时读取它。在您的情况下,当用户第一次启动应用程序时,共享首选项中的变量将为false,因此启动登录屏幕并在成功登录后,将共享首选项中的布尔变量设置为true,这样当用户第二次来时,共享首选项中的值将为true。因此,跳过登录屏幕,启动您的主要活动。
要在SharedPreference中存储布尔值,请使用以下代码:
public static void saveBooleanInSP(Context _context, boolean value){
SharedPreferences preferences = _context.getSharedPreferences("PROJECTNAME", android.content.Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("ISLOGGEDIN", value);
editor.commit();
}//savePWDInSP()要从SharedPreference执行getValue,请使用以下代码:
public static boolean getBooleanFromSP(Context _context) {
// TODO Auto-generated method stub
SharedPreferences preferences = _context.getSharedPreferences("PROJECTNAME", android.content.Context.MODE_PRIVATE);
return preferences.getBoolean("ISLOGGEDIN", false);
}//getPWDFromSP()https://stackoverflow.com/questions/9964480
复制相似问题