gpt4 book ai didi

Android AsyncTask 示例及说明

转载 作者:IT王子 更新时间:2023-10-29 00:04:30 24 4
gpt4 key购买 nike

我想在我的应用程序中使用 AsyncTask,但我无法找到一个简单解释事情工作原理的代码 fragment 。我只是想要一些东西来帮助我快速恢复速度,而不必涉水the documentation或再次进行大量问答。

最佳答案

AsyncTask 是在 Android 中实现并行性的最简单方法之一,无需处理线程等更复杂的方法。尽管它提供了与 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, Progress, Result>.
// 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<String, Integer, String> {

// 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
}
}
}

流程图:

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

enter image description here

其他有用的链接:

关于Android AsyncTask 示例及说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25647881/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com