我有一个与AsyncTask
类相关的概念问题。我们使用AsyncTask
,以便不阻止主UI。
但是假设,我想从设备的内存中检索一些数据,为此我使用AsyncTask类。代码的相关行如下(假设返回的数据类型是String):
//code
String data = new ExtendedAsyncTask().execute(param1, param2).get();
//use this returned value.
以上行是否会阻止用户界面,从而无法使用AsyncTask
?如果是,那么如何在不阻止UI的情况下获取相关数据?我想补充一点,下一行代码将需要这些数据来执行某些任务,因此取决于返回的值。
由于
答案 0 :(得分:19)
get() method will block the UI thread
。要获取相关数据,您需要从doInBackground返回值并捕获onPostExecute参数中的值。
doInBackground返回的值由onPostExecute方法
捕获
示例:
public class BackgroundTask extends AsyncTask<String, Integer, String >{
private ProgressDialog mProgressDialog;
int progress;
public BackgroundTask() {
mProgressDialog = new ProgressDialog(context);
mProgressDialog.setMax(100);
mProgressDialog.setProgress(0);
}
@Override
protected void onPreExecute() {
mProgressDialog =ProgressDialog.show(context, "", "Loading...",true,false);
super.onPreExecute();
}
@Override
protected void onProgressUpdate(Integer... values) {
setProgress(values[0]);
}
@Override
protected String doInBackground(String... params) {
String data=getDatafromMemoryCard();
return data; // return data you want to use here
}
@Override
protected void onPostExecute(String result) { // result is data returned by doInBackground
Toast.makeText(context, result, Toast.LENGTH_LONG).show();
mProgressDialog.dismiss();
super.onPostExecute(result);
}
}
如果你在单独的类中使用asynctask,那么像这样使用带有回调接口的AsyncTask
以下是我之前提供的关于同一AsyncTask with Callback
的答案答案 1 :(得分:0)
你没有这样得到结果。请参阅此链接以获取示例:https://github.com/levinotik/ReusableAsyncTask/tree/master/src/com/example
基本上,这是你需要做的:
答案 2 :(得分:0)
执行异步任务时,任务将经历4个步骤:
1.onPreExecute(), invoked on the UI thread before the task is executed. use this to diaply progress dialog.
2.doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. Can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
3.onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). Used to publish progress.
4.onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.
在你的活动onCreate()
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv= (TextView)findViewById(R.id.textView);
new TheTask().execute();
}
class TheTask extends AsyncTask<Void, Void,String> {
protected void onPreExecute() {
//dispaly progress dialog
}
protected String doInBackground(Void... params) {
//do network operation
return "hello";
}
protected void onPostExecute(String result) {
//dismiss dialog. //set hello to textview
//use the returned value here.
tv.setText(result.toString());
}
}
考虑使用robospice(替代AsyncTask。https://github.com/octo-online/robospice。
进行异步调用,在ui线程上通知。