最近在做一个批量安装卸载的管理器,在安装的过程中要显示安装信息,比如说:"正在安装XX1.apk 正在安装XX2.apk“当然这个显示是在对话框上面显示的。怎么做呢?实现是这样的:
1、在Activity中重写onCreateDialog(int id)方法;
2、使用Handler更新对话框的信息;
3、用线程监控安装信息,将信息设置在Message中通过Handler发送。
具体实现请看代码:
package cn.tch.cdg; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class CustomDialogActivity extends Activity { private static final int PROGRESS_DIALOG = 0; private Button btnShowDialog; private ProgressThread mProgressThread; private Dialog mDialog; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); btnShowDialog = (Button) findViewById(R.id.progressDialog); btnShowDialog.setOnClickListener(new OnClickListener(){ public void onClick(View v) { showDialog(PROGRESS_DIALOG); } }); } protected Dialog onCreateDialog(int id) { switch(id) { case PROGRESS_DIALOG: mDialog = new AlertDialog.Builder(CustomDialogActivity.this).create(); mDialog.setTitle("请稍候"); ((AlertDialog) mDialog).setMessage(""); mProgressThread = new ProgressThread(handler); mProgressThread.start(); return mDialog; default: return null; } } final Handler handler = new Handler() { public void handleMessage(Message msg) { int total = msg.getData().getInt("total"); String message = msg.getData().getString("message"); ((AlertDialog) mDialog).setMessage(message); if (total >= 100){ dismissDialog(PROGRESS_DIALOG); mProgressThread.setState(ProgressThread.STATE_DONE); } } }; private class ProgressThread extends Thread { Handler mHandler; final static int STATE_DONE = 0; final static int STATE_RUNNING = 1; int mState; int mTotal; ProgressThread(Handler handler) { mHandler = handler; } public void run() { mState = STATE_RUNNING; mTotal = 0; while (mState == STATE_RUNNING) { Message msg = mHandler.obtainMessage(); Bundle bundle = new Bundle(); bundle.putInt("total", mTotal); bundle.putString("message", "正在安装:"+mTotal); // 设置Message msg.setData(bundle); mHandler.sendMessage(msg); mTotal++; try { Thread.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); } } } public void setState(int state) { mState = state; } } }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <Button android:id="@+id/progressDialog" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="显示对话框"/> </LinearLayout>