简体   繁体   中英

Call Main thread from secondary thread in Android

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

The simplest way is to call runOnUiThread(...) from your thread

activity.runOnUiThread(new Runnable() {
    public void run() {
        ... do your GUI stuff
    }
});

My recommendation to communicate threads in the same process is sending messages between those threads. It is very easy to manage this situation using Handlers:

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

Example of use, from Android documentation, to handling expensive work out of the ui thread:

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
        [ . . . ]
    }
}

此外,最好记住,如果通过AsyncTask获得辅助线程,则可以选择调用onProgressUpdate()onPostExecute()等来对主线程进行操作。

您需要一个将信息传递回主线程的Handler

Sample code using HandlerThread

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final Handler responseHandler = new Handler(Looper.getMainLooper()){
            @Override
            public void handleMessage(Message msg) {
                //txtView.setText((String) msg.obj);
                Toast.makeText(MainActivity.this,
                        "Result from UIHandlerThread:"+(int)msg.obj,
                        Toast.LENGTH_LONG)
                        .show();
            }
        };

        HandlerThread handlerThread = new HandlerThread("UIHandlerThread"){
            public void run(){
                /* Add your business logic to pupulate attributes in Message
                   in place of sending Integer 5 as in example code */
                Integer a = 5;
                Message msg = new Message();
                msg.obj = a;
                responseHandler.sendMessage(msg);
                System.out.println(a);
            }
        };
        handlerThread.start();

    }

}

Explanation:

  1. In above example, HandlerThread post a Message on Handler of UI Thread, which has been initialized with Looper of UI Thread.

     final Handler responseHandler = new Handler(Looper.getMainLooper()) 
  2. responseHandler.sendMessage(msg); sends Message from HandlerThread to UI Thread Handler .

  3. handleMessage processes Message received on MessageQueue and shows a Toast on UI Thread.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM