如何进行阻止和同步活动?

wwy*_*wyt 1 android synchronous android-activity

好吧,请不要问我原因,但我需要启动同步和阻止活动,以便程序流程在完成之前不会继续.我知道如何进行同步对话,但我该如何进行同步活动?

以下是我尝试但失败的两种方法:

// In the 1st activity, start the 2nd activity in the usual way
startActivity(intent);
Looper.loop();        // but pause the program here
// Program continuse running afer Looper.loop() returns
....

// Then, in the second activity's onBackPressed method:
public void onBackPressed() {
    // I was hoping the following quit() will terminate the loop() call in
    // the first activity. But it caused an exception "Main thread not allowed
    // to quit." Understandable.
    new Hanlder().getLooper().quit();
}
Run Code Online (Sandbox Code Playgroud)

我还试图用另一个线程来实现这个目的:

// In the first activity, start a thread
SecondThread m2ndThread = new SecondThread(this);
Thread th = new Thread(m2ndThread, "Second Thread");
th.run();
synchronized(m2ndThread) {
    m2ndThread.wait();
}

class SecondThread implements Runnable {

    Activity m1stActivity;

    SecondThread(Activity a) {
        m1stActivity = a;
    }

    public void run() {
        Looper.prepare();
        Handler h = new Handler() {
            public void handleMessage() {
                Intent intent = new Intent(m1stActivity, SecondActivity.class);
                m1stActivity.startActivity(intent); // !!!!!!!!!!!!!!
            }
        }
        h.sendEmptyMessage(10); // let it run
        Looper.quit();
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,这种方法不起作用,因为当我使用第一个活动来启动第二个活动时,主线程已经处于等待状态并且什么都不做.所以第二项活动甚至没有创建.(这很讽刺:你必须使用一个活动来开始一项活动,但是当它已经处于等待状态时你怎么能这样做呢?)

hac*_*bod 9

你不能.

这就是它的全部.你不能这样做.活动始终在主线程上执行.您的主线程必须主动运行其事件循环.它总是被破坏以阻止主线程的事件循环.总是.