2012-06-26 3 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 ok, разместите свой код, это может помочь мне больше узнать :) – Lucifer

+0

@ answer88: используйте AsynTask для загрузки данных с сервера и используйте onProgressUpdate для обновления индикатора выполнения в соответствии с загруженными данными с сервера –