Finish sub activities programmatically

I have an activity that launches another activity with startActivityForResult method. I would like to terminate the called one programmatically but I don't know how to do this since in onActivityResult() method I have no information about the called activity and I cannot call finish() on it. How can I achieve this?



Try finishActivity(requestCode). According to the documentation it lets you finish an activity previously started with startActivityForResult. And if there are multiple such activities with the same request code, all will be finished.

Note: I haven't actually tried this myself, but that's what the documentation says! Experiment with that, see if it does what you want.


The launched Activity can finish self:

setResult(RESULT_OK); finish();


At the moment you call startActivityForResult your Activity will be closed or paused and the new activity is started. The only one that can finish the new activity is the new activity.

You could start a background task and let this background task somehow notify your activity the activity could now finish itself.

I don't know if a Handler created in Activity A and passed to a thread will remain valid if Activity A is paused and Activity B is active. But I would assume this works because both of the Activities are running in the same thread therefore they should share the same message queue.


This thing just bit me, so I thought I'll add a comment here:

if(readyToFinish()){ finish() } thisCodeWillBeExecuted()

My experience is that all your code in the stacktrace gets executed, before the activity is finished. The documentation is not ideal at this point.

人吐槽 人点赞



用户名: 密码:
验证码: 匿名发表


查看评论:Finish sub activities programmatically