2011-11-02 65 views
0

我研究過這個,沒有找到明確的答案,它包含進度條+狀態欄+服務的組合?我的問題是文件上傳的實現方式(這是因爲服務器像這樣支持它的唯一方式),我無法跟蹤正在寫入的字節數。因此,我無法正確遞增進度欄以反映準確的文件上傳狀態。 當前的實現會增加進度條,進行上載並在進度條達到100時刪除進度條。但是進度並不準確地反映上載。上傳發生得更早,但酒吧保持開啓。我希望在發生此請求/響應時顯示進度。 以下是我的代碼片段:如何在使用服務進行文件上傳時更新狀態欄中的進度欄​​?

public class UploadFileService extends IntentService { 
    public UploadFileService() { 
super("UploadFileService"); 
} 

@Override 
protected void onHandleIntent(Intent intent) { 
    fName = intent.getExtras().getString(Constants.EXTRA_K_FILENAME); 
    path = intent.getExtras().getString(Constants.EXTRA_K_FILEPATH); 
      attribute = intent.getExtras().getString(Constants.EXTRA_K_ATTRIBUTE); 

//Start thread to doFilepUpload 
uploadthread = new UploadThread(fName, path, attribute); 
uploadthread.start(); 

}

//定義從線程接收郵件的處理程序和更新進度

final Handler handler = new Handler() { 
    public void handleMessage(Message msg) { 

     Integer total = msg.arg1; 
     notification.contentView.setProgressBar(R.id.status_progress, 100, total, false); 
     nm.notify(NOTIFICATION_ID, notification); 



     if (total.equals(100) && getResponse() != null){ 
      // inform the progress bar of updates in progress 
      uploadthread.setState(UploadThread.STATE_DONE); 

      Intent broadcastIntent = prepareBroadcast(); 
      // remove the notification (we're done) 
      nm.cancel(NOTIFICATION_ID); 
      sendBroadcast(broadcastIntent); 
     } 
    } 
}; 


public class UploadThread extends Thread { 

    private String name; 
    private String path; 
    private String attribute; 
    final static int STATE_DONE = 0; 
    final static int STATE_RUNNING = 1; 
    int mState; 
    int total; 


    public UploadThread(String fName, String path, String attribute) { 
     // TODO Auto-generated constructor stub 
     this.name = fName; 
     this.path = path; 
     this.attribute = attribute; 
    } 

    @Override 
    public void run() { 
     // TODO Auto-generated method stub 
     setResponse(doFileUpload(name, path, attribute)); 

     if(getResponse() != null){ 
          // house keeping for the application 
      if(response.result.equalsIgnoreCase("success")){ 
       saveFileName = response.data.savedFileName; 
       responseMessage = response.message; 
      }else if (response.result.equalsIgnoreCase("error") || 
     response == null){ 
       responseMessage = response.message; 
       saveFileName = null; 
       originalName = fName; 
      } 
     } 

     mState = STATE_RUNNING; 
     total = 0; 
     while (mState == STATE_RUNNING && total <=100) { 
      try { 
       Log.d(TAG, "^^ Thread.sleep"); 
       Thread.sleep(1000); 
      } catch (InterruptedException e) { 
       Logger.e("ERROR", "Thread Interrupted"); 
      } 
      Message msg = handler.obtainMessage(); 
      msg.arg1 = total; 
      handler.sendMessage(msg); 
      total++; 
     } 
    } 

    /* sets the current state for the thread, 
    * used to stop the thread */ 
    public void setState(int state) { 
     mState = state; 
    } 

} 

有沒有人對我怎麼建議/意見可以更新進度條以顯示正確的上傳進度? 文件上傳過程:

paramString = p.getName()+"="+URLEncoder.encode(p.getValue(), HTTP.UTF_8); 
        } catch (UnsupportedEncodingException e) { 
         Log.e(TAG, "unsupported encoding --> 
      name="+p.getName()+"; value="+p.getValue(), e); 
         throw e; 
        } 
        if (combinedParams.length() > 1) { 
         combinedParams += "&" + paramString; 
        } else { 
         combinedParams += paramString; 
        } 
       } 
      } 

      request = new HttpPost(url + combinedParams); 

      MultipartEntity entity = new MultipartEntity(); 

      // add headers 
      for (NameValuePair h : headers) {    
       request.addHeader(h.getName(), h.getValue()); 
      } 

      // add cookies 
      for(NameValuePair c : cookies) {    
       request.addHeader(H_COOKIE,   
         c.getName()+"="+c.getValue());     
      }   
       entity.addPart(uploadFile.getName(), new FileBody(uploadFile)); 

      request.setEntity(entity) 
+0

您是否嘗試過使用'AsyncTask'來上傳您的作業?它允許你使用'publishProgress()',每當你調用這個方法時,你將會從這裏傳播到UI ...? –

+0

@NikolaDespotoski:我確實嘗試了AsyncTask,但由於一次上傳一個文件等問題,服務似乎是此應用的最佳選擇。 –

+1

如果您是從Service處理它,爲什麼還要麻煩線程,因爲服務在單獨的進程上運行,這不會導致任何UI凍結在您的活動中。只需找出計算上傳進度的方法。可以從服務運行線程,我完全理解...這是我的簡要思想... –

回答

0

我發現了一個解決這個問題。這不是一個理想的解決方案,但由於字節計數是不可能的,所以我使用了這條路線。在我創建的上傳服務中,我有2個不同的線程。線程#1,上傳和線程#2,維護通知區域中的進度條。線程#2取決於#1。當#1處於活動狀態時,線程#2增加1,休眠1秒,每增加一個進程,睡眠間隔增加0.2secs。如果上傳完成可以說45%,則進度條跳轉到100%。