我不是在这里判断它是否是一个好的模式,但如果你真的需要一个活动来等待一个子活动,你可以尝试这种方法:
- 定义两个活动在其上同步的对象(锁);这也可以(应该)作为在这两个活动之间交换数据的对象,因此应该定义为静态的
- 在父activity中,启动一个异步任务(因为UI主线程不能处于等待状态)
- 在异步任务中,启动您的子活动
- 异步任务等待锁定直到收到通知
- 子活动做它需要做的任何事情,并在完成时通知等待线程
我在我的应用程序中做了类似的事情,恕我直言,这样做有充分的理由(不要在应用程序启动或恢复时用登录屏幕打扰用户,应用程序会尝试重复使用存储在安全位置且仅在万一它失败了,它会显示这个登录屏幕.所以是的,基本上我的应用程序中的任何活动都可以“暂停”并等待用户在登录活动中提供正确的凭据,然后登录屏幕完成并且应用程序准确地继续它得到的位置暂停(在父活动中)。
在代码中应该是这样的:
父活动:
public class ParentActivity extends Activity {
private static final String TAG = ParentActivity.class.getSimpleName();
public static class Lock {
private boolean condition;
public boolean conditionMet() {
return condition;
}
public void setCondition(boolean condition) {
this.condition = condition;
}
}
public static final Lock LOCK = new Lock();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.parent_layout);
// do whatever logic you need and anytime you need to stat sub-activity
new ParentAsyncTask().execute(false);
}
private class ParentAsyncTask extends AsyncTask<Boolean, Void, Boolean> {
@Override
protected Boolean doInBackground(Boolean... params) {
// do what you need and if you decide to stop this activity and wait for the sub-activity, do this
Intent i = new Intent(ParentActivity.this, ChildActivity.class);
startActivity(i);
synchronized (LOCK) {
while (!LOCK.conditionMet()) {
try {
LOCK.wait();
} catch (InterruptedException e) {
Log.e(TAG, "Exception when waiting for condition", e);
return false;
}
}
}
return true;
}
}
}
儿童活动:
public class ChildActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.child_layout);
// do whatever you need in child activity, but once you want to finish, do this and continue in parent activity
synchronized (ParentActivity.LOCK) {
ParentActivity.LOCK.setCondition(true);
ParentActivity.LOCK.notifyAll();
}
finish();
// if you need the stuff to run in background, use AsyncTask again, just please note that you need to
// start the async task using executeOnExecutor method as you need more executors (one is already occupied), like this:
// new ChildAsyncTask().executeOnExecutor(ChildAsyncTask.THREAD_POOL_EXECUTOR, false);
}
}