我制作了一个程序,将选定的视频从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 :(得分: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正在上传进度对话框。
答案 1 :(得分:0)
如果您想在通知区域中显示进度条,请参阅我的回答:Android: show notification bar on downloading application