Ejemplo n.º 1
0
 @Override
 public void run() {
   Looper myLooper = Looper.myLooper();
   Looper mainLooper = Looper.getMainLooper();
   String msgobj;
   if (null == myLooper) {
     // 这里获得的是主线程的Looper,由于NoLooperThread没有自己的looper所以这里肯定会被执行
     mNoLooperThreadHandler = new EventHandler(mainLooper);
     msgobj = "NoLooperThread has no looper and handleMessage function executed in main thread!";
   } else {
     mNoLooperThreadHandler = new EventHandler(myLooper);
     msgobj =
         "This is from NoLooperThread self and handleMessage function executed in NoLooperThread!";
   }
   mNoLooperThreadHandler.removeMessages(0);
   if (bpostRunnable == false) {
     // send message to main thread
     Message msg = mNoLooperThreadHandler.obtainMessage(2, 1, 1, msgobj);
     mNoLooperThreadHandler.sendMessage(msg);
     Log.e(TAG, "NoLooperThread id:--------+>" + this.getId());
   } else {
     // 下面new出来的实现了Runnable接口的对象中run函数是在Main Thread中执行,不是在NoLooperThread中执行 记得 null == myLooper么
     // 注意Runnable是一个接口,它里面的run函数被执行时不会再新建一个线程
     // 您可以在run上加断点然后在eclipse调试中看它在哪个线程中执行
     mNoLooperThreadHandler.post(
         new Runnable() {
           public void run() {
             // TODO Auto-generated method stub
             tv.setText("update UI through handler post runnalbe mechanism!");
             Log.e(TAG, "update UI id:--------+>" + Thread.currentThread().getId());
             noLooperThread.stop();
           }
         });
   }
 }