2013-10-03 4 views
0

대기열처럼 파일을 하나씩 업로드하고 싶습니다. 간단히 말해서 10 개의 파일이 있고 모든 파일을 업로드하려고하며 네트워크 연결을 확인해야합니다. 그렇지 않으면 파일이 대기열에 있어야하며 나중에 업로드하려고 시도합니다. 왼쪽 큐에있는 하나의 파일까지 계속 시도합니다. 제발 도와주세요, 어떻게 안드로이드에서 이것을 얻을 수 있습니까?android의 대기열처럼 하나씩 파일을 업로드하고 싶습니다.

이것은 내가 (캔트 아직 편집 참조) 지금까지

final Thread thread = new Thread(){ 
     public void run() { 
      try { 
       while(true){ 
        ThisCaching ic = new ThisCaching(getApplicationContext()); 
        fileToUpload = ic.getDataFromCache("audiofiles", "SELECT * FROM audiofiles WHERE STATUS = '2' OR STATUS = '3' ORDER BY rowid DESC"); 
        if(fileToUpload != null) 
        { 
         for (int i=0; i<fileToUpload.size(); i++) { 
          try { 
           System.out.println("Current position while uploading ::> " + i); 
           Thread.sleep(1000); 
           ConstantData.selectedFile = fileToUpload.get(i).toString(); 
           ConstantData.position = i; 
           if(checkConnectivity()){ 
            new Uploading().execute(); 
            myApplication.getHttpClient().getConnectionManager().closeExpiredConnections(); 
           }else{ 
            String[] status = {"STATUS"}; 
            String[] val = {"2"}; 
            try { 
             SQLiteDatabase sd = ThisDataHelper.getInstance(getApplicationContext()).getDB(); 
             new ThisTable(sd, "audiofiles").updateRow(status,val, "FILENAME = " + "'"+ConstantData.selectedFile+"'"); 
            } catch (Exception e1) { 
             e1.printStackTrace(); 
            } 
           } 
          } catch (Exception e) { 
           return; 
          }    
         } 
        } 
       } 
      } catch (Exception e) { 
       e.printStackTrace(); 
       return; 
      }    
     } 
    }; 


     String line = null; 
     HttpClient httpClient = null; 
     HttpContext localContext = null; 
     HttpPost httpPost = null; 
     MultipartEntity entity = null; 
     HttpResponse response = null; 
     HttpEntity httpEntity =null; 
     SQLiteDatabase sd = ThisDataHelper.getInstance(getApplicationContext()).getDB(); 
     try { 
      String strArray[]={"http://myurl.com","filename",ConstantData.selectedFile,"activityType",ConstantData.activityType,"patientId",ConstantData.patientId,"caseId",ConstantData.caseId,"doctorId",ConstantData.doctorId,"clinicCode",ConstantData.clinicCode,"documentType",ConstantData.documentType,"templateId",ConstantData.templateId}; 
      httpClient = new DefaultHttpClient(); 
      //httpClient.getConnectionManager().r 
      localContext = new BasicHttpContext(); 
      httpPost = new HttpPost(strArray[0]); 
      entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); 
      File file = new File(ConstantData.selectedFile); 
      String type = file.getAbsolutePath().substring(file.getAbsolutePath().lastIndexOf(".")+1); 
      if(strArray.length>1) 
      { 
       for(int i=1;i<strArray.length;i=i+2) 
       { 
        if(strArray[i]!=null){ 
         if(!strArray[i].equalsIgnoreCase("")){ 
          //        System.out.println("i) : "+i +" i+1) : "+(i+1)); 
          Log.i(strArray[i], "::" + strArray[i+1]); 
          if(strArray[i].equalsIgnoreCase("filename")){ 
           entity.addPart("filename", new FileBody(file,"audio/"+type)); 
          }else{ 
           entity.addPart(strArray[i], new StringBody(strArray[i+1])); 
          } 
         } 
        } 
       } 
      } 
      httpPost.setEntity(entity); 
      response = httpClient.execute(httpPost,localContext);// i m getting error at this line 

      System.out.println("Response code is ::> " +response.getStatusLine().getStatusCode()); 
      code = response.getStatusLine().getStatusCode(); 
      httpEntity = response.getEntity(); 
      line = EntityUtils.toString(httpEntity, HTTP.UTF_8); 
     } catch (UnsupportedEncodingException e) { 
      code=100; 
      e.printStackTrace(); 
      line = "<results status=\"error\"><msg>Can't connect to server</msg></results>"; 
      ConstantData.uploaded = false; 
      String[] status = {"STATUS"}; 
      String[] val = {"3"}; 
      try { 
       new ThisTable(sd, "audiofiles").updateRow(status,val, "FILENAME = " + "'"+ConstantData.selectedFile+"'"); 
      } catch (Exception e1) { 
       e1.printStackTrace(); 
      } 
     } catch (MalformedURLException e) { 
      code=100; 
      e.printStackTrace(); 
      line = "<results status=\"error\"><msg>Can't connect to server</msg></results>"; 
      ConstantData.uploaded = false; 
      String[] status = {"STATUS"}; 
      String[] val = {"3"}; 
      try { 
       new ThisTable(sd, "audiofiles").updateRow(status,val, "FILENAME = " + "'"+ConstantData.selectedFile+"'"); 
      } catch (Exception e1) { 
       e1.printStackTrace(); 
      } 
     } catch (IOException e) { 
      code=100; 
      e.printStackTrace(); 
      line = "<results status=\"error\"><msg>Can't connect to server</msg></results>"; 
      ConstantData.uploaded = false; 
      String[] status = {"STATUS"}; 
      String[] val = {"3"}; 
      try { 
       new ThisTable(sd, "audiofiles").updateRow(status,val, "FILENAME = " + "'"+ConstantData.selectedFile+"'"); 
      } catch (Exception e1) { 
       e1.printStackTrace(); 
      } 
     } catch (Exception e) { 
      code=100; 
      e.printStackTrace(); 
      ConstantData.uploaded = false; 
      String[] status = {"STATUS"}; 
      String[] val = {"3"}; 
      try { 
       new ThisTable(sd, "audiofiles").updateRow(status,val, "FILENAME = " + "'"+ConstantData.selectedFile+"'"); 
      } catch (Exception e1) { 
       e1.printStackTrace(); 
      } 
     }finally{ 
// 


try { 
//     System.out.println("&&&& while realeasing connection"); 
////      if(httpClient != null){ 
////       httpClient.getConnectionManager().releaseConnection((ManagedClientConnection) httpClient.getConnectionManager(), -1, TimeUnit.MINUTES); 
////      } 
//     if(httpPost.getEntity().getContent() != null){ 
//      InputStream content = httpPost.getEntity().getContent(); 
//      content.close(); 
//     } 
//    } catch (Exception e) { 
//     e.printStackTrace(); 
//    } 
      } 

      return line; 


` 

답변

0

내가 보는 바로는 시도는 일반 스레드를 사용 할 수있는 샘플 코드입니다. Java 1.5부터 대기열 및 mutlithreading과 같은 것들을위한 패키지가있어 훨씬 쉽게 살 수 있습니다.

대기열을 목적으로 Executors.newSingleThreadExecutor()으로 단일 스레드 실행 프로그램을 만들 수 있습니다. submit(Runnable)을 제출 한 순서대로 각 태스크를 실행하는 스레드가 하나있는 스레드 풀을 얻게됩니다. Executor는 항상 하나의 스레드가 큐에서 작동 함을 Java가 보증합니다 (Java는 Thread가 자동으로 스레드를 다시 생성합니다)

제출 한 각 태스크는 Runnable을 구현합니다. 따라서 위에서 설명한 세 가지 재시도를 구현하려면 Runnable 인터페이스를 구현하는 클래스가 필요하며 재시도 횟수가 포함됩니다. 업로드가 성공적이지 않은 경우 카운터를 증가시키고 자체적으로 다시 제출합니다.

여기 Executors 및 ExecutorService에 Guide, TutorialReference이 있습니다.

관련 문제