Android线程显示进度框
package com.test.threadtest1; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.app.Activity; import android.app.Dialog; import android.app.ProgressDialog; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; /** * * @author Sean * */ public class ThreadTest1Activity extends Activity { private Button btn; private Thread mThread; private static final int PROGRESS_DIALOG=10; ProgressDialog progressDialog=null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_thread_test1); btn=(Button)findViewById(R.id.button1); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub //创建新线程 mThread = new Thread(runable); mThread.start(); //主线程执行UI更新显示 showDialog(PROGRESS_DIALOG); } }); } private Handler mHandler=new Handler(){ public void handleMessage(Message msg){ switch(msg.what) { case 300: if(msg.arg1==msg.arg2) { //移除对话框 removeDialog(PROGRESS_DIALOG); } else { //显示进度 progressDialog.setProgress(msg.arg1*100/msg.arg2); } } } }; //创建Dialog样式 protected Dialog onCreateDialog(int id){ switch(id) { case PROGRESS_DIALOG: progressDialog= new ProgressDialog(this); progressDialog.setTitle("后台处理"); progressDialog.setMessage("请稍候,正在处理。。。"); progressDialog.setIndeterminate(false); progressDialog.setCancelable(true); progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressDialog.setProgress(0); return progressDialog; } return super.onCreateDialog(id); } //创建Runnable执行后台任务 Runnable runable=new Runnable() { @Override public void run() { // TODO Auto-generated method stub int total=100; int current=0; while(current<=total) { try { //模拟进程时间 Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } Message msg=mHandler.obtainMessage(300); msg.arg2=total; msg.arg1=current; current+=10; mHandler.sendMessage(msg); } } }; @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_thread_test1, menu); return true; } }