同步startActivityForResult - 等待活动来完成来完成、startActivityForResult

2023-09-12 04:49:09 作者:喜你笑颜

我在哪里,我推出一个新的活动的应用程序,并且需要继续之前有活动的结果。

I have an application where I am launching a new Activity, and need to have the result of the activity before proceeding.

我意识到startActivityForResult是异步/非阻塞的,而且我可以在onActivityResult回调活动的结果。

I realize that startActivityForResult is asynchronous / non-blocking, and that I can get the result of the activity in the onActivityResult callback.

所以我猜我寻找的是等待活动,以回报的最佳途径...... 像这样的事情吧?还是有更好的办法吗?

So I guess what I'm looking for is the best way to wait for the activity to return... Something like this perhaps? Or is there a better way?

活动启动功能:

public String ActivityLauncher()
{
   //Set up Intent
   startActivityForResult(intent, 1);
   while (mIsActivityDone == false)
   {
       Thread.Sleep(250);
   }
   //Continue with processing
   String data = "<Data from Activity">
   return data;
}

回调:

protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
   //Pull out the data
   mIsActivityDone = true;
}

该数据需要恢复到一个更高的层次调用函数 - 这就是为什么我需要等待结果的ActivityLauncher功能

The data needs to be returned to a higher level calling function - this is why I need to wait for the result in the ActivityLauncher function.

谢谢!

推荐答案

这将阻止你的UI线程,以便其他活动将不会执行任何。 我会用一些由更高级别的功能,提供的回调类,在这种情况并调用回调函数 onActivityResult

This will block your UI thread so other activity will not execute either. I would use some kind of callback class provided by higher level function, in this kind of situation and call its callback function in onActivityResult