MainActivity如下:
package cc.c; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.app.Activity; /** * Demo描述: * Handler常用方法 * 1 sendMessage() * 2 post() * 3 postDelayed() * 4 handleMessage() */ public class MainActivity extends Activity { private Runnable mRunnable; private Handler mHandler; private final int CANCEL_RUNNABLE = 99; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); initTest(); } private void initTest() { System.out.println("UI线程ID=" + Thread.currentThread().getId()); mHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (msg.what == 1) { System.out.println("收到mHandler.sendMessage()方法发来的消息"); } if (msg.what == CANCEL_RUNNABLE) { System.out.println("取消Runnable的执行"); if (mRunnable != null) { removeCallbacks(mRunnable); } } } }; // 为方便测试将以下三个方法分别调用 // testSendMessage(); // testPost(); testPostDelayed(); } /** * Handler调用sendMessage()发送消息 */ private void testSendMessage() { new Thread() { @Override public void run() { super.run(); Message message = new Message(); message.what = 1; message.obj = new Object(); mHandler.sendMessage(message); } }.start(); } /** * Handler调用post()发送Runnable(本质也是发送消息) */ private void testPost() { mRunnable = new Runnable() { public void run() { System.out.println("Runnable所属线程ID="+Thread.currentThread().getId()); for (int i = 0; i < 5; i++) { System.out.println("Runnable中的i=" + i); } } }; mHandler.post(mRunnable); } /** * Handler调用postDelayed()发送延迟的Runnable(本质也是发送消息) */ private void testPostDelayed() { mRunnable = new Runnable() { public void run() { System.out.println("Runnable所属线程ID="+Thread.currentThread().getId()); for (int i = 10; i < 16; i++) { System.out.println("Runnable中的i=" + i); } } }; // 1 发送带有延迟的Runnable mHandler.postDelayed(mRunnable, 1000); // 2 也可按照业务需求取消该mRunnable // 即调用removeCallbacks(mRunnable); // 等同于调用mHandler.sendEmptyMessage(CANCEL_RUNNABLE); mHandler.removeCallbacks(mRunnable); } }
main.xml如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /> </RelativeLayout>
时间: 2024-11-05 18:57:27