如何在不开始新 Activity 的情况下清除 Android 上的上一个 Activity

How to clear previous Activity on Android without start new Activity

我想清除以前的 activity 但没有在 android 开始新的 activity。

通常我在清洁时使用此代码

Intent intent = new Intent(SplashActivity.this,MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);

但如果我不想更改活动怎么办?也许有人可以帮助我..

第 1 步:创建可绘制对象:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@android:color/darker_gray" />
<item>
    <bitmap
        android:gravity="center"
        android:src="@drawable/img_splash" />
</item>

代码link:splash_theme_bg.xml

第 2 步:创建样式

<style name="SplashTheme" parent="Theme.AppCompat.NoActionBar">
    <item name="android:windowBackground">@drawable/splash_theme_bg</item>
</style>

代码link:styles.xml

第三步:在AndroidManifest.xml

中设置样式
<activity
        android:name=".SplashActivity"
        android:theme="@style/SplashTheme">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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

代码link:AndroidManifest.xml

如果您仍然卡在任何地方,请告诉我。 编码愉快!

Start an Activity, start it like this:

Intent myIntent = new Intent(SplashActivity.this, MainActivity.class);
startActivityForResult(myIntent, 0);

When you want to close the entire app, do this:

setResult(RESULT_CLOSE_ALL);
finish();

RESULT_CLOSE_ALL 是一个最终的全局变量,带有一个唯一的整数,表示您要关闭所有活动。

然后定义每个 activity 的 onActivityResult(...) 回调,这样当 activity returns 与 RESULT_CLOSE_ALL 值,它也调用 finish():

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch(resultCode)
    {
    case RESULT_CLOSE_ALL:
        setResult(RESULT_CLOSE_ALL);
        finish();
    }
    super.onActivityResult(requestCode, resultCode, data);
}

See these threads for other methods as well:

Android: Clear the back stack

Finish all previous activities