Search code examples
androidandroid-activity

finishActivity (int RequestCode) doesn't work


I'm trying to close an Activity that is open from my own activity. I think finish activity is the better way but it doesn't work. Here is my code to open the activity. (Works with a third party package, this may be the problem?)

Intent calendar = new Intent();
calendar.setPackage("com.digibites.calendar");
if (calendar.resolveActivity(getPackageManager()) != null) {
    startActivityForResult(calendar, REQUEST_CALENDAR);
    CURRENT_ACTIVITY = REQUEST_CALENDAR;
}

I close the activity with this, after launch it:

finishActivity(CURRENT_ACTIVITY);

When I start the activity I'm calling a third part package to show a calendar. When the user wants, the calendar is closed by pressing a button. finishActivity is in the method of the button. If I call finish, y close my application activity, not the calendar activity.


Solution

  • finishActivity(...) is used for something different than you might think. Its meant for when you want to finish the result yielding activity from the activity that launched it. Its counter intuitive but the docs are clear about it:

    https://developer.android.com/reference/android/app/Activity#finishActivity(int)

    What you need to do in your scenario is:

    Just use finish() after setResult(..., ...) in the activity you called for result.

    val intent = Intent()
    intent.putExtras(yourResultsBundle)
    setResult(Activity.RESULT_OK, intent)
    finish()