Dhr*_*ada 61 android return-value android-asynctask
调用时AsyncTask<Integer,Integer,Boolean>,其返回值为:
protected Boolean doInBackground(Integer... params)?
通常我们启动AsyncTask new AsyncTaskClassName().execute(param1,param2......);但它似乎没有返回值.
哪里可以doInBackground()找到返回值?
Kon*_*rov 62
然后可以在onPostExecute中使用该值,您可能希望覆盖该值以便使用结果.
以下是Google文档的示例代码段:
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
Run Code Online (Sandbox Code Playgroud)
Cyr*_*oux 34
您可以doInBackground()通过调用类的get()方法来检索受保护的布尔值的返回值AsyncTask:
AsyncTaskClassName task = new AsyncTaskClassName();
bool result = task.execute(param1,param2......).get();
Run Code Online (Sandbox Code Playgroud)
但要小心UI的响应性,因为get()等待计算完成并将阻止UI线程.
如果您正在使用内部类,则最好将该作业放入onPostExecute(布尔结果)方法中.
如果您只想更新用户界面,请AsyncTask为您提供以下两种选择:
doInBackground()(例如更新a ProgressBar),您必须publishProgress()在doInBackground()方法内部调用.然后,您必须更新onProgressUpdate()方法中的UI .onPostExecute()方法中执行此操作.
/** This method runs on a background thread (not on the UI thread) */
@Override
protected String doInBackground(String... params) {
for (int progressValue = 0; progressValue < 100; progressValue++) {
publishProgress(progressValue);
}
}
/** This method runs on the UI thread */
@Override
protected void onProgressUpdate(Integer... progressValue) {
// TODO Update your ProgressBar here
}
/**
* Called after doInBackground() method
* This method runs on the UI thread
*/
@Override
protected void onPostExecute(Boolean result) {
// TODO Update the UI thread with the final result
}
Run Code Online (Sandbox Code Playgroud)
这样您就不必关心响应问题了.
| 归档时间: |
|
| 查看次数: |
88315 次 |
| 最近记录: |