[Android]简单的Handler样例,通过线程队列和消息队列操作一个ProgressBar

      Handler主要用于异步消息的处理。

      这里点击了按钮之后在run方法中设置message的alg1的值,每次通过sendMessage把message对象压入消息队列。在handleMessage方法中取出消息队列中的message对象,并设置progressBar的值,然后再把线程对象加入线程队列。这个循环一直运行到进度条走到头~~。

 

package com.example.prograssbarhandle;

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 {
	private ProgressBar pb1=null;
	private Button bt1=null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bt1=(Button)findViewById(R.id.but);
        pb1=(ProgressBar)findViewById(R.id.firstBar);
        pb1.setVisibility(View.VISIBLE);
        bt1.setOnClickListener(new bt1listener());
    }	

    class bt1listener implements OnClickListener{

		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			hl1.post(run1);
		}
    	
    }
    
    Handler hl1=new Handler()
    {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			pb1.setProgress(msg.arg1);
			hl1.post(run1);
		}
    	
    };
    
    Runnable run1=new Runnable()
    {
    	int i=0;
		public void run() {
			// TODO Auto-generated method stub
			i+=10;
			//得到一个消息对象
			Message msg=hl1.obtainMessage();
			msg.arg1=i;
			try{
				Thread.sleep(1000);
			}catch(InterruptedException e){
				e.printStackTrace();
			}
			if(i>=100){
				i=0;
				pb1.setProgress(i);
		//		bt1.setText("dawda");
				hl1.removeCallbacks(run1);
				return;
			}
			hl1.sendMessage(msg);
		}
    	
    };
     
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

 

<LinearLayout 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:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world"
        tools:context=".MainActivity" />
    <Button 
        android:id="@+id/but"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="start"
        />
    <ProgressBar
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:id="@+id/firstBar"
        style="?android:attr/progressBarStyleHorizontal" 
        />

</LinearLayout>
 

你可能感兴趣的:(android,handler,message,bbezxcy)