2011-10-21 42 views
0

我真的一直在努力搞清楚如何获得ProgressDialog在UI线程用于鉴于uploadPhoto这个代码,并希望任何指导:我如何显示ProgressDialog在UI线程

@Override 
    /** Handle Upload a Photo **/ 
    protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) { 
     super.onActivityResult(requestCode, resultCode, imageReturnedIntent); 

     // Get image 
     if (resultCode == RESULT_OK) { 

      // ProgressDialog dialog = ProgressDialog.show(this, "", "Uploading Photo...", true, false); 

      switch(requestCode) { 

       // Take Photo 
       case 4001:  
        // Upload 
        uploadPhoto(Uri.fromFile(mImageFile)); 
        break; 

       // Select Photo 
       case 5001: 

        // Get image 
        Uri selectedImage = imageReturnedIntent.getData(); 

        // Upload 
        uploadPhoto(selectedImage); 
        break; 
      } 

      // Dismiss 
      // dialog.dismiss();    
     } 
    } 

回答

2

使用的AsyncTask也许。把上传图片功能放在异步任务的后台。

在预执行中启动进度对话框。

在post执行中关闭/取消进度对话框。

post执行并预执行在UI线程上运行。

private class uploadPhoto extends AsyncTask<Void, Void, Void>{ 

      private ProgressDialog dialog; 
     protected void onPostExecute(Void dResult) { 

       dialog.cancel(); 

     } 

     protected void onPreExecute() { 


      dialog = new ProgressDialog(Myactivity.this); 
      dialog.setCancelable(true); 
      dialog.setMessage("uploading..."); 
      dialog.show(); 

       } 

     protected Void doInBackground(Void... params) { 
      // call upload photo here. 
     } 

    } 

调用的AsyncTask使用

new uploadPhoto().execute(); 
+0

我有点明白你在说什么,但是我从来没有做过任何这些事情。 –

+0

好吧,那么你可能不得不看看asyncTask,以及它是如何工作的。它通常用于这种类型的实例。我添加了一些代码让你知道它是如何工作的。 –

3

使用的AsyncTask像这样:

public class NetworkTask extends AsyncTask<Object , Void, Object> { 
    Context context; 
    boolean shouldContinue = true; 
    public ProgressDialog dialog; 
    String waitMessage = "Please wait, loading data..."; 
    public NetworkTask(Context con){ 
     this.context = con;  
    } 
    public void setMessage(String msg){ 
     waitMessage = "Please wait, "+msg; 
    } 
    protected void onPreExecute(){ 
     shouldContinue = ConnectionUtils.isNetworkAvailable(context); 
     if(shouldContinue) 
      dialog = ProgressDialog.show(context, null, waitMessage, true); 
     else{ 
      Dialog.showToast(context, Constants.NETWORK_ERROR); 
      return; 
     } 
    } 
    @Override 
    protected void onPostExecute(Object result){ 
     if(dialog != null){ 
      if(dialog.isShowing()) 
      dialog.dismiss(); 
      dialog = null; 
     }   
    } 
    @Override 
    protected Object doInBackground(Object... params){ 
     //do uploading and other tasks 
    } 
} 

,并在您Activity调用它像这样:

NetWorkTask task = new NetWorkTask(this); //Here you can pass other params 
task.execute("");