0

I got a Service which sends a Notification. When you click on the notification, it opens an Activity. I want to close this Activity when I click on a Button. I used finish(); but it closes the Activity and open the main activity of the application. I'm not sure how to close it and it get back to the last "screen/application"

Yasin Kaçmaz
  • 6,573
  • 5
  • 40
  • 58

2 Answers2

0

Just route to the page you want to open inside the onClickListener of the button where you are calling the finish()

Something like this

Button buttonX = (Button)findViewById(R.id.buttonXName);
buttonX.setOnClickListener(new OnClickListener() {
    public void onClick(View v)
    {
        //  DesiredActivity is the activity you want to open on click
        Intent intent = new Intent(CurrentActivity.this, DesiredActivity.class);
        startActivity(intent);
        finish();
    } 
}); 
Gaurav Sarma
  • 2,248
  • 2
  • 24
  • 45
0

You don't need to finish directly; you need onBackPressed() because you are coming this Activity from nowhere(phone's main screen/another app).

So when you call onBackPressed() it will close app :

@Override
public void onBackPressed() {
    super.onBackPressed();
    //supportFinishAfterTransition(); finish activity after going back 
    //if want overridePendingTransition(R.anim.nothing, R.anim.slide_out_right); 
}

Additionally you can add supportFinishAfterTransition() after super.onBackPressed() line still if you want to finish your Activity.

After adding, call this method : onBackPressed() in your onClick method, in this way you can add custom transitions too.

Yasin Kaçmaz
  • 6,573
  • 5
  • 40
  • 58