从Android中的辅助线程调用主线程

saj*_*joo 40 java multithreading android

如何从Android中的辅助线程调用主线程?

tho*_*dge 82

最简单的方法是从线程调用runOnUiThread(...)

activity.runOnUiThread(new Runnable() {
    public void run() {
        ... do your GUI stuff
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 你是什​​么意思'通过Java'?这是Java (4认同)
  • 通过java怎么样? (2认同)

小智 24

我建议在同一进程中传递线程是在这些线程之间发送消息.使用Handler管理这种情况非常容易:

http://developer.android.com/reference/android/os/Handler.html

从Android文档到ui线程处理昂贵工作的使用示例:

public class MyActivity extends Activity {

    [ . . . ]
    // Need handler for callbacks to the UI thread
    final Handler mHandler = new Handler();

    // Create runnable for posting
    final Runnable mUpdateResults = new Runnable() {
        public void run() {
            updateResultsInUi();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        [ . . . ]
    }

    protected void startLongRunningOperation() {

        // Fire off a thread to do some work that we shouldn't do directly in the UI thread
        Thread t = new Thread() {
            public void run() {
                mResults = doSomethingExpensive();
                mHandler.post(mUpdateResults);
            }
        };
        t.start();
    }

    private void updateResultsInUi() {

        // Back in the UI thread -- update our UI elements based on the data in mResults
        [ . . . ]
    }
}
Run Code Online (Sandbox Code Playgroud)