2012-08-26 2 views
2

안녕하세요, iam이 PHP 서버에 동영상을 업로드하는 안드로이드 응용 프로그램을 만들고 있습니다.
업로드를 수행하려면 HTTPURLConnection을 사용하십시오. Iam은 알림 영역에 진행률 표시 줄을 표시하고 업데이트하는 데 큰 충격을 받았습니다. 이걸 그리고는 누군가가 알고있는 경우 hint.Please 내게 도움을받을 수 없다 할 거의 일주일에 검색
스피 :알림 영역에 진행률 표시 줄을 표시하는 방법은 무엇입니까?

내 코드 :

HttpURLConnection conn = null; 
     DataOutputStream dos = null; 
     DataInputStream inStream = null; 
     String lineEnd = "\r\n"; 
     String twoHyphens = "--"; 
     String boundary = "*****"; 
     int bytesRead; 
     byte[] buffer; 
     String urlString = "http://xxxxx/My_path.php"; 
     try { 
      long total = 0; 
      int count = 0; 
      // ------------------ CLIENT REQUEST 
      UUID uniqueKey = UUID.randomUUID(); 
      fname = uniqueKey.toString(); 
      Log.e("UNIQUE NAME", fname); 
      FileInputStream fileInputStream = new FileInputStream(
        new File(selectedPath)); 
      URL url = new URL(urlString);      
      conn = (HttpURLConnection) url.openConnection(); 
      int length=selectedPath.length(); 
      conn.setDoInput(true); 
      conn.setDoOutput(true); 
      conn.setUseCaches(false); 
      conn.setRequestMethod("POST"); 
      conn.setRequestProperty("Connection", "Keep-Alive"); 
      conn.setRequestProperty("Content-Type", 
        "multipart/form-data;boundary=" + boundary); 
      dos = new DataOutputStream(conn.getOutputStream()); 
      dos.writeBytes(twoHyphens + boundary + lineEnd); 
      dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" 
        + fname + "" + lineEnd); 
      dos.writeBytes(lineEnd); 
      buffer = new byte[8192]; 
      bytesRead = 0; 
      while ((bytesRead = fileInputStream.read(buffer)) > 0) {         
       dos.write(buffer, 0, bytesRead);      
      }   
      dos.writeBytes(lineEnd); 
      dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);   
      Log.e("Debug", "File is written"); 
      fileInputStream.close(); 
      dos.flush(); 
      dos.close(); 

     } catch (MalformedURLException ex) { 
      Log.e("Debug", "error: " + ex.getMessage(), ex); 
     } catch (IOException ioe) { 
      Log.e("Debug", "error: " + ioe.getMessage(), ioe); 
     }  
     // ------------------ read the SERVER RESPONSE 
     try { 
      inStream = new DataInputStream(conn.getInputStream()); 
      String str; 
      while ((str = inStream.readLine()) != null) { 
       Log.e("Debug", "Server Response " + str); 
      } 
      inStream.close(); 

     } catch (IOException ioex) { 
      Log.e("Debug", "error: " + ioex.getMessage(), ioex); 
     } 

답변

3

긴 검색 후 알림 영역에 진행률 표시 줄을 표시하는 작업을 마쳤습니다. 우리가 필요로하는 것은 asynctask입니다. 여기에 표시된 코드가 완벽하게 작동하지 않을 수 있습니다. iam 테스트가 제대로 작동합니다. 확인하고 upvote하십시오 이 대답은 효과가 있다면.

내 코드 :

public class loadVideo extends AsyncTask<Void, Integer, Void> { 

     int progress = 0; 
     Notification notification; 
     NotificationManager notificationManager; 
     int id = 10; 

     protected void onPreExecute() { 

     } 

     @Override 
     protected Void doInBackground(Void... params) { 
      HttpURLConnection conn = null; 
      DataOutputStream dos = null; 
      DataInputStream inStream = null; 
      String lineEnd = "\r\n"; 
      String twoHyphens = "--"; 
      String boundary = "*****"; 
      int bytesRead; 
      int sentData = 0;    
      byte[] buffer; 
      String urlString = "http://xxxxx/xxx/xxxxxx.php"; 
      try { 
       UUID uniqueKey = UUID.randomUUID(); 
       fname = uniqueKey.toString(); 
       Log.e("UNIQUE NAME", fname); 
       FileInputStream fileInputStream = new FileInputStream(new File(
         selectedPath)); 
       int length = fileInputStream.available(); 
       URL url = new URL(urlString); 
       conn = (HttpURLConnection) url.openConnection(); 
       conn.setDoInput(true); 
       conn.setDoOutput(true); 
       conn.setUseCaches(false); 
       conn.setRequestMethod("POST"); 
       conn.setRequestProperty("Connection", "Keep-Alive"); 
       conn.setRequestProperty("Content-Type", 
         "multipart/form-data;boundary=" + boundary); 
       dos = new DataOutputStream(conn.getOutputStream()); 
       dos.writeBytes(twoHyphens + boundary + lineEnd); 
       dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" 
         + fname + "" + lineEnd); 
       dos.writeBytes(lineEnd); 
       buffer = new byte[8192]; 
       bytesRead = 0; 
       while ((bytesRead = fileInputStream.read(buffer)) > 0) { 
        dos.write(buffer, 0, bytesRead); 
        sentData += bytesRead; 
        int progress = (int) ((sentData/(float) length) * 100); 
        publishProgress(progress); 
       } 
       dos.writeBytes(lineEnd); 
       dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); 
       Log.e("Debug", "File is written"); 
       fileInputStream.close(); 
       dos.flush(); 
       dos.close(); 

      } catch (MalformedURLException ex) { 
       Log.e("Debug", "error: " + ex.getMessage(), ex); 
      } catch (IOException ioe) { 
       Log.e("Debug", "error: " + ioe.getMessage(), ioe); 
      } 
      // ------------------ read the SERVER RESPONSE 
      try { 
       inStream = new DataInputStream(conn.getInputStream()); 
       String str; 
       while ((str = inStream.readLine()) != null) { 
        Log.e("Debug", "Server Response " + str); 
       } 
       inStream.close(); 

      } catch (IOException ioex) { 
       Log.e("Debug", "error: " + ioex.getMessage(), ioex); 
      } 

      return null; 
     } 

     @Override 
     protected void onProgressUpdate(Integer... progress) { 

      Intent intent = new Intent(); 
      final PendingIntent pendingIntent = PendingIntent.getActivity(
        getApplicationContext(), 0, intent, 0); 
      notification = new Notification(R.drawable.video_upload, 
        "Uploading file", System.currentTimeMillis()); 
      notification.flags = notification.flags 
        | Notification.FLAG_ONGOING_EVENT; 
      notification.contentView = new RemoteViews(getApplicationContext() 
        .getPackageName(), R.layout.upload_progress_bar); 
      notification.contentIntent = pendingIntent; 
      notification.contentView.setImageViewResource(R.id.status_icon, 
        R.drawable.video_upload); 
      notification.contentView.setTextViewText(R.id.status_text, 
        "Uploading..."); 
      notification.contentView.setProgressBar(R.id.progressBar1, 100, 
        progress[0], false); 
      getApplicationContext(); 
      notificationManager = (NotificationManager) getApplicationContext() 
        .getSystemService(Context.NOTIFICATION_SERVICE); 
      notificationManager.notify(id, notification); 
     } 

     protected void onPostExecute(Void result) { 
      Notification notification = new Notification(); 
      Intent intent1 = new Intent(MultiThreadActivity.this, 
        MultiThreadActivity.class); 
      final PendingIntent pendingIntent = PendingIntent.getActivity(
        getApplicationContext(), 0, intent1, 0); 
      int icon = R.drawable.check_16; // icon from resources 
      CharSequence tickerText = "Video Uploaded Successfully"; // ticker-text 
      CharSequence contentTitle = getResources().getString(
        R.string.app_name); // expanded message 
      // title 
      CharSequence contentText = "Video Uploaded Successfully"; // expanded 
                     // message 
      long when = System.currentTimeMillis(); // notification time 
      Context context = getApplicationContext(); // application 
                 // Context 
      notification = new Notification(icon, tickerText, when); 
      notification.flags |= Notification.FLAG_AUTO_CANCEL; 
      notification.setLatestEventInfo(context, contentTitle, contentText, 
        pendingIntent); 
      String notificationService = Context.NOTIFICATION_SERVICE; 
      notificationManager = (NotificationManager) context 
        .getSystemService(notificationService); 
      notificationManager.notify(id, notification); 
     } 
    } 

감사합니다 감사합니다 다르.

+0

저는이 문제를 해결하기위한 솔루션을 찾고있었습니다. 정확히 동일한 작업 (havent는 알림 영역 진행 표시 줄을 시도했습니다)을 생각하고있었습니다. 사용자가 화면 방향을 변경하거나 앱을 종료 할 때 스레드가 멈추는 것을 걱정하는 유일한 것. 그러나 ... 여기 문제가 아니며, 다른 누군가가 내가 생각하고있는 해결책을 사용하는 것을보고 싶습니다. :) 다른 사람이 더 좋은 해결책을 얻은 경우, 물론 알려 주시기 바랍니다 – Honnes

+0

@Honnes 정확히 뭐죠? 필요한 것? – Manikandan

0

RemoveView에서, 당신은 진행 표시 줄을 업데이트 할 수 있습니다. 그래서 예제 코드의 일부를 결합,이 같은 것을 얻을 :

public class MyActivity extends Activity { 
private static final int PROGRESS = 0x1; 
private static final int MAX_PROGRESS = 100; 

private int mProgressStatus = 0; 

private Handler mHandler = new Handler(); 

protected void onCreate(Bundle icicle) { 
    super.onCreate(icicle); 

    //define Notification 
    //... 

    RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custom_notification_layout); 
    contentView.setProgressBar(R.id.progress_bar, MAX_PROGRESS, mProgressStatus, false); 
    notification.contentView = contentView; 

    // Start file upload in a background thread 
    new Thread(new Runnable() { 
     public void run() { 
      while (mProgressStatus < MAX_PROGRESS) { 
       mProgressStatus = doWork(); 

       // Update the progress bar 
       mHandler.post(new Runnable() { 
        public void run() { 
         contentView.setProgressBar(R.id.progress_bar, MAX_PROGRESS, mProgressStatus, false); 
        } 
       }); 
      } 
     } 
    }).start(); 
    } 
} 

blog post는 동일하게 구현하는 아주 좋은 사례가있다. 희망이 도움이됩니다.

+0

위의 코드는 널 포인터 예외를 발생시킵니다. 코드를 확인하고 알려 주실 수 있습니까? – Manikandan

+0

블로그 게시물을 확인 했습니까? 나는 그것이 당신의 문제를 해결할 것이라고 생각합니다. – darsh

+0

네, 블로그를 봅니다. 그러나 블로그 게시물 U와 업로드 코드를 동기화하는 방법을 모릅니다. – Manikandan

관련 문제