2014-04-25 7 views
0

사용자가 미디어 파일 (예 : 이미지, 사진, 비디오)을 서버에 업로드 할 수있는 앱을 개발 중이며 큰 파일에는 약간의 문제가 있습니다. 업로드 및 다른 문제가 진행되는 동안 진행 상황 표시 줄을보고 기다리십시오. 앱에서 업로드가 종료 될 경우 업로드 코드를 전송해야합니다. 그래서 여기 내 고민이 시작됩니다 - 업로드 코드를 서버로 전송하면 진행률 업데이트 (%)를 어떻게 활동에 보낼 수 있습니까? 당신의 앱이 닫힌 경우백그라운드로 서버에 파일 업로드하기

public static void uploadMovie(final HashMap<String, String> dataSource, final OnResponseListener finishedListener, final ProgressListener progressListener) { 
    if (finishedListener != null) { 
     new Thread(new Runnable() { 
      public void run() { 
       try { 

        //Prepare data--> 

        String boundary = getMD5(dataSource.size() + String.valueOf(System.currentTimeMillis())); 
        MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create(); 
        multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); 
        multipartEntity.setCharset(Charset.forName("UTF-8")); 
        for (String key : dataSource.keySet()) { 
         if (key.equals(MoviesFragmentAdd.USERFILE)) { 
          FileBody userFile = new FileBody(new File(dataSource.get(key))); 
          multipartEntity.addPart(key, userFile); 
          continue; 
         } 
         multipartEntity.addPart(key, new StringBody(dataSource.get(key), ContentType.APPLICATION_JSON)); 
        } 
        HttpEntity entity = multipartEntity.build(); 
        //<-- 

        //Prepare Connection--> 

        trustAllHosts(); 
        HttpsURLConnection conn = (HttpsURLConnection) new URL(SAKH_URL_API + "/video/addForm/").openConnection(); 
        conn.setUseCaches(false); 
        conn.setDoOutput(true); 
        conn.setDoInput(true); 
        conn.setRequestMethod("POST"); 
        conn.setRequestProperty("Accept-Charset", "UTF-8"); 
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); 
        conn.setRequestProperty("Content-length", entity.getContentLength() + ""); 
        conn.setRequestProperty(entity.getContentType().getName(), entity.getContentType().getValue()); 
        conn.connect(); 


        //<-- 
        // Upload--> 


        OutputStream os = conn.getOutputStream(); 
        ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
        entity.writeTo(baos); 
        baos.close(); 
        byte[] payload = baos.toByteArray(); 
        baos = null; 
        int totalSize = payload.length; 
        int bytesTransferred = 0; 
        int chunkSize = 2000; 

        while (bytesTransferred < totalSize) { 
         int nextChunkSize = totalSize - bytesTransferred; 
         if (nextChunkSize > chunkSize) { 
          nextChunkSize = chunkSize; 
         } 
         os.write(payload, bytesTransferred, nextChunkSize); 
         bytesTransferred += nextChunkSize; 

         //Progress update--> 
         if (progressListener != null) { 
          progressListener.onProgressUpdate((100 * bytesTransferred/totalSize)); 
         } 
         //<-- 

        } 

        os.flush(); 

        //<-- 
        //Get server response--> 
        int status = conn.getResponseCode(); 
        if (conn.getResponseCode() == HttpsURLConnection.HTTP_OK) { 

         BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
         JsonObject request = (JsonObject) gparser.parse(in.readLine()); 

         if (!request.get("error").getAsBoolean()) { 
          finishedListener.onLoadFinished(new Object()); 
         } 
        } else { 
         throw new IOException("Server returned non-OK status: " + status); 
        } 

        conn.disconnect(); 
       } catch (Exception e) { 
        e.printStackTrace(); 
        finishedListener.onNotConnected(); 

       } 
      } 
     }).start(); 

    } 
} 

답변

1

여기에 또는 다른 경우에 바인딩하기 전에 서비스를 시작 필요한 바인더

을 바인딩 가능한 서비스를 1 생성 및 구현 :

여기 내 업로드 방법의 코드입니다 서비스도 닫습니다.

2 - 서비스에서 StartDownload (url, IUpdateTarget)와 같은 공용 기능을 노출합니다.

3 - UpdateProgress (somevalues)와 같은 함수로 인터페이스 (IUpdateTarget)를 만듭니다.

4 구현 실행중인 서비스의 인스턴스 업데이트 알림

서비스에 가

5 바인딩을 받고 검색해야보기에 IUpdateTarget 인터페이스를

6 이제 서비스의 인스턴스가 있고, StartDownload를 호출하여 알림 URL과 대상보기를 전달합니다.

7 - 서비스에 전달 된 IUpdateProgress 인스턴스 (대상 뷰)에서 서비스 호출에서 UpdateProgress로 인터페이스를 업데이트해야 할 때마다.

크로스 스레딩 호출에주의하십시오. 메인 스레드에서 항상 인터페이스를 업데이트해야합니다.

+0

큰 감사를 보냅니다. – whizzzkey

+0

반갑습니다. 또한 서비스가 물건을 다운로드하거나 장치가 절전 모드로 들어갈 수있을 때 전원 잠금 장치를 사용해야합니다. – Gusman

1

사용 처리기는 당신이 쓴 나는 그것을 시도 할 것이다, 당신의 대답에 대한 과정을

new Thread(new Runnable() { 

    @Override 
    public void run() { 
     // TODO Auto-generated method stub 
     android.os.Message msg = new android.os.Message(); 
     Bundle bundle = new Bundle(); 
     bundle.putInt("process", process); 
     msg.setData(bundle); 
     mHandler.sendMessage(msg); 
    } 
}).start(); 

Handler mHandler = new Handler() { 
    public void handleMessage(android.os.Message msg) { 
     int process = msg.getData().getInt("process"); 
    }; 
}; 
+0

좋은 생각! thx =) – whizzzkey

관련 문제