Я работаю над Android-приложением, которое требует от пользователя входа в систему, прежде чем делать что-либо еще. В настоящее время я создал основную активность с именем LoginScreen, и после успешного входа в это действие запускается другое действие под названием "Главная". Но я вижу проблему с этим подходом. Что делать, если пользователь нажимает кнопку "Назад" из "Дома"? Я не хочу, чтобы пользователь возвращался к экрану входа в систему. что является правильным способом остановить пользователя от этого. Нужно ли обрабатывать события нажатия клавиш?
Каков правильный способ создания экрана входа/активности в Android?
Ответ 1
То, что я закончил, состояло в том, чтобы заставить мою главную деятельность обрабатывать намерение android.intent.action.MAIN. Начальная активность при запуске проверяет, был ли пользователь подписан или нет (с использованием общих настроек), если он не начинается, то он запускает LoginActivity и вызывает finish().
LoginActivity при успешном входе в систему запускает основное действие, и на этот раз, поскольку пользователь вошел в систему, основное действие продолжит нормальный курс. LoginActivity объявляется следующим в файле манифеста:
<activity android:name="LoginScreen" android:label="@string/app_name"
android:noHistory="true" android:excludeFromRecents="true">
</activity>
Настройка noHistory и excludeFromRecents на true для LoginActivity означает, что пользователь не может вернуться к этому действию с помощью кнопки возврата.
Ответ 2
После вызова startActivity(...)
в активности LoginScreen вызовите finish()
. Это приведет к удалению этой активности из стека действий, поэтому нажатие на кнопку по существу будет закрывать ваше приложение, когда вы находитесь в своей домашней деятельности.
Ответ 3
LoginActivity.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fitsSystemWindows="true"
android:background="#263238">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="80dp"
android:paddingLeft="16dp"
android:paddingRight="16dp">
<!-- App Logo -->
<ImageView android:id="@+id/logo"
android:src="@drawable/logo"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_marginBottom="20dp"
android:layout_gravity="center_horizontal" />
<!--Title TextView-->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="STOCK BUDDY"
android:id="@+id/title"
android:textSize="24sp"
android:textStyle="bold"
android:textColor="#7B869B"
android:layout_marginBottom="24dp"
android:layout_gravity="center_horizontal"/>
<!--User Email-->
<EditText
android:id="@+id/login_email"
android:layout_marginTop="10dp"
android:layout_marginBottom="5dp"
android:layout_centerVertical="true"
android:layout_width="match_parent"
android:layout_height="40dp"
android:ellipsize="start"
android:gravity="center"
android:hint="Email"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:textColorHint="#cccccc"
android:textColor="#7B869B"
android:maxLength="40"
android:maxLines="1"
android:inputType="textEmailAddress"
android:background="@drawable/edittextshape"/>
<!-- User Password -->
<EditText
android:id="@+id/login_password"
android:layout_marginTop="5dp"
android:layout_marginBottom="10dp"
android:layout_centerVertical="true"
android:layout_width="match_parent"
android:layout_height="40dp"
android:ellipsize="start"
android:gravity="center"
android:paddingRight="16dp"
android:paddingLeft="16dp"
android:hint="Password"
android:textColor="#7B869B"
android:textColorHint="#cccccc"
android:maxLength="20"
android:maxLines="1"
android:inputType="textPassword"
android:background="@drawable/edittextshape"/>
<!--Login Button-->
<android.support.v7.widget.AppCompatButton
android:id="@+id/btn_login"
android:layout_width="fill_parent"
android:layout_marginTop="5dp"
android:layout_marginBottom="24dp"
android:background="@drawable/buttonshape"
android:text="Login"
android:textSize="20sp"
android:layout_height="40dp"
android:textColor="#ffffff"
android:shadowRadius="5"
android:onClick="Login"/>
<!--signup Link TextView-->
<TextView android:id="@+id/link_signup"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="24dp"
android:text="No account yet? Create one"
android:gravity="center"
android:textSize="12sp"
android:textColor="#7B869B"/>
</LinearLayout>
</ScrollView>
buttonshape.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<corners
android:radius="44dp"
/>
<gradient
android:angle="45"
android:centerX="35%"
android:centerColor="#63D0C3"
android:startColor="#70DB9A"
android:endColor="#56C5EE"
android:type="linear"
/>
<padding
android:left="0dp"
android:top="0dp"
android:right="0dp"
android:bottom="0dp"
/>
<stroke
android:width="0dp"
android:color="#878787"
/>
</shape>
edittextshape.xml
<?xml version="1.0" encoding="utf-8" ?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:thickness="0dp"
android:shape="rectangle">
<solid android:color="#ffffff"/>
<stroke android:width="1dp"
android:color="#ffffff" />
<corners android:radius="44dp" />
</shape>
.....................
см. полный код на https://androidpugnator.wordpress.com/2017/03/12/android-login-and-signup-screens
Ответ 4
Попробуйте установить флаги в намерение.
Пример:
new Intent(context, SomeActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
Дополнительная информация о флажках: http://developer.android.com/reference/android/content/Intent.html#nestedclasses
Ответ 5
Вызовите startActivity (...) в LoginActivity для какого-либо события (например, нажмите кнопку входа в систему). Используйте отдельный класс базы данных, чтобы сохранить имя пользователя и пароль пользователя из класса HomeActivity.
Обработайте событие onKeyDown() для управления кнопкой возврата в HomeActivity (используйте метод finish()).
В классе OnCreate() класса LoginActivity используйте соединение с базой данных, чтобы проверить, существуют ли имя пользователя и пароль в таблице базы данных, если да, тогда вызывается startActivity() тоже для прямого перехода на HomeScreen из LoginScreen. Это не покажет LoginScreen.
Надеюсь, это сработает для вас. Попробуйте.
Ответ 6
Смотрите: https://stackoverflow.com/a/41290453/4560689 (текст ниже)
Чтобы сделать это, вы должны создать единую активность запуска с No Display (с использованием темы Android 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