上一篇我們說到了Toast的基本應用的代碼實現,下面我們來說下它在線程中的使用;
大家都知道和UI顯示相關的都應該在UI線程上執行(也就是主線程);
那麼如果想監聽子線程來顯示Toast我們可以用Handler來實現,當子線程執行完後,調用mHandler.sendMessage(msg);來通知主線程執行Toast顯示;
在主線程中的代碼:
- private final Handler mHandler = new Handler(){
- public void handleMessage(Message msg) {
- switch (msg.arg1) {
- case “1”:
- Toast.makeText(getApplicationContext(),"顯示toast",Toast.LENGTH_SHORT).show();
- break;
- default:
- break;
- }
- }
- };
- Message msg = mHandler.obtainMessage();
- msg.arg1 = “1”;
- mHandler.sendMessage(msg);
Can’t create handler inside thread that has not calledLooper.prepare();
其實這個報錯網上一查就能知道是在非UI線程實現UI顯示;
如果不用上面說的Handle,還可以用下面的代碼來實現:
- final Thread mThread = new Thread(new Runnable() {
- @Override
- public void run()
- {
- Looper.prepare();
- Toast.makeText(getApplicationContext(), "顯示toast",
- Toast.LENGTH_SHORT).show();
- Looper.loop();
- }
- });
- mThread.start();