繁体   English   中英

用户在Android Studio中登录后如何打开应用程序进行其他活动

[英]How to open app to different activity after user login in Android Studio

我是Android Studio的新手,我正在制作一个简单的应用程序,用户必须登录后才能转到其他屏幕。 当用户首次打开应用程序时,系统会提示他们登录活动,如果登录成功,他们将进入另一个活动。 我想知道用户登录后如何关闭应用程序并再次打开它,它将直接将他们带到其他活动。

您的登录活动中需要以下内容:

protected void onResume() {
    super.onResume();
    // Checking for user session
    // if user is already logged in, take him to main activity
    if (pref.isLoggedIn()) {
       //here, pref is the instance of your preference manager
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);

        finish();
    }

}

您可以这样创建一个首选项管理器:

public class PrefManager {
// Shared Preferences
SharedPreferences pref;

// Editor for Shared preferences
SharedPreferences.Editor editor;

// Context
Context _context;

// Shared pref mode
int PRIVATE_MODE = 0;

// Shared preferences file name
private static final String PREF_NAME = "YourAppName";

// All Shared Preferences Keys
private static final String KEY_IS_LOGGED_IN = "isLoggedIn";
private static final String KEY_NAME = "name";
private static final String KEY_PICTURE = "picture";
private static final String KEY_MOBILE = "mobile";

//initializing sharedPreferences
public PrefManager(Context context) {
    this._context = context;
    pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
    editor = pref.edit();
}

public void setMobileNumber(String mobileNumber) {
    editor.putString(KEY_MOBILE, mobileNumber);
    editor.commit();
}

public void setName(String name) {
    editor.putString(KEY_NAME, name);
    editor.commit();
}

public void setPicture(String picture) {
    editor.putString(KEY_PICTURE, picture);
    editor.commit();
}

public String getMobileNumber() {
    return pref.getString(KEY_MOBILE, null);
}

//Logging in user and setting the name and profile picture
public void createLogin(final String mobile) {

    //here, handle the mobile number or email or any details that you 
    //use for the login. Then do this:

    editor.putBoolean(KEY_IS_LOGGED_IN, true);
    editor.commit();
}

public boolean isLoggedIn() {
    return pref.getBoolean(KEY_IS_LOGGED_IN, false);//false is the default value in case there's nothing found with the key
}

public void clearSession() {
    editor.clear();
    editor.commit();
}
}

在登录活动中,一旦登录成功,也将PrefManager的登录设置为true。 让我知道您是否需要更多帮助。

初始屏幕是确定用户必须导航到哪个页面的最佳位置。 在启动屏幕中,检查用户已登录的天气。如果已登录,则将其导航到主页。 否则,请导航他以登录/注册页面。 将用户登录信息存储在共享首选项中,以在初始屏幕上检查。

以一种非常简单的方式,使用“共享首选项”存储用户的登录详细信息。 并在登录之前检查共享首选项是否具有用户凭据。如果有,请切换到另一活动,否则转到登录页面。

用户首次打开应用程序时,登录成功后,您将保存一个变量boolean isLogin对共享首选项为true 再次打开时,您检查变量boolean isLogin为true,然后启动MainActivity,反之亦然,即启动活动登录。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM