首页 > 解决方案 > Android:如果有用户登录,则启动不同的活动

问题描述

我正在构建一个 Android 应用程序,其中一个活动是登录屏幕。打开应用程序时,如果用户已经登录,我想跳过 LoginActivity 并将用户定向到另一个。当用户登录我的应用程序(使用 Google Firebase)时,我会将他们的用户名和其他数据保存在他们设备的共享首选项中。当他们注销时,他们的共享首选项将被清除。

我目前拥有清单文件的方式是,在启动应用程序时唯一可以打开的活动是 LoginActivity:

        <activity android:name=".LoginActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

在 LoginActivity 的 OnCreate() 方法中,如果共享首选项中保存了用户名(表示用户已登录),我立即更改活动:

public class LoginActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        SharedPreferences userData = getApplicationContext().
                getSharedPreferences("userdata", 0);
        String n = userData.getString("username", "");
        if (!userData.getString("username", "").equals(""))
        {
            Intent myIntent = new Intent(LoginActivity.this, TabbedActivity.class);
            startActivity(myIntent);
        }
}

但是,这种方法存在一个问题。很多时候,在启动 TabbedActivity 之前,LoginActivity 仍会显示片刻。我想解决这个问题,以便在用户登录时实际上根本看不到 LoginActivity。

我认为我采用的方法都是错误的,并且有一种更清洁的方法可以立即打开正确的活动。对此的任何帮助将不胜感激。

标签: javaandroidfirebasesharedpreferencesmanifest

解决方案


一种可能的方法:

  1. 为启动主题创建样式:
<style name="SplashTheme" parent="Theme.AppCompat.NoActionBar">
    <item name="android:statusBarColor">@color/background_splash</item>
    <item name="android:windowBackground">@drawable/background_splash</item>
</style>
  1. 为启动创建一个背景可绘制对象(drawable/background_splash.xml):
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <color android:color="@color/background_splash"/>
    </item>
    <item>
        <bitmap
            android:src="@drawable/ic_splash_logo"
            android:gravity="center"/>
    </item>
</layer-list>
  1. 在您的清单中,将 设置SplashTheme为您的应用程序/启动器活动主题:
<application
    ...
    android:theme="@style/SplashTheme">

<!-- or -->

<activity
    ...
    android:theme="@style/SplashTheme">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

  1. 如果用户未登录,则在您的LoginActivityin 中设置您的正常应用程序主题和内容视图,并在(或在清单中设置)中设置应用程序主题onCreate()MainActivity
public class LoginActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        val isUserLoggedIn = ...
        if (!isUserLoggedIn)
        {
            setTheme(R.style.AppTheme)
            setContentView(R.layout.activity_login)
        } 
        else {
            //Navigate to Main Activity
        }
    }
}

启动画面参考


推荐阅读