android asynctask例子,Android AsyncTask示例和解释

AsyncTask是在Android中实现并行性的最简单方法之一,而无需处理诸如Threads之类的更复杂的方法。尽管它提供了与UI线程的基本并行度,但不应将其用于更长的操作(例如,不超过2秒)。

AsyncTask有四种方法

onPreExecute()

doInBackground()

onProgressUpdate()

onPostExecute()

在哪里doInBackground()最重要,因为在哪里执行后台计算。

码:

这是带有说明的骨骼代码概述:

public class AsyncTaskTestActivity extends Activity {

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

// This starts the AsyncTask

// Doesn't need to be in onCreate()

new MyTask().execute("my string parameter");

}

// Here is the AsyncTask class:

//

// AsyncTask.

//    Params – the type (Object/primitive) you pass to the AsyncTask from .execute()

//    Progress – the type that gets passed to onProgressUpdate()

//    Result – the type returns from doInBackground()

// Any of them can be String, Integer, Void, etc.

private class MyTask extends AsyncTask {

// Runs in UI before background thread is called

@Override

protected void onPreExecute() {

super.onPreExecute();

// Do something like display a progress bar

}

// This is run in a background thread

@Override

protected String doInBackground(String... params) {

// get the string from params, which is an array

String myString = params[0];

// Do something that takes a long time, for example:

for (int i = 0; i <= 100; i++) {

// Do things

// Call this to update your progress

publishProgress(i);

}

return "this string is passed to onPostExecute";

}

// This is called from background thread but runs in UI

@Override

protected void onProgressUpdate(Integer... values) {

super.onProgressUpdate(values);

// Do things like update the progress bar

}

// This runs in UI when background thread finishes

@Override

protected void onPostExecute(String result) {

super.onPostExecute(result);

// Do things like hide the progress bar or change a TextView

}

}

}

流程图:

这是一个图表,以帮助解释所有参数和类型的去向:

acd75f8ea8ea4027221a4708a959daa2.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值