子线程中创建handler

方法1、

android显示操作界面,需要在主线程中执行

不在主线程中需要在handler中执行
Looper.prepare();
myhandler = new Handler(new Handler.Callback() {
public boolean handleMessage(Message msg) {
return false;
}
});
Looper.loop();

必须开始Looper但是开启的时刻可以自己控制

方法2、

 public static ServiceHandler mHandler;
 // Handler that receives messages from the thread
public final class ServiceHandler extends Handler {
     public ServiceHandler(Looper looper) {
         super(looper);
     }
     @Override
     public void handleMessage(Message msg) {
    switch (msg.what) {
case 1:
break;
case 2:
default:
break;
}
     }
 }

Service的onCreate中调用

 HandlerThread handlerThread = new HandlerThread("ATMSServiceName",Process.THREAD_PRIORITY_BACKGROUND);
   handlerThread.start();
  // Get the HandlerThread's Looper and use it for our Handler
 mServiceLooper = handlerThread.getLooper();
 mHandler = new ServiceHandler(mServiceLooper);
 

你可能感兴趣的:(Android基础)