Android学习笔记20140719_Handler

Handler的实质就是异步消息处理。

实例一:

Handler的基本用法

XML布局代码:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    
    <TextView 
        android:id="@+id/tvResult"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="高兴点,未来不是梦"/>
    <Button 
        android:id="@+id/btnStart"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="动起来!"/>
     <Button 
        android:id="@+id/btnEnd"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="歇会吧!"/>
     <Button 
        android:id="@+id/btnClear"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="清零!"/>


</LinearLayout>


Java代码:

public class HandlerActivity extends Activity {

	private Button btnStart;
	private Button btnEnd;
	private Button btnClear;
	private TextView tvResult;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initContent();
	}

	private void initContent() {
		setContentView(R.layout.activity_handler);
		tvResult = (TextView) findViewById(R.id.tvResult);
		btnStart = (Button) findViewById(R.id.btnStart);
		btnEnd = (Button) findViewById(R.id.btnEnd);
		btnClear = (Button) findViewById(R.id.btnClear);
		btnStart.setOnClickListener(new StartButtonListener());
		btnEnd.setOnClickListener(new EndButtonListener());
		btnClear.setOnClickListener(new ClearButtonListener());
	}

	// 创建一个Handler对象
	Handler handler = new Handler();
	private int i = 0;
	// 将要执行的操作写在线程对象的run方法当中
	Runnable updateThread = new Runnable() {
		public void run() {
			System.out.println("高兴点,追梦!--" + i);
			tvResult.setText("高兴点,追梦!--" + i);
			i++;
			// 在run方法内部,执行postDelayed或者是post方法
			handler.postDelayed(updateThread, 3000);
		};
	};

	class StartButtonListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			// 调用Handler的post方法,将要执行的线程对象添加到队列当中
			handler.post(updateThread);
		}
	}

	class EndButtonListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			// 调用Handler的post方法,将要updateThread从队列当中移除
			handler.removeCallbacks(updateThread);
		}

	}

	class ClearButtonListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			// 调用Handler的post方法,将要updateThread从队列当中移除
			handler.removeCallbacks(updateThread);
			i = 0;
			tvResult.setText("高兴点,未来不是梦");
		}

	}
}


实例二:

Handler与ProgressBar的结合使用

XML布局代码:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >


    <ProgressBar
        android:id="@+id/progressbar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:visibility="gone" />


    <Button
        android:id="@+id/btnStart"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="前进吧,小摩托!" />


</LinearLayout>


Java代码:

public class HandlerProgressBarActivity extends Activity {

	private ProgressBar progressbar;
	private Button btnStart;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initContent();
	}

	private void initContent() {
		setContentView(R.layout.activity_handlerprogressbar);
		progressbar = (ProgressBar) findViewById(R.id.progressbar);
		btnStart = (Button) findViewById(R.id.btnStart);
		btnStart.setOnClickListener(new StartOnClick());
	}

	class StartOnClick implements OnClickListener {
		@Override
		public void onClick(View v) {
			progressbar.setVisibility(View.VISIBLE);
			updateBarHandler.post(updateThread);
		}
	}

	Handler updateBarHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			progressbar.setProgress(msg.arg1);
			updateBarHandler.post(updateThread);
		}

	};

	Runnable updateThread = new Runnable() {
		int i = 0;

		@Override
		public void run() {
			System.out.println("Begin Thread!" + i);
			i = i + 10;
			Message msg = updateBarHandler.obtainMessage();
			msg.arg1 = i;
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			updateBarHandler.sendMessage(msg);
			if (i == 100) {
				updateBarHandler.removeCallbacks(updateThread);
			}
		}

	};

}


实例三:

Handler与线程的关系(一)

XML布局代码:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="前进吧,小摩托!" />

</LinearLayout>

Java代码:

public class HandlerThreadActivity extends Activity {

	private Handler handler = new Handler();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initContent();
	}

	private void initContent() {
		handler.post(r);
		setContentView(R.layout.activity_handlerthread);
		System.out.println("activity--->"+Thread.currentThread().getId());
		System.out.println("activityname--->"+Thread.currentThread().getName());
	}
	
	Runnable r = new Runnable(){

		@Override
		public void run() {
			System.out.println("handler--->"+Thread.currentThread().getId());
			System.out.println("handlername--->"+Thread.currentThread().getName());
			try {
				Thread.sleep(10000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
	};

}


实例四:

Handler与线程的关系(二)

XML布局代码:

同【实例三】中的布局代码

Java代码:

public class HandlerThreadActivity extends Activity {

	private Handler handler = new Handler();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initContent();
	}

	private void initContent() {
		setContentView(R.layout.activity_handlerthread);
		Thread t = new Thread(r);
		t.start();
		System.out.println("activity--->" + Thread.currentThread().getId());
		System.out.println("activityname--->"
				+ Thread.currentThread().getName());
	}

	Runnable r = new Runnable() {

		@Override
		public void run() {
			System.out.println("handler--->" + Thread.currentThread().getId());
			System.out.println("handlername--->"
					+ Thread.currentThread().getName());
			try {
				Thread.sleep(10000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

	};

}

实例五:

Handler实现真正的异步消息处理,在新线程中处理消息

XML布局代码:

同【实例三】中的布局代码

Java代码:

public class HandlerMsgActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initContent();
	}

	private void initContent() {
		setContentView(R.layout.activity_handlermsg);
		// 打印当前线程
		System.out.println("activity---->" + Thread.currentThread().getId());
		// 生成一个HandlerThread对象(具有循环处理消息的功能),实现了Looper来处理消息队列
		HandlerThread handlerThread = new HandlerThread("handler_thread");
		// 让一个线程运行,必须用[线程名称].start()方法
		handlerThread.start();
		MyHandler myHandler = new MyHandler(handlerThread.getLooper());
		Message msg = myHandler.obtainMessage();
		// 将msg发动到目标对象,所谓目标对象,就是生成msg的handler对象
		msg.sendToTarget();
	}

	class MyHandler extends Handler {
		public MyHandler() {

		}

		public MyHandler(Looper looper) {
			super(looper);
		}

		@Override
		// 每当向Handler发送一个msg的时候,就会执行handleMessage()方法
		public void handleMessage(Message msg) {
			System.out.println("handler---->" + Thread.currentThread().getId());
			System.out.println("handlerMessage");
		}
	}
}

实例六:

Handler实现真正的异步消息处理,在新线程中处理消息

XML布局代码:

同【实例三】中的布局代码

Java代码:

public class HandlerMsgActivity extends Activity {


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initContent();
	}


	private void initContent() {
		setContentView(R.layout.activity_handlermsg);
		// 打印当前线程
		System.out.println("activity---->" + Thread.currentThread().getId());
		// 生成一个HandlerThread对象(具有循环处理消息的功能),实现了Looper来处理消息队列
		HandlerThread handlerThread = new HandlerThread("handler_thread");
		// 让一个线程运行,必须用[线程名称].start()方法
		handlerThread.start();
		MyHandler myHandler = new MyHandler(handlerThread.getLooper());
		Message msg = myHandler.obtainMessage();
		
		Bundle b = new Bundle();
		b.putInt("age", 20);
		b.putString("name", "滔滔1024");
		msg.setData(b);				//msg.arg1与msg.arg2的消耗比msg.setData()小,但只能传递整型变量
		// 将msg发动到目标对象,所谓目标对象,就是生成msg的handler对象,本例中是发送到MyHandler对象中
		msg.sendToTarget();		
	}


	class MyHandler extends Handler {
		public MyHandler() {


		}


		public MyHandler(Looper looper) {
			super(looper);
		}


		@Override
		// 每当向Handler发送一个msg的时候,就会执行handleMessage()方法
		public void handleMessage(Message msg) {
			Bundle b = msg.getData();
			int age = b.getInt("age");
			String name = b.getString("name");
			System.out.println("age->"+age+"\nname->"+name);
			System.out.println("handler---->" + Thread.currentThread().getId());
			System.out.println("handlerMessage");
		}
	}
}


你可能感兴趣的:(Android学习笔记20140719_Handler)