8

I have a question concerning the finish() method of an activity in android studio:

I have this simple code:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }
}

In my activity_main I simply have a button. When I click on the button the activity finishes and I go back to the main screen of the device...However, when I click on the menu button of the device (which shows all the app running in background) I still see my activity... and I do not want that. How can I fix it?

Bazouk55555
  • 557
  • 6
  • 24
  • 1
    "However, when I click on the menu button of the device (which shows all the app running in background)" -- no, it does not. It shows recent tasks. None of those are necessarily "running", insofar as none necessarily have a running process. "and I do not want that" -- why? Or, more accurately, why do your *users* not want that? – CommonsWare Sep 16 '17 at 14:26
  • Possible duplicate of [what exactly Activity.finish() method is doing?](https://stackoverflow.com/questions/10847526/what-exactly-activity-finish-method-is-doing) –  Sep 16 '17 at 14:42
  • To CommonsWare: Actually I had this question for another application more developed than this one. This application is an alarm and I had a button finish. When the screen is locked, the activity of the alarm appears at the time of the alarm. when I clik on the button: "finish the alarm" the alarm finished but it was it was in the recent tasks (thank you btw for this explanation!). And when I clicked on it it was ringing again...I hope I am clear – Bazouk55555 Sep 16 '17 at 14:51
  • To Shiva: I saw this question but it didn't have my answer – Bazouk55555 Sep 16 '17 at 14:51

2 Answers2

21

try using

android:excludeFromRecents="true" in your Activity in AndroidManifest.xml.

<activity
            ...
             android:excludeFromRecents="true">
</activity>
Mohamed Nageh
  • 1,963
  • 1
  • 19
  • 27
0

if the activity has a thread running in the background to download data from the network, it may create that thread in onCreate() and then stop the thread here in onDestroy() if you don't have new thread you can after finish(); write return;

AlimItTech
  • 172
  • 1
  • 9