Skip to content Skip to sidebar Skip to footer

How To Clear Previous Activity On Android Without Start New Activity

I want to clear previous activity but without start new activity on android. Usually I use this code when change with cleaning Intent intent = new Intent(SplashActivity.this,MainAc

Solution 1:

Step1:Create a drawable:

<?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>

Code link: splash_theme_bg.xml

Step2: Create Style

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

Code link: styles.xml

Step3: Set style in 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>

Code link: AndroidManifest.xml

Let me know if you still get stuck anywhere. Happy Coding!


Solution 2:

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 is a final global variable with a unique integer to signal you want to close all activities.

Then define every activity's onActivityResult(...) callback so when an activity returns with the RESULT_CLOSE_ALL value, it also calls 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


Post a Comment for "How To Clear Previous Activity On Android Without Start New Activity"