Android:下载完成后如何恢复主线程

时间:2012-11-08 14:03:12

标签: android multithreading android-activity resume

我能做什么,如果我在任何活动中并且我想下载文件(使用线程),同时我希望主线程等待下载完成?

3 个答案:

答案 0 :(得分: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();

}
}

答案 1 :(得分: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();
    }
});

答案 2 :(得分:0)

如果您希望线程与主线程通信,告诉下载已完成,请使用handler 此代码将帮助您理解

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


正如你可以通过处理程序看到线程与UI线程进行通信。在上面的例子中,我只将任何对象从线程发送到UI线程。要做到这一点,只需在线程中执行msg.obj=your_obj即可。它可以是任何物体。希望这可以帮助你:)