2012-11-08 23 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。它可以是任何對象。希望這可以幫助你:)

相關問題