public void sendMessage() {
MHandler mHandler = new MHandler();
Message msg = mHandler.obtainMessage();
msg.sendToTarget();
}
Service 中,onStart的执行也是阻塞的。如果一个startService在onStart执行完成之前,再次条用startService也会阻塞。如果希望能尽快的执行onStart则可以在onStart中使用handler,因为Message的send是非阻塞的。
public void sendMessageWithLooper() {
HandlerThread ht = new HandlerThread("Rintail");
ht.start();
MHandler mHandler = new MHandler(ht.getLooper());
向Handler对象发送类似new Message ()形式的空Message可以达到清空Message的目的,这种做法与getLooper().quit()的做法是一样的。如果利用的资源较多,应及时清理。
-----------------------------------------------外面的线程也在做,handler里的发了消息也做 两个同时做(只不过不知道哪个是主,,,研究了几个 哪个是主吖次吖吖吖吖吖 吖 吖吖 ~~~~~~~~~~~·)
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
sendMessageWithLooper();
//sendMessage();
}
public void sendMessage() {
MHandler mHandler = new MHandler();
Message msg = mHandler.obtainMessage();
msg.sendToTarget();
}
public void sendMessageWithLooper() {
HandlerThread ht = new HandlerThread("Rintail");
ht.start();
MHandler mHandler = new MHandler(ht.getLooper());
Message msg = mHandler.obtainMessage();
msg.sendToTarget();
}
class MHandler extends Handler {
public MHandler() {
}
public MHandler(Looper l) {
super(l);
}
@Override
public void handleMessage(Message msg) {
Log.d(TAG, "first");
while (true) {
if (false)
break;
}
Log.d(TAG, "second");
}
};
class MyThread extends Thread {
@Override
public void run() {
Log.d(TAG, "first");
while (true) {
if (false)
break;
}
Log.d(TAG, "second");
}
};