从Android的辅助线程调用主线程
如何从Android的辅助线程调用主线程?
最简单的方法是从你的线程调用runOnUiThread(…)
activity.runOnUiThread(new Runnable() { public void run() { ... do your GUI stuff } });
我build议在同一个进程中交stream线程是在这些线程之间发送消息。 使用处理程序pipe理这种情况非常简单:
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 [ . . . ] } }
您将需要一个Handler
,将信息传递回主线程。
另外,最好记住,如果通过AsyncTask获得辅助线程,则可以select调用onProgressUpdate() , onPostExecute()等来在主线程上工作。
使用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(); } }
说明:
-
在上面的例子中,
HandlerThread
在UI Thread的Handler
上发布了一个Message
,该Message
已经被UI Thread的Looper
初始化了。final Handler responseHandler = new Handler(Looper.getMainLooper())
-
responseHandler.sendMessage(msg);
将Message
从HandlerThread
发送到UI线程Handler
。 -
handleMessage
处理在MessageQueue
收到的Message
,并在UI线程上显示Toast。