Android消息队列

Android消息队列

public class MainActivity extends Activity { 

	@Override 
	protected void onCreate(Bundle savedInstanceState) { 
		super.onCreate(savedInstanceState); 
		setContentView(R.layout.activity_main);
		m_LooperThread.start(); 
	} 

	private final static int MSG_NOTIFY = 0x10; 
	private final static int MSG_EXIT = 0x20;
	private LooperThread m_LooperThread = new LooperThread(); 
	public void onClickSendNotifyMessage(View view) { 
		m_LooperThread.mHandler.sendEmptyMessage(MSG_NOTIFY); 
	}
	public void onClickSendExitThreadLooper(View view) { 
		m_LooperThread.mHandler.sendEmptyMessage(MSG_EXIT); 
	} 
	public class LooperThread extends Thread { 
			public Handler mHandler = null; 
			
			@Override public void run() { 
					Looper.prepare(); 
					//在线程运行起来并且调用了Looper.prepare之后才定义Handler对象 
					mHandler = new Handler() { 
					@Override 
					public void handleMessage(Message msg) { 
						switch(msg.what) { 
								case MSG_NOTIFY: 
										Log.d("TestLooper", "Notify Message!"); 
								break; 
								case MSG_EXIT: //这里获得的是线程的Looper对象,故正常退出 
										Looper.myLooper().quit(); 
								break; 
					}
				 } 
			 }; 
		 Looper.loop();//该函数只有调用Looper的quit函数后才会返回 
		 Log.d("TestLooper", "Exit the looper thread!"); 
		 } 
	 } 
 }

猜你喜欢

转载自blog.csdn.net/daoliting5268/article/details/86646824