Android的两种异步调用

[color=darkblue][b]1. Handler + Thread[/b][/color]
[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();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值