Search code examples
javaandroidandroid-studioandroid-activityandroid-ondestroy

How to completely destroy an activity from code?


I am building an medication reminder app in android using java. User can set one or more reminders and according to those will get notified to take the medicine.

Problem is, whenever a notification is generated, and the user taps on it and the receiver activity opens up, the user is presented with two choices of either taking the medicine or skipping it. Now, I have made sure that in both the cases, the activity will finish and have called its onDestroy() method too. My objective is to prevent the activity from appearing in the recent app list, so that the user can not repeatedly take or skip medicines.

Here's the details(the links all point to screenshots of the app if it helps in any way):

Notification Image

The notification comes,User taps on the notification and the Reminder Receive activity opens up

Reminder receive activity

User either takes or skips the medicine, and the activity finishes.

activity shown on recent app list

but the activity is still being shown on the recent app list, and if tapped on it, it opens up the reminder receive activity again, with the user able to perform the same action again

after tapping on the app from recent app list

I want to prevent this particular behaviour from happening.

Here's the things I have tried(I have a fragment,running on top of the activity):

  1. finishing the activity from fragment,then calling onDestroy() on it
ReminderRecieveActivity activity = (ReminderRecieveActivity) requireActivity();
activity.finish();
activity.onDestroy();

  1. Modifying the onDestroy() method of the activity like so
    @Override
    protected void onDestroy() {
        super.onDestroy();
        int id= android.os.Process.myPid();
        android.os.Process.killProcess(id);
        System.exit(0);
    }

But still the problem persists, Please help.


Solution

  • Why not create a separate Activity with android:noHistory="true" and also android:excludeFromRecents="true"? You don't have to kill the process to do that.