Handler

1、handler.post(runnable);运行的runnable接口仍然是在主线程中运行的。。

是否在主线程运行的区别在于是否有start方法。。比如new Thread().start();

2、Handler 默认运行在主线程中。

Msg Quene消息队列。。。。。。

如果需要在子线程中运行handler类 需要开启Looper 使用相当于获取主线程的Msg quene。。Looper.prepare();开启Looper.loop();开始循环

package com.example.asynthreadtest1;

import java.util.concurrent.ExecutionException;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;
import android.app.Activity;
import android.content.AsyncTaskLoader;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;

public class MainActivity extends Activity {
	ProgressBar progress;
	Button button;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		progress=(ProgressBar) findViewById(R.id.progressBar4);
		System.out.println("OnCreate"+Thread.currentThread().getId());
		button=(Button) findViewById(R.id.button1);
		button.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				MyThread myThread=new MyThread();
				myThread.start();
				
			}
		});
	}
	
	class MyThread extends Thread{
		@Override
		public void run() {
			// TODO Auto-generated method stub
			Looper.prepare();
			Handler handler=new Handler(){
				@Override
				public void handleMessage(Message msg) {
					// TODO Auto-generated method stub
					System.out.println("handler msg");
					super.handleMessage(msg);
				}
			};
			handler.sendEmptyMessage(1);
			Looper.loop();
			super.run();
		}
	}
}

 使用HandlerThread为我们封装了下线程,不需要手动开启消息循环队列

HandlerThread thread=new HandlerThread("hello");
				thread.start();
				handler=new Handler(thread.getLooper()){
					@Override
					public void handleMessage(Message msg) {
						// TODO Auto-generated method stub
						System.out.println("handlerMsg "+Thread.currentThread().getId());
						super.handleMessage(msg);
					}
				};
				handler.sendEmptyMessage(1);

3、子线程中运行

HandlerThread  thread=new HandlerThread("MyHandlerThread");
		thread.start();
		handler=new Handler(thread.getLooper());
		handler.post(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
			}
		});

 注意如果该线程运行很久的话考虑在onDestory();

hanlder.mHandler.removeCallbacks(mBackgroundRunnable);

相关推荐