ProgressDialog 是Android中很常用的处理后台线程显示前台界面的工具
package com.testprogressdialog;
import java.io.File;
import java.net.URLEncoder;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class TestProgressDialog extends Activity {
private ProgressDialog dialog;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
dialog = new ProgressDialog(this);
dialog.setMessage("运行中...");
dialog.setIndeterminate(false);
dialog.setCancelable(true);
Button bt1=(Button)findViewById(R.id.button1);
bt1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog.show();
Thread thread = new Thread(new ThreadDemo());
thread.start();
}
});
}
final Handler handle = new Handler()
{
@Override
public void handleMessage(Message msg)
{
if(dialog!=null)
{
dialog.dismiss();
}
if( msg.what>0 )
{
Toast.makeText(TestProgressDialog.this, "线程成功结束", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(TestProgressDialog.this, "线程出现意外", Toast.LENGTH_SHORT).show();
}
}
};
Handler endSessionHandle = new Handler()
{
@Override
public void handleMessage(Message msg)
{
finish();
}
};
class ThreadDemo implements Runnable
{
public void run()
{
int what = -1;
try
{
for (int i=0;i<10;i++)
{
Thread.sleep(1000);
if (i==9)
{what=1;
}
}
}
catch (Exception e)
{
e.printStackTrace();
Log.e("WeiboPub", e.getMessage());
}
handle.sendEmptyMessage(what);
}
}
}
另一种 :通过异步实现:
其实都是和线程操作有关的东西
thread的run()残缺返回值于是+handler组合就可以做出时候用户体验的界面+线程运作了
而asyn直接实现就可以了
class InitTask extends AsyncTask<Integer, Integer, String>{
//后面尖括号内分别是参数(例子里是线程休息时间),进度(publishProgress用到),返回值 类型
@Override
protected void onPreExecute() {
//第一个执行方法
pdialog.show();
super.onPreExecute();
}
@Override
protected String doInBackground(Integer... params) {
//第二个执行方法,onPreExecute()执行完后执行
initoken();
return "初始化完毕,请继续操作!";
}
@Override
protected void onProgressUpdate(Integer... progress) {
//这个函数在doInBackground调用publishProgress时触发,虽然调用时只有一个参数
//但是这里取到的是一个数组,所以要用progesss[0]来取值
//第n个参数就用progress[n]来取值
// if (progress[0] == 100)setTitle(R.string.app_name);
super.onProgressUpdate(progress);
}
@Override
protected void onPostExecute(String result) {
//doInBackground返回时触发,换句话说,就是doInBackground执行完后触发
//这里的result就是上面doInBackground执行后的返回值,所以这里是"执行完毕"
pdialog.dismiss();
setTitle(result);
super.onPostExecute(result);
}
}
这个的功能就是在线程运行时候显示progressdialog,线程结束dialog消失