我正在开发一个Android应用程序,它要求用户在做任何其他事情之前先登录。目前,我已经创建了一个名为LoginScreen的主活动,在成功登录后,此活动将启动另一个名为Home的活动。但我看到了这种方法的问题。如果用户在主页活动中按下后退按钮,该怎么办?我不想让用户回到登录屏幕。阻止用户这样做的正确方法是什么?我是否需要处理Key Press事件?
发布于 2016-12-23 03:35:44
请参阅:https://stackoverflow.com/a/41290453/4560689 (文本如下)
要做到这一点,你应该创建一个没有显示的启动器活动(使用安卓的NoDisplay主题),它运行是转到主屏幕还是登录/注册的逻辑。
首先,在您的清单中:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.android">
<-- Permissions etc -->
<application
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name">
<activity
android:name=".onboarding.StartupActivity"
android:label="@string/app_name"
android:launchMode="singleInstance"
android:theme="android:style/Theme.NoDisplay">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:launchMode="singleTop" />
<activity
android:name=".authentication.controller.AuthenticationActivity"
android:label="@string/title_sign_in"
android:launchMode="singleTask"
android:windowSoftInputMode="adjustResize|stateHidden" />
<-- Other activities, services, etc -->
</application>
然后,您的StartupActivity:
package com.example.android.onboarding;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import com.example.android.MainActivity;
import com.example.android.authentication.controller.AuthenticationActivity;
import com.example.android.util.ResourceUtils;
public class StartupActivity extends Activity {
private static final AUTHENTICATION_REQUEST_CODE = 1000;
@Override
protected void onCreate(Bundle savedInstanceState) {
if (isLoggedIn()) {
Intent startupIntent = new Intent(this, MainActivity.class);
startupIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(startupIntent);
finish();
} else {
Intent startupIntent = new Intent(this, AuthenticationActivity.class);
startActivityForResult(startupIntent, AUTHENTICATION_REQUEST_CODE);
}
super.onCreate(savedInstanceState);
}
private boolean isLoggedIn() {
// Check SharedPreferences or wherever you store login information
return this.getSharedPreferences("my_app_preferences", Context.MODE_PRIVATE).getBoolean("loggedIn", false);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == AUTHENTICATION_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
Intent startupIntent = new Intent(this, MainActivity.class);
startupIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(startupIntent);
}
finish();
}
}要点:https://gist.github.com/chanakin/c44bf1c6a9a80d2640440b5aaa92c8ee
https://stackoverflow.com/questions/5859095
复制相似问题