标签:
Android中的多线程可以有多种实现方式,前面我们已经讲过了封装程度较高异步任务(AnsyncTask),这一节我们来看看较为灵活的方式:Handler Looper MessageQueue Message。
package com.example.katahandler; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; 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 { Button mButton; ProgressBar mProgressBar; ProgressBar mProgressBar2; static final int PROGRESS_VALUE1 = 1; static final int PROGRESS_VALUE2 = 2; int mClickCount = 0; class MyHandler extends Handler{ @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub //区分消息的种类 if ( msg.what == PROGRESS_VALUE1 ){ mProgressBar.setProgress(msg.arg1); super.handleMessage(msg); } else if ( msg.what == PROGRESS_VALUE2 ){ mProgressBar2.setProgress(msg.arg1); super.handleMessage(msg); } } } MyHandler handler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mProgressBar = (ProgressBar) findViewById(R.id.progressBar1); mProgressBar2 = (ProgressBar) findViewById(R.id.progressBar2); mButton = (Button) findViewById(R.id.button1); mButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub mClickCount++; new Thread(){ @Override public void run() { int what = 0; if(mClickCount==1) what = PROGRESS_VALUE1; else if(mClickCount==2) what = PROGRESS_VALUE2; for(int i = 0;i<100;i++){ try { sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } Message msg = handler.obtainMessage(what, i+1, 0); handler.sendMessage(msg); } super.run(); } }.start(); } }); handler = new MyHandler(); } }
Android多线程之图解Handler Looper MessageQueue Message
标签:
原文地址:http://www.cnblogs.com/childhooding/p/4340957.html