Android学习笔记-Handler的使用

来源:互联网 发布:新加坡李家王朝 知乎 编辑:程序博客网 时间:2024/05/18 05:03

wKiom1RrObPwHDA6AAAyoqkfsXA679.jpg

点击Start按钮,每隔3秒在Logcat里打印一句话

    <Button         android:id="@+id/startButton"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="Start"/>    <Button         android:id="@+id/endButton"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:layout_below="@id/startButton"        android:text="End"/>

MainActivity.java

public class MainActivity extends ActionBarActivity {private Button startButton = null;private Button endButton = null;Handler handler = new Handler();@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);startButton = (Button) findViewById(R.id.startButton);endButton = (Button) findViewById(R.id.endButton);startButton.setOnClickListener(new StartButtonListener());endButton.setOnClickListener(new EndButtonListener());}class StartButtonListener implements OnClickListener{@Overridepublic void onClick(View v) {handler.post(updateThread);}}class EndButtonListener implements OnClickListener{@Overridepublic void onClick(View v) {handler.removeCallbacks(updateThread);}}Runnable updateThread = new Runnable() {@Overridepublic void run() {System.out.println("updateThread");handler.postDelayed(updateThread, 3000);}};}



wKioL1RsA8uAOtQcAABIB_CLOpQ916.jpg

点击Start按钮之后每隔11000毫秒进度条增加10%

界面 activity_main.xml

    <ProgressBar         android:id="@+id/bar"        style="?android:attr/progressBarStyleHorizontal"        android:layout_width="200dp"        android:layout_height="wrap_content"        android:visibility="gone"/>    <Button         android:id="@+id/startButton"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:layout_below="@id/bar"        android:text="Start"/>

MainActivity.java

public class MainActivity extends ActionBarActivity {private ProgressBar bar = null;private Button startButton = null;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);bar = (ProgressBar) findViewById(R.id.bar);startButton = (Button) findViewById(R.id.startButton);startButton.setOnClickListener(new ButtonListener());}//当点击StartButton按钮时就会执行ButtonListener的onClick方法class ButtonListener implements OnClickListener{@Overridepublic void onClick(View v) {System.out.println("Onclick");Toast.makeText(MainActivity.this, "Onclick", Toast.LENGTH_SHORT).show();bar.setVisibility(View.VISIBLE);updateBarHandler.post(updateThread);}}//使用匿名内部类来复写Handler当中的handleMessage方法Handler updateBarHandler = new Handler(){public void handleMessage(android.os.Message msg) {bar.setProgress(msg.arg1);updateBarHandler.post(updateThread);};};//线程类,使用匿名内部类的方式进行声明Runnable updateThread = new Runnable() {int i = 0;@Overridepublic void run() {System.out.println("Begin Thread");i = i + 10;//得到一个消息对象。Message类是由Android操作系统提供。Message msg = updateBarHandler.obtainMessage();//使用arg1和arg2这两个成员变量传递消息,优点是节省系统资源msg.arg1 = i;try {//设置当前线程睡眠一秒Thread.sleep(1000);} catch (Exception e) {e.printStackTrace();}//将msg加入到消息队列当中updateBarHandler.sendMessage(msg);if (i== 100) {System.out.println(" i ==100");updateBarHandler.removeCallbacks(updateThread);}}};}



wKiom1RsREXQ2-iJAAD2GgS2bl8428.jpg

可以看到处理消息的线程和主线程是同一个线程

public class MainActivity extends ActionBarActivity {private Handler handler = new Handler();@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);handler.post(runnable);/*如果采用这种方式则会创建新的线程Thread thread = new Thread(runnable);thread.start();*/setContentView(R.layout.activity_main);// 要等10秒钟才显示System.out.println("Activity:" + Thread.currentThread().getId());System.out.println("ActivityName:" + Thread.currentThread().getName());}// 上面打印的信息和下面打印的信息是一样的// Handler处理线程的时候并没有创建新的线程Runnable runnable = new Runnable() {@Overridepublic void run() {System.out.println("Handler:" + Thread.currentThread().getId());System.out.println("HandlerName:"+ Thread.currentThread().getName());try {Thread.sleep(10000);} catch (Exception e) {}}};}




wKiom1RsRhPylF6wAAEVrkZ90W0325.jpg

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

public class MainActivity extends ActionBarActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//打印当前线程的IDSystem.out.println("MainActivity>>>" + Thread.currentThread().getId());//生成一个HandlerThread对象,实现了使用Looper来处理消息队列的功能HandlerThread handlerThread = new HandlerThread("handler_Thread");handlerThread.start();MyHandler myHandler = new MyHandler(handlerThread.getLooper());Message msg = myHandler.obtainMessage();//msg.obj = "abc"; //简单数据Bundle bundle = new Bundle();bundle.putInt("age", 20);bundle.putString("name", "umgsai");msg.setData(bundle);//将msg发送到目标对象,即生成msg对象的Handler对象msg.sendToTarget();}class MyHandler extends Handler {public MyHandler() {}public MyHandler(Looper looper) {super(looper);}@Overridepublic void handleMessage(Message msg) {super.handleMessage(msg);//String s = (String) msg.obj;   //取出数据Bundle bundle = msg.getData();System.out.println("age:" + bundle.getInt("age") + ",name:" + bundle.getString("name"));System.out.println("Handler>>>" + Thread.currentThread().getId());System.out.println("handlerMeaage");}}}


本文出自 “优赛工作室” 博客,请务必保留此出处http://shamrock.blog.51cto.com/2079212/1579277

0 0
原创粉丝点击