[color=darkblue][b]1. Handler + Thread[/b][/color]
[color=red]由主线程打开对话框, 然后使用新的线程(Handler.sendMessage(message))对它进行操作, 包括修改和关闭等.[/color]
定义
调用
[color=darkblue][b]2. AsyncTask[/b][/color],参考:[url]http://www.cnblogs.com/jingd/archive/2012/03/10/2389648.html[/url]
异步处理程序
调用:
[color=red]由主线程打开对话框, 然后使用新的线程(Handler.sendMessage(message))对它进行操作, 包括修改和关闭等.[/color]
定义
class MyHandler extends Handler {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg); //To change body of overridden methods use File | Settings | File Templates.
switch (msg.what) {
case PRO_ADD:
progressBar.setProgress(count);
break;
}
}
}
}
调用
package com.example.ADemo6;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;
public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/
private static final int PRO_ADD = 1;
private ProgressBar progressBar;
private MyHandler myHandler = new MyHandler();
private int count=0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button1 = (Button) findViewById(R.id.button1);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final int max = progressBar.getMax();
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
for (int i = 0; i < max; i++) {
Message message = new Message();
Thread.sleep(50);
if (i > 100) {
count = 100;
message.what = PRO_ADD;
myHandler.sendMessage(message);
} else {
count = progressBar.getProgress()+2;
message.what = PRO_ADD;
myHandler.sendMessage(message);
}
}
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
});
thread.start();
}
});
}
}
[color=darkblue][b]2. AsyncTask[/b][/color],参考:[url]http://www.cnblogs.com/jingd/archive/2012/03/10/2389648.html[/url]
异步处理程序
class AnsyTry extends AsyncTask<String, TextView, Double> {
TextView te = null;
public AnsyTry(TextView te) {
super();
this.te = te;
}
@Override
protected Double doInBackground(String... params) {
double dou = 0;
dou = 100;
searchFromWebService(te); //处理事情的方法......
publishProgress(te);
return dou;
}
@Override
protected void onPostExecute(Double result) {
super.onPostExecute(result);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onProgressUpdate(TextView... values) {
super.onProgressUpdate(values);
}
}
调用:
AnsyTry anys = new AnsyTry(textView2);
anys.execute();