gpt4 book ai didi

android - 如何只显示一次登录屏幕?

转载 作者:IT老高 更新时间:2023-10-28 23:29:38 24 4
gpt4 key购买 nike

我正在创建一个项目,其中有一个登录屏幕,用于用户登录
应用。这个登录屏幕应该只在第一次可见,因此用户可以填写并登录,但是当用户第二次打开应用程序时,应用程序必须显示 main.activity。使用方法Shared preference .

我不明白该怎么做。

最佳答案

要使用 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.
}

希望对你有帮助

编辑:要防止用户使用后退按钮返回登录 Activity ,您必须在开始新 Activity 后finish() 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 Activity 上调用 finish() 函数。

另请参阅:Removing an activity from the history stack

关于android - 如何只显示一次登录屏幕?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9964480/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com