介绍,该例子主要是利用Handle的消息机制实现一个音乐播放器;用AsyncTask形式实现点击按钮就更改UI界面的文字信息。两种方式都是多线程的通信方式。具体注释贴代码如下:
HandleMessageActivity.java
import java.security.PublicKey; import android.app.Activity; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import android.os.Looper; import android.content.Intent; public class HandleMessageActivity extends Activity { /** Called when the activity is first created. */ private Button mBtnPlayMusic = null; private Button mBtnStopMusic = null; private Button mBtnChangeWelInfo = null; private TextView mTextShowMusicName = null; private TextView mTextWelcomeInfo = null; Looper loop = Looper.myLooper();//获取主线程的looper MyHandle myHandle = new MyHandle();//new一个Handle,来处理主线程的消息信息 private String mArgs = null;//这个用于AsyncTask中的参数传递。 @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mBtnPlayMusic = (Button)findViewById(R.id.play_music); mBtnStopMusic = (Button)findViewById(R.id.stop_music); mBtnChangeWelInfo = (Button)findViewById(R.id.changeText); mTextShowMusicName = (TextView)findViewById(R.id.music_name); mTextWelcomeInfo = (TextView)findViewById(R.id.welcomeinfo); /** * 实现播放音乐的功能 */ mBtnPlayMusic.setOnClickListener(new Button.OnClickListener(){ @Override public void onClick(View v) { // TODO Auto-generated method stub new Thread(){ public void run(){ //实现细节 System.out.println(" star music:Current Thread ID is:"+Thread.currentThread().getId()); System.out.println("star music Current Thread Name is:"+Thread.currentThread().getName()); //获取包内的资源:取得music的全路径名称 String musicName = getResources().getString(R.raw.dongni); System.out.println("the full of music name and path is:"+musicName);// res/raw/dongni.mp3 System.out.println("the full of resource name and path is:"+getResources().getResourceName(R.raw.dongni));//这里返回的包含了包得路径 //获取路径,不需要后缀名 int b = musicName.lastIndexOf("/"); int e = musicName.lastIndexOf("."); String musicTrueName = musicName.substring(b+1, e); /** * 定义消息,并和Handle关联起来,这里注意的是,该消息只会和所定义的Handle关联起来, * 而我们这里的Handle是在UI主线程里面创建的,所以此处的消息是会发送给UI的消息队列的。 */ Message message = myHandle.obtainMessage(); message.arg1 = 0;//用于区分在哪个线程里面发过来的Handle消息。 message.obj = musicTrueName;//所发送的对象 message.sendToTarget();//将消息发送给UI线程。 Intent intent = new Intent(HandleMessageActivity.this,MusicServer.class); startService(intent);//启动service } }.start(); } }); /** * 实现停止音乐播放的功能 */ mBtnStopMusic.setOnClickListener(new Button.OnClickListener(){ public void onClick(View v){ new Thread() { @Override public void run() { // TODO Auto-generated method stub System.out.println("stop music Current Thread ID is:"+Thread.currentThread().getId()); System.out.println("stop music Current Thread Name is:"+Thread.currentThread().getName()); Message stopMsg = myHandle.obtainMessage();//获取消息对象,表示要发送给myHandle的消息 stopMsg.arg1 = 1;//给消息赋值 stopMsg.sendToTarget();//发给myHandle Intent intent = new Intent(HandleMessageActivity.this,MusicServer.class); stopService(intent);//停止service } }.start(); } }); /** * 改变欢迎信息,这里使用AsynTask的方式来执行 */ mBtnChangeWelInfo.setOnClickListener(new Button.OnClickListener(){ public void onClick(View v){ System.out.println("in mBtnChangeWelInfo ,Current Thread ID is:"+Thread.currentThread().getId()); System.out.println("in mBtnChangeWelInfo ,Current Thread Name is:"+Thread.currentThread().getName()); mArgs = "100"; new AsynTask().execute(mArgs); /* new Runnable() { @Override public void run() { System.out.println("Current Thread ID is:"+Thread.currentThread().getId()); System.out.println("Current Thread Name is:"+Thread.currentThread().getName()); Message changeTextMsg = myHandle.obtainMessage(); changeTextMsg.arg1 = 20; changeTextMsg.obj = "改变欢迎信息"; changeTextMsg.sendToTarget(); } }.run(); */ } }); } /** * * @author bluesky * 定义主线程的处理程序,这里我们复写handleMessage来处理发送给UI线程的消息。 */ class MyHandle extends Handler{ public MyHandle(){ } public MyHandle(Looper loop){ super(loop); } @Override public void dispatchMessage(Message msg) { // TODO Auto-generated method stub super.dispatchMessage(msg); } @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub super.handleMessage(msg); switch(msg.arg1){ case 0: CharSequence getMusicName = (CharSequence)msg.obj; mTextShowMusicName.setText(getMusicName); break; case 1: CharSequence change = "no music played"; mTextShowMusicName.setText(change); break; // case 20: //mTextWelcomeInfo.setText(msg.obj.toString()); //break; default: break; } } @Override public boolean sendMessageAtTime(Message msg, long uptimeMillis) { // TODO Auto-generated method stub return super.sendMessageAtTime(msg, uptimeMillis); } @Override public String toString() { // TODO Auto-generated method stub return super.toString(); } } /** * * @author bluesky * 异步消息处理类,用于处理异步操作。 */ class AsynTask extends AsyncTask<String, String, String>{ /** * 后台进行一些处理操作,然后将返回的结果送给onPostExecute, * onPostExecute可以依据放回的结果来更新UI的操作。 * 在线程池中操作 */ @Override protected String doInBackground(String... params) { // TODO Auto-generated method stub System.out.println("do InBackground,Current Thread ID is:"+Thread.currentThread().getId()); System.out.println("do InBackground,Current Thread Name is:"+Thread.currentThread().getName()); String getParam = null; getParam = params[0]; String progress = "测试更新进度"; publishProgress(progress); return getParam; } /** * 可以再处理的过程中取消异步线程处理。 */ @Override protected void onCancelled() { // TODO Auto-generated method stub System.out.println("do onCancelled,Current Thread ID is:"+Thread.currentThread().getId()); System.out.println("do onCancelled,Current Thread Name is:"+Thread.currentThread().getName()); super.onCancelled(); } /** * 从doInBackground获取执行后的结果,然后可以对UI的主界面进行更新操作。 * 在主线程中操作 */ @Override protected void onPostExecute(String result) { // TODO Auto-generated method stub System.out.println("do onPostExecute,Current Thread ID is:"+Thread.currentThread().getId()); System.out.println("do onPostExecute,Current Thread Name is:"+Thread.currentThread().getName()); if(result == "100"){ mTextWelcomeInfo.setText("AsynTask方式改变UI显示!"); } } /** * 在主线程中进行一系列的准备工作。 * */ @Override protected void onPreExecute() { // TODO Auto-generated method stub System.out.println("do onPreExecute,Current Thread ID is:"+Thread.currentThread().getId()); System.out.println("do onPreExecute,Current Thread Name is:"+Thread.currentThread().getName()); Toast.makeText(HandleMessageActivity.this, "开始使用AsynTask来进行进程中通信", Toast.LENGTH_LONG).show(); super.onPreExecute(); } /** * 主线程中用于显示进度的函数,该函数由doInBackground()调用publishProgress()函数��结果发送过来。 */ @Override protected void onProgressUpdate(String... values) { // TODO Auto-generated method stub String getProgress = values[0]; System.out.println("do onProgressUpdate,Current Thread ID is:"+Thread.currentThread().getId()); System.out.println("do onProgressUpdate,Current Thread Name is:"+Thread.currentThread().getName()); System.out.println("do onProgressUpdate,Current value get from doInBackGround is:"+getProgress); } } }