java - 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。
我认为我采用的方法都是错误的,并且有一种更清洁的方法可以立即打开正确的活动。对此的任何帮助将不胜感激。
解决方案
一种可能的方法:
- 为启动主题创建样式:
<style name="SplashTheme" parent="Theme.AppCompat.NoActionBar">
<item name="android:statusBarColor">@color/background_splash</item>
<item name="android:windowBackground">@drawable/background_splash</item>
</style>
- 为启动创建一个背景可绘制对象(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>
- 在您的清单中,将 设置
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>
- 如果用户未登录,则在您的
LoginActivity
in 中设置您的正常应用程序主题和内容视图,并在(或在清单中设置)中设置应用程序主题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
}
}
}
推荐阅读
- python - 如何将字典的键转换为单列熊猫数据框?
- visual-studio-code - 如何设置 Visual Studio Code 来编译和运行 C 代码?
- ansible - Ansible 模板忽略行尾差异 LF CRLF。插件?
- c# - 使用 TopShelf 创建 Windows 服务时出现“错误 1053 服务未响应”错误
- c# - 为什么计数器在线程池中不起作用
- javascript - 如何在 javascript 或 jquery 中使用变量作为数组键
- actionscript-3 - 在 AS3 中好的 Cast 有什么要求?
- c - 在嵌套 C 结构的部分初始化中苦苦挣扎 - 在“->”标记之前预期“=”
- unit-testing - 使用 CHAI 的测试设置器和获取器
- matlab - 使用 matlab GUI 编辑 .txt 文件中的特定数字 使用搜索/替换