2012-06-26 160 views
0

我做了一個程序,將選定的視頻從SD卡上傳到ASP.NET服務器。現在我想添加一個進度條來顯示上傳文件的狀態?任何人都可以幫我解決這個問題嗎?我有點困惑。我嘗試了很多方式來顯示狀態,但我沒有成功。添加進度條上傳程序

感謝您的幫助。

package com.isoft.uploder; 

import java.io.DataOutputStream; 
import java.io.File; 
import java.io.FileInputStream; 
import java.net.HttpURLConnection; 
import java.net.URL; 
import android.app.Activity; 
import android.app.ProgressDialog; 
import android.content.Context; 
import android.content.Intent; 
import android.database.Cursor; 
import android.net.ParseException; 
import android.net.Uri; 
import android.os.Bundle; 
import android.os.Handler; 
import android.os.Message; 
import android.provider.MediaStore; 
import android.util.Log; 
import android.view.View; 
import android.widget.Button; 
import android.widget.ProgressBar; 

public class VideoUploader extends Activity 
{ 
    /** Called when the activity is first created. */ 

public static final int SELECT_VIDEO=1; 
public static final String TAG="UploadActivity"; 
String path=""; 

@Override 
public void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    Button camera =(Button)findViewById(R.id.camera); 
    Button back= (Button)findViewById(R.id.back1); 
    Button select=(Button)findViewById(R.id.select); 
    //Video Çek 
    camera.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View arg0) { 
      // TODO Auto-generated method stub 
      Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
      startActivity(intent); 
     } 
    }); 
    // 
    //Video Seç 
    select.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View arg0) { 
      // TODO Auto-generated method stub 
      openGaleryVideo(); 
     } 
    }); 
    // 
    //Geri Dön 
    back.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View arg0) { 
      // TODO Auto-generated method stub 
      finish(); 
     } 
    }); 
    // 
} 

//Gallery'i aç 
public void openGaleryVideo() 
{ 
    Intent intent=new Intent(); 
    intent.setType("video/*"); 
    intent.setAction(Intent.ACTION_GET_CONTENT); 
    startActivityForResult(Intent.createChooser(intent, "Select Video"),SELECT_VIDEO); 
} 

//Dosyayı seç ve yükle 
@Override 
public void onActivityResult(int requestCode, int resultCode, Intent data) 
{ 
    super.onActivityResult(requestCode, resultCode, data); 
    if (resultCode == RESULT_OK) { 
     if (requestCode == SELECT_VIDEO) { 
      Uri videoUri = data.getData(); 
      path= getPath(videoUri); 
      doFileUpload(); 
     } 
    } 
} 

//SD carddan yerini al 
public String getPath(Uri uri) 
{ 
    String[] projection = { MediaStore.Video.Media.DATA}; 
    Cursor cursor = managedQuery(uri, projection, null, null, null); 
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA); 
    cursor.moveToFirst(); 
    return cursor.getString(column_index); 
} 

//upload et 
public void doFileUpload() 
{ 
     File file=new File(path); 
     String urlServer = "http://192.168.10.177/androidweb/default.aspx"; 
     String filename=file.getName(); 
     int bytesRead, bytesAvailable, bufferSize; 
     byte[] buffer; 
     int maxBufferSize = 10*1024*1024; 
     try 
     { 
     FileInputStream fileInputStream = new FileInputStream(file); 
     URL url = new URL(urlServer); 
     HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
     connection.setFixedLengthStreamingMode((int) file.length()); 

     // Allow Inputs & Outputs 
     connection.setDoInput(true); 
     connection.setDoOutput(true); 
     connection.setUseCaches(false); 

     // Enable POST method 
     connection.setRequestMethod("POST"); 
     connection.setRequestProperty("Connection", "Keep-Alive"); 
     connection.setRequestProperty("Content-Type", "multipart/form-data"); 
     connection.setRequestProperty("SD-FileName", filename);//This will be the file name 
     DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); 
     bytesAvailable = fileInputStream.available(); 
     bufferSize = Math.min(bytesAvailable, maxBufferSize); 
     buffer = new byte[bufferSize]; 

     // Read file 
     bytesRead = fileInputStream.read(buffer, 0, bufferSize); 
     while (bytesRead > 0) 
     { 
      outputStream.write(buffer, 0, bufferSize); 
      bytesAvailable = fileInputStream.available(); 
      bufferSize = Math.min(bytesAvailable, maxBufferSize); 
      bytesRead = fileInputStream.read(buffer, 0, bufferSize); 
     }//end of while statement 


      //Tekrar video seçmek için 
      setContentView(R.layout.end); 
      //event 
      Button back2=(Button)findViewById(R.id.back2); 
      Button select2=(Button)findViewById(R.id.new1); 
      back2.setOnClickListener(new View.OnClickListener() 
      { 
       @Override 
       public void onClick(View arg0) { 
        // TODO Auto-generated method stub 
        finish(); 
       } 
      }); 
      select2.setOnClickListener(new View.OnClickListener() 
      { 
       @Override 
       public void onClick(View arg0) { 
        // TODO Auto-generated method stub 
        openGaleryVideo(); 
       } 
      }); 
      // 

     //int serverResponseCode = connection.getResponseCode(); 
     //String serverResponseMessage = connection.getResponseMessage(); 
     //Log.d("ServerCode",""+serverResponseCode); 
     //Log.d("serverResponseMessage",""+serverResponseMessage); 
     fileInputStream.close(); 
     outputStream.flush(); 
     outputStream.close(); 
     }//end of try body 

     catch (Exception ex) 
     { 
      //ex.printStackTrace(); 
      Log.e("Error: ", ex.getMessage()); 
     } 
     } 
    } 
+0

必須解決您的問題嗎? – sunil

回答

0

我做同一種工作,在我的代碼看看,

public class LogUploaderActivity extends Activity 
{ 
    private static LogUploaderActivity thisAct = null; 
    private ButtonListener buttonClickListener = null; 
    private MyDialogInterfaceListener dListener = null; 

    private RadioButton rbServer; 
    private RadioButton rbEmail; 

    private Button cmdOK; 
    private Button cmdCancel; 

    // Progress Bar Variables 
    private static AlertDialog alertDialog = null; 
    private static ProgressDialog progressDialog = null; 

    private int delay = 1000;  
    private ProgressThread progThread; 
    private int maxBarValue; 

    private String[] fileName; 

    private static File directory = null; 

    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     thisAct = this; 

//  directory = Environment.getExternalStorageDirectory(); 

     rbServer = (RadioButton) findViewById(R.id.rdWebServer); 
     rbEmail = (RadioButton) findViewById(R.id.rdLTLogs); 

     cmdOK = (Button) findViewById(R.id.cmdOK); 
     cmdCancel = (Button) findViewById(R.id.cmdCancel); 

     cmdOK.setOnClickListener(getListener()); 
     cmdCancel.setOnClickListener(getListener()); 

    } 

    private int readLogList(String filePath) 
    { 
     directory = Environment.getExternalStorageDirectory(); 

//  System.out.println (directory + ConstantCodes.FILE_SEPARATOR + filePath); 

     File folder = new File(directory + ConstantCodes.FILE_SEPARATOR + filePath); 

     if (!folder.exists()) 
     { 
      return 0; 
     } 

     fileName = folder.list(); 

     return folder.list().length; 
    } 

    private String readSingleFile(String filePath, String fileName) 
    { 
     try 
     { 
//   File directory = Environment.getExternalStorageDirectory(); 

//   System.out.println ("Dir : " + directory); 

      System.gc(); 

      File file = new File (directory + ConstantCodes.FILE_SEPARATOR + filePath , fileName); 

      BufferedReader br = new BufferedReader (new FileReader (file)); 
      String line; 
      StringBuffer sb = new StringBuffer(); 

      while ((line = br.readLine()) != null) 
      { 
       sb.append(line); 
      } 

//   byte[] fileData = sb.toString().trim().getBytes(); 

//   String content = sb.toString().trim(); 

      System.out.println ("File Size : " + sb.toString().length()); 

      return sb.toString().trim(); 
     } 
     catch (Exception e) 
     { 
      System.out.println ("Error while reading File " + e.toString()); 
      return null; 
     } 
    } 

    private MyDialogInterfaceListener getDialogListener() 
    { 
     if (dListener == null) 
     { 
      dListener = new MyDialogInterfaceListener(); 
     } 
     return dListener; 
    } 

    private ButtonListener getListener() 
    { 
     if (buttonClickListener == null) 
     { 
      buttonClickListener = new ButtonListener(); 
     } 
     return buttonClickListener; 
    } 

    private class MyDialogInterfaceListener implements DialogInterface.OnClickListener 
    { 
     public void onClick(DialogInterface dialog, int which) 
     { 
      alertDialog.dismiss(); 
     } 
    } 

    private class ButtonListener implements Button.OnClickListener 
    { 
     public void onClick (View view) 
     { 
      if (view == cmdCancel) 
      { 
       finish(); 
      } 
      else if (view == cmdOK) 
      { 
       // First Check which Radio Button is selected 
       if (rbServer.isChecked()) 
       { 
        try 
        { 
         maxBarValue = readLogList(ConstantCodes.APPLICATION_LOG_PATH); 
         Thread.sleep(1000); 
        } 
        catch (Exception e) { } 

        if (maxBarValue > 0) 
        { 
         progressDialog = new ProgressDialog (thisAct); 
         progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
         progressDialog.setMax(maxBarValue); 
         progressDialog.setMessage("Uploading Files"); 
         progressDialog.show(); 

         progThread = new ProgressThread(handler, ConstantCodes.APPLICATION_LOG_PATH, ConstantCodes.TEXT_FILE_METHOD_NAME); 
         progThread.start(); 
        } 
        else 
        { 
         alertDialog = new AlertDialog.Builder(thisAct).create(); 
         alertDialog.setTitle("Error"); 
         alertDialog.setMessage("No More Logs to Upload"); 
         alertDialog.setButton("OK", getDialogListener()); 
         alertDialog.show(); 
        } 
       } 
       else if (rbEmail.isChecked()) 
       { 
        try 
        { 
         maxBarValue = readLogList(ConstantCodes.LOCATION_TRACKER_PATH); 
         Thread.sleep(1000); 
        } 
        catch (Exception e) { } 

        if (maxBarValue > 0) 
        { 
         progressDialog = new ProgressDialog (thisAct); 
         progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
         progressDialog.setMax(maxBarValue); 
         progressDialog.setMessage("Uploading Files"); 
         progressDialog.show(); 
        } 
        else 
        { 
         alertDialog = new AlertDialog.Builder(thisAct).create(); 
         alertDialog.setTitle("Error"); 
         alertDialog.setMessage("No More Logs to Upload"); 
         alertDialog.setButton("OK", getDialogListener()); 
         alertDialog.show(); 
        } 

        progThread = new ProgressThread(handler,ConstantCodes.LOCATION_TRACKER_PATH, ConstantCodes.LOCATION_TRACKER_METHOD_NAME); 
        progThread.start(); 
       } 
       else 
       { 
        alertDialog = new AlertDialog.Builder(thisAct).create(); 
        alertDialog.setTitle("Error"); 
        alertDialog.setMessage("Please Select Any One Option"); 
        alertDialog.setButton("OK", getDialogListener()); 
        alertDialog.show(); 
       } 
      } 
     } 
    } 

    final Handler handler = new Handler() 
    { 
     public void handleMessage(Message msg) 
     { 
      int total = msg.getData().getInt("total"); 
      progressDialog.setProgress(total); 
      if (total >= maxBarValue) 
      { 
       progressDialog.dismiss(); 
       progThread.setState(ProgressThread.DONE); 
      } 
     } 
    }; 


    private class ProgressThread extends Thread 
    { 
     final static int DONE = 0; 
     final static int RUNNING = 1; 
     int status; 
     int total; 
     String filePath; 
     String METHOD_NAME; 

     Handler mHandler; 

     ProgressThread(Handler h, String filePath,String METHOD_NAME) 
     { 
      mHandler = h; 
      this.filePath = filePath; 
      this.METHOD_NAME = METHOD_NAME; 
     } 

     @Override 
     public void run() 
     { 
      status = RUNNING; 
      while (status == RUNNING) 
      { 
       try 
       { 
        Thread.sleep(delay); 
       } 
       catch (Exception e) { } 

       Message msg = mHandler.obtainMessage(); 
       Bundle b = new Bundle(); 
       b.putInt("total", total); 
       msg.setData(b); 
       mHandler.sendMessage(msg); 

//    if (total < fileName.length) 
       { 
//     System.out.println ("Uploading File Name : " + fileName[total]); 

        try 
        { 

//      System.out.println ("Method Name : " + METHOD_NAME); 

         int response = WebService.fileUpload(METHOD_NAME, fileName[total], readSingleFile(filePath,fileName[total])); 

         System.out.println ("response " + response); 

         if (response == 404) 
         { 
          progressDialog.dismiss(); 
          setState(ProgressThread.DONE); 

//       Thread.sleep(500); 
//       
//       alertDialog = new AlertDialog.Builder(getActivity()).create(); 
//       alertDialog.setTitle("Error"); 
//       alertDialog.setMessage("Error While Uploading"); 
////       alertDialog.setButton("OK", getDialogListener()); 
//       alertDialog.show(); 
         } 
        } 
        catch (Exception e) 
        { 
//      alertDialog = new AlertDialog.Builder(thisAct).create(); 
//      alertDialog.setTitle("Error"); 
//      alertDialog.setMessage("Error While Uploading"); 
//      alertDialog.setButton("OK", getDialogListener()); 
//      alertDialog.show(); 
        } 
       } 
       total++; 
      } 
     } 

     public void setState(int state) 
     { 
      status = state; 
     } 
    } 

    public static LogUploaderActivity getActivity() 
    { 
     return thisAct; 
    } 

    public void onDestroy() 
    { 
     super.onDestroy(); 
    } 
} 

它顯示在SD卡的文件總數和一個它們上傳到服務器之一,顯示了狀態爲2/20正在上傳進度對話框中。

+0

@Lucifeer感謝您的回覆,但我想添加此欄來實時顯示上傳文件的百分比。你有什麼建議嗎?我會在這裏發佈我的代碼。 – answer88

+0

@ answer88好吧,發佈你的代碼,它可能會幫助我更多地引導你:) – Lucifer

+0

@ answer88:使用AsynTask從服務器下載數據並使用onProgressUpdate根據服務器下載的數據更新進度條 –