Search code examples
androidandroid-layoutandroid-activityactivity-lifecycleactivity-finish

Close android activity (completely, not even in background) using finish on a button click


I need to close an activity when a button is clicked. Unfortunately, when button is clicked, the activity does disappear but is still in the background. User can still select it and it comes back to front. What I need is the activity completely gone/destroyed.

public class MainActivity extends AppCompatActivity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            Button button = (Button)findViewById(R.id.button);
            button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}

I searched on SO on related questions, however, none of them help with closing the activity completely. I already tried adding return, adding another broadcast listener and passing command to call finish outside onCreate. So at this point, the question is - is this really possible or is this how Android works, you can call finish() but it is still in the background and user can re-launch it.

Here is xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.app1.test.myapplication">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

EDIT: Adding android:excludeFromRecents="true" does not solve the issue. Here are steps to recreate this, if anyone thinks it is a duplicate or already solved, please try and post comment/answer, I will accept it.

  1. Open Android Studio
  2. Create empty activity project.
  3. Add a button.
  4. Add code in MainActivity's onCreate for button click listener.
  5. Inside click listener, call finish.
  6. Run the app and click button and see if the activity is still in background or not.

Solution

  • You need to put this in your XML manifest:android:excludeFromRecents="true"

    in your Activity TAG.

    <activity
                ...
                 android:excludeFromRecents="true">
    </activity>