如果我在任何活动中并且我想下载一个文件(使用线程)并且同时我希望主线程等待下载完成,我该怎么办?
问问题
841 次
3 回答
2
从活动中使用AsyncTask ..
new DownloadTask(this).execute();
以任务为例:
public class DownloadTask extends AsyncTask<Void, Void, String> {
private ProgressDialog progressDialog;
private Context context;
/**
*
* @param context
* @param pdfDoc the document of the PDF
*/
public DownloadTask(Context context) {
this.context = context;
progressDialog = new ProgressDialog(context);
}
@Override
protected void onPreExecute() {
progressDialog.setMessage("Downloading...");
progressDialog.setIndeterminate(true);
progressDialog.show();
}
@Override
protected String doInBackground(Void... arg0) {
//download here
}
@Override
protected void onPostExecute(final String result) {
progressDialog.dismiss();
}
}
于 2012-11-08T14:08:30.810 回答
1
使用 AsyncTask 和回调。
public interface DownloadCallback<T>{
public void onFinishDownload(T downloadedResult);
}
public static void downloadString(String url, DownloadCallback<String> callback){
new AsyncTask<Void,Void,Void>(){
String result;
@Override
protected void onPreExecute() {
// Do things before downloading on UI Thread
}
@Override
protected String doInBackground(Void... arg0) {
//download here
result = download(url);
}
@Override
protected void onPostExecute(final Void result) {
// Do things on UI thread after downloading, then execute your callback
if (callback != null) callback.onFinishDownloading(result);
}
}.execute();
}
要使用它,您只需执行以下操作:
downloadString("http://www.route.to.your.string.com", new DownloadCallback<String>(){
public void onFinishDownloading(String downloadedResult){
Toast.makeText(YourActivityName.this, downloadedResult, Toast.LENGTH_SHORT).show();
}
});
于 2012-11-08T14:19:56.047 回答
0
如果您希望线程与主线程通信,告诉下载完成,请使用处理程序 此代码将帮助您理解它
MyHnadler handler;
onCreate(Bundle savedInstance)
{
setContent..
...
handler=new MyHandler();
new MyThread().start();
}
public class MyHandler extends Handler
{
@Override
public void handleMessage(Message message) {
switch (message.what) {
case 1: //....threading over
//write your code here
break;
case2 : //if you want to be notiifed of something else
..
}
public class MyThread extends Thread
{
@Override
public void run()
{
//run the threa
//and when over
Message msg=handler.getMessage();
msg.what=1;
handler.sendMessage(msg); //send the message to handler
}
}
}
如您所见,线程通过Handler与 UI 线程通信。在上面的示例中,我只将线程中的任何对象发送到 UI 线程。要做到这一点,只需在线程中执行。它可以是任何对象。希望这对你有帮助:)msg.obj=your_obj
于 2012-11-08T14:31:40.467 回答