I upload photo to the server via the default HttpClient in Android SDK. I want to show progress in the user interface, is there a way to find out how much has been uploaded?
1) Be sure to perform your upload in a Service with its own thread.
2) To get the progress: Wrap your InputStream in this class, and use a a httpmime.jar library which has MultiPart support for HttpClient. I used a thread which checks the progress and updates the progressbar in the notification.
package com.hyves.android.service.upload;
import java.io.IOException;
import java.io.InputStream;
/**
* This outputstream wraps an existing outputstream and provides
* callbacks after certain amount of bytes to a HttpCallback
*
* @author tjerk
*/
public class ProgressNotifyingInputStream extends InputStream {
private InputStream wrappedStream;
private int count = 0;
private int totalSize;
/**
* Creates a new notifying outputstream which wraps an existing one.
* When you write to this stream the callback will be notified each time when
* updateAfterNumberBytes is written.
*
* @param stream the outputstream to be wrapped
* @param totalSize the totalsize that will get written to the stream
*/
public ProgressNotifyingInputStream(InputStream stream, int totalSize) {
if(stream==null) {
throw new NullPointerException();
}
if(totalSize == 0) {
throw new IllegalArgumentException("totalSize argument cannot be zero");
}
this.wrappedStream = stream;
this.totalSize = totalSize;
}
@Override
public int read() throws IOException {
count++;
return wrappedStream.read();
}
/**
* Get progress from 0 to 100
* @return
*/
public int getProgress() {
return count * 100 / totalSize;
}
}