2012-11-08 24 views

回答

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(); 

} 
} 
+0

要进一步添加,你的主线程不应该完全锁定,而它等待。假设用户将使用Activity上的其他元素,甚至在下载完成之前终止它。使用上面的示例Async将允许这样做。 –

+0

我无法在下载之前创建我的活动。 – GVillani82

1

使用的AsyncTask和回调。如果你想线程与他主线程沟通,告诉下载完成后,使用handler 这个代码将有助于

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(); 
    } 
}); 
+0

通过这种方法,您甚至可以在其他下载任务中重复使用其他结果类型的回调函数;-) – razielsarafan

+0

这样主线程就等待完成下载了吗? – GVillani82

+0

这样: A)主线程执行onExExcute,然后休眠。 B)新线程执行doInBackground。主线程没有被堵塞,同时,你可以做任何你想要的。 C)主线程唤醒并执行onPostExecute。 – razielsarafan

0

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(); 
} 

,并利用这一点,你只是这样做你了解它

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。它可以是任何对象。希望这可以帮助你:)

相关问题