我有一个 Activity,它启动一个带有已实现进程对话框的 AsyncTask。这很好用!但是我想在 asyncTask 完成后得到一个字符串返回。所以我必须在 onPostExecute - 方法中返回一些东西。我想在启动 AsyncTask 的 Activity 中获取该结果(字符串)。我不想使用 .get() 因为它阻塞了 UI 线程。
我必须在 onPostExecute 中写入什么,而 Activity 从 doInBackground 中获取字符串?
感谢您为解决此问题提供的任何帮助;)
现在使用代码:
class BgDL extends AsyncTask<String, Integer, String> {
String finishString="";
private Context context;
ProgressDialog pdialog;
public BgDL(Context cxt) { //get the context (usually "this" from Activity / otherwise progressdialog wont show up!
context = cxt;
pdialog = new ProgressDialog(context);
}
@Override
protected String doInBackground(String... strings) {
OutputStream output;
ByteArrayOutputStream baos = null;
try {
URL url = new URL(strings[0]);
URLConnection connection = url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream());
if (strings[1]=="toString") { // write byte to string if a file is not given
baos= new ByteArrayOutputStream();
output = new DataOutputStream(baos);
} else { //otherwise to string
output = new FileOutputStream(strings[1]);
}
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
if (strings[1]=="toString") {
finishString = baos.toString(); //
} // only write byte to string if a file is not given
} catch (Exception e) {log.d("ex",e.toString());
}
return finishString;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
pdialog.setTitle("Please wait");
pdialog.setIndeterminate(false);
pdialog.setMax(100);
pdialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pdialog.show();
}
@Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
pdialog.setProgress(progress[0]);
}
protected void onPostExecute(String...finishString) {
pdialog.dismiss();//!!!!!!!!!finishString i want to pass over to my Activity, which started this asynctask with .execute();
}