In my android project i need to display seekbar and network speed(With how much speed the file is Uploading/Downloading from server using FTP Protocol). In my situation when i try to upload a file from emulator sdcard then it's showing the speed and seekbar at the end when the file is stored in the server, but my requirement is i need to show sheekbar and network speed continuously while the file is uploading into server. I am not understand where i did wrong in my code. Below is my code for file upload into ftp server:
Thanks In Advance.
#Override
protected String doInBackground(String... arg0) {
int count = 0;
FTPClient ObjFtpCon = new FTPClient();
//Toast.makeText(con, "FTPasync doInBackground() is called" ,Toast.LENGTH_SHORT).show();
try {
runOnUiThread(new Runnable() {
public void run() {
bar.setProgress(0);
//real_time.setText(0 + " secs");
test_avg.setText(0+ " kbps");
//peak.setText(0+" kbps");
}
});
updateUI(pp, R.drawable.pause);
//ObjFtpCon.connect("ftp.customhdclips.com");
ObjFtpCon.connect("ftp."+map.get("url").toString());
updateUI(status, "Connecting");
//if (ObjFtpCon.login("fstech#customhdclips.com", "fstech123")) {
if (ObjFtpCon.login(map.get("username").toString(), map.get("password").toString())) {
updateUI(status, "Connected");
ObjFtpCon.enterLocalPassiveMode(); // important!
ObjFtpCon.cwd("/");// to send the FTP CWD command to the server, receive the reply, and return the reply code.
//if (mode == 0) {
if(Integer.parseInt((map.get("oprn").toString()))== 0){ // Download File Using FTP Protocol
System.out.println("download test is called");
File objfile = new File(Environment.getExternalStorageDirectory() + File.separator + "/logo.png");
objfile.createNewFile();
FileOutputStream objFos = new FileOutputStream(objfile);
boolean blnresult = ObjFtpCon.retrieveFile("/logo.png", objFos);
objFos.close();
if (blnresult) {
// toast("Download succeeded");
// toast("Stored at : " +
// objfile.getAbsolutePath());
}
//***********************************************************
/*
File objfile = new File(
Environment.getExternalStorageDirectory()
+ File.separator + "/test.txt");
// System.out.println("total" + objfile.getTotalSpace() + " bytes");
objfile.createNewFile();
FileOutputStream objFos = new FileOutputStream(objfile);
boolean blnresult = ObjFtpCon.retrieveFile("/test.txt",
objFos);
objFos.close();
if (blnresult) {
System.out.println("download in ftp is successful");
// toast("Download succeeded");
// toast("Stored at : " +
// objfile.getAbsolutePath());
}*/
}
else {
// Upload
System.out.println("upload test is called");
//Toast.makeText(con, "upload FTP test is called", Toast.LENGTH_SHORT).show();
//ContextWrapper context = null;
//assetManager= context.getAssets();
assetManager = getResources().getAssets();
input1 = assetManager.open("hello.txt");
long total = 0;
long sleepingTime= 0;
final long started = System.currentTimeMillis();
int size = input1.available();
byte[] buffer = new byte[size];
byte dataByte[] = new byte[1024];
//byte dataByte[] = new byte[(int)((CharSequence) input1).length()];
//input1.read(buffer);
//final int lenghtOfFile = data.getBytes().length;
final int lenghtOfFile = input1.toString().getBytes().length;
System.out.println("length of file....."+lenghtOfFile);
ByteArrayInputStream byteArrayIS = new ByteArrayInputStream(input1.toString().getBytes());
System.out.println("ByteArrayIS value is...."+byteArrayIS);
System.out.println("started time --"+started);
updateUI(status, "Uploading");
while ((count = byteArrayIS.read(dataByte)) != -1)
{
System.out.println("read value is...."+byteArrayIS.read(dataByte));
while (sleep1) {
System.out.println("While Loop Sleep1 is Called");
Thread.sleep(1000);
sleepingTime +=1000;
}
total += count;
System.out.println("Total Value IS:: "+total);
System.out.println("Count Value Is:: "+count);
final int progress = (int) ((total * 100) / lenghtOfFile);
System.out.println("Progress Value IS::" + progress);
final long speed = total;
//duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000; --- When using this line then it's not updating Avarage
boolean result = ObjFtpCon.storeFile("/test.txt", input1);
//boolean result = ObjFtpCon.storeFile(map.get("file_address").toString()+"/test.txt", input1); --- When using this line then it's not updating Status
duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;
runOnUiThread(new Runnable() {
public void run() {
//bar.setProgress(progress);
// trans.setText("" + progress);
//duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;
//duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;
//real_time.setText(duration + " secs");
if (duration != 0) {
test_avg.setText((((speed / duration)*1000)*0.0078125) + " kbps");
bar.setProgress(progress);
/*if (pk <= (speed / duration) / 1024) {
pk = (speed / duration) / 1024;
}*/
if (pk <= ((speed / duration)*1000)*0.0078125) {
pk = (long)(((speed / duration)*1000)*0.0078125);
}
//peak.setText(pk + " kbps");
}
}
});
//in.close();
if (result) {
updateUI(status, "Uploaded");
// toast("Uploading succeeded");
// toast("Uploaded at /test.txt");
//duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;
System.out.println("curreent time..... "+System.currentTimeMillis());
System.out.println("started time --"+started);
System.out.println("sleep tome...."+sleepingTime);
System.out.println("duration is....."+duration);
/*runOnUiThread(new Runnable() {
public void run() {
bar.setProgress(progress);
// trans.setText("" + progress);
//duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;
real_time.setText(duration + " secs");
if (duration != 0) {
test_avg.setText((speed / duration) / 1024
+ " kbps");
if (pk <= (speed / duration) / 1024) {
pk = (speed / duration) / 1024;
}
peak.setText(pk + " kbps");
}
}
});*/
}
/*while(!result){Thread.sleep(1000);}*/
}
byteArrayIS.close();
}
}
else{
System.out.println("password entered is incorrect");
//Toast.makeText(con, "Username or/and password is incorrect", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e) {
e.printStackTrace();
// toast(e.getLocalizedMessage());
}
try {
ObjFtpCon.logout();
ObjFtpCon.disconnect();
}
catch (IOException e) {
e.printStackTrace();
// toast(e.getLocalizedMessage());
}
return null;
}
Since you're calling doInBackground(), I assume you're subclassing AsyncTask. If so, why aren't you using publishProgress and onProgressUpdate? runOnUiThread doesn't execute immediately unless you're already on the UI Thread, and because you're in doInBackground() you're in a background thread, not the UI Thread. There's a possibility that runOnUiThread() isn't actually running until doInBackground() is over. In comparison, publishProgress and onProgressUpdate are specifically designed to report progress from the background thread.
Related
I am implementing a download manager in native android where a thread pool executor is used to implement parallel downloads. A runnable is where the actual download happens, which is being executed on the pool threads. How can I send the download progress from the runnable to the UI? In order to send broadcasts, I need to pass context into the runnable. Is that the appropriate way?
How can I handle pause/resume/cancel of download gracefully?
Right now the moment user taps the pause/cancel button the value is updated in the DB and while the Thread.CurrentThread().IsInterrupted condition in the runnable becomes valid I check the status in database and decide whether I need to delete the partially downloaded file (if its cancel).
Also, will it be possible to know when the download completes so that I can remove the future object from the list?
public class Downloadable : Java.Lang.Object, IRunnable
{
private readonly string _destination;
private readonly int _productId;
public Downloadable(int productId)
{
_productId = productId;
_destination = Utils.StoragePath() + productId + ".zip";
}
public void Run()
{
int count;
try
{
Response response = CloudService.GetCloud().GetDownLoadURL(_productId.ToString(), true).Result;
if (string.Equals(response.status, "error", StringComparison.OrdinalIgnoreCase) || string.Equals(response.status, "internalError", StringComparison.OrdinalIgnoreCase))
{
//send error
}
else
{
DownloadPath downloadPath = JsonConvert.DeserializeObject<DownloadPath>(response.data);
string offlineUrl = downloadPath.contentUrl.Offline;
if (string.IsNullOrWhiteSpace(offlineUrl))
{
//send error
}
else
{
File directory = new File(Utils.StoragePath());
if (!directory.Exists())
directory.Mkdirs();
URL url = new URL(offlineUrl);
HttpURLConnection connection = (HttpURLConnection)url.OpenConnection();
long total = 0;
File file = new File(_destination);
file.CreateNewFile();
if (file.Exists() && file.Length() > 0)
{
total = file.Length();
connection.SetRequestProperty("Range", "Bytes=" + total + "-");
}
connection.Connect();
int lenghtOfFile = connection.ContentLength;
BufferedInputStream bufferedInputStream = new BufferedInputStream(url.OpenStream());
FileOutputStream fileOutputStream = new FileOutputStream(_destination, true);
byte[] buffer = new byte[1024];
count = 0;
while ((count = bufferedInputStream.Read(buffer, 0, 1024)) != -1)
{
if (Thread.CurrentThread().IsInterrupted)
{
if (DBService.GetDB().GetStatus(_productId) == (int)IpcCommon.Enumerations.Status.DOWNLOAD)
file.Delete();
break;
}
total += count;
System.Console.WriteLine("__PROGRESS__ " + (int)((total * 100) / lenghtOfFile));
System.Console.WriteLine("__PROGRESS__ ID " + _productId);
//publishProgress("" + (int)((total * 100) / lenghtOfFile));
fileOutputStream.Write(buffer, 0, count);
}
fileOutputStream.Close();
bufferedInputStream.Close();
}
}
}
catch (System.Exception exception)
{
IpcCommon.App.Logger.Log("Downloadable - File Download", new System.Collections.Generic.Dictionary<string, string> { { "Error", exception.Message } });
}
}
}
Dictionary<int, IFuture> _runningTaskList = new Dictionary<int, IFuture>();
int noOfCores = Runtime.GetRuntime().AvailableProcessors();
LinkedBlockingQueue _taskQueue = new LinkedBlockingQueue();
_threadPoolExecutor = new ThreadPoolExecutor(noOfCores, noOfCores * 2, 1, TimeUnit.Minutes, _taskQueue);
IFuture future = _threadPoolExecutor.Submit(new Downloadable(productId));
_runningTaskList.Add(productId, future);
Scenario :
Create request
**Interface**
#GET("someurl.mp4")
#Streaming
Call<ResponseBody> downloadFile(); // retrofit2.Call
**call**
RetrofitInterface retrofitInterface = retrofit.create(RetrofitInterface.class);
//okhttp3.ResponseBody
Call<ResponseBody> request = retrofitInterface.downloadFile();
try {
downloadFile(request.execute().body());
} catch (IOException e) {
e.printStackTrace();
}
Download bytes by bytes
private void downloadFile(ResponseBody body) throws IOException {
int count;
byte[] data;
data = new byte[1024 * 4];
long fileSize = body.contentLength();
Log.i("Download", "downloadFile: " + fileSize);
InputStream bis = new BufferedInputStream(body.byteStream(), 1024 * 8);
File outputFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), System.currentTimeMillis() + ".mp4");
try (OutputStream output = new FileOutputStream(outputFile)) {
long total = 0;
long startTime = System.currentTimeMillis();
Log.i("Download", "downloadFile size: " + fileSize);
int timeCount = 1;
while ((count = bis.read(data)) != -1) {
total += count;
totalFileSize = (int) (fileSize / (Math.pow(1024, 2)));
double current = Math.round(total / (Math.pow(1024, 2)));
int progress = (int) ((total * 100) / fileSize);
long currentTime = System.currentTimeMillis() - startTime;
Download download = new Download();
download.setTotalFileSize(totalFileSize);
if (currentTime > 1000 * timeCount) {
download.setCurrentFileSize((int) current);
download.setProgress(progress);
sendNotification(download);
timeCount++;
}
if (download.getProgress() != 0)
Log.i("Download", "progress: " + download.getProgress());
output.write(data, 0, count);
}
onDownloadComplete();
output.flush();
//output.close();
}
bis.close();
}
Problem
I am not able to port above code in RxJava using Observable/Single interface.
All i want is to download file bytes by bytes for some purpose.
I tried to call downloadFile(request.execute().body()); inside ongoing async operation(RxJava) but didn't work as expected.
There is no good reason to declare method as returning Call<ResponseBody> if you are using RxJava anyway. Declare it as Single<ResponseBody> and use its result directly.
I'm trying to download an image from url and I need to display the size of the file and the progress of the file downloading.
This is what I have.
int bytes_downloaded = cursor.getInt(cursor
.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
int bytes_total = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
final int dl_progress = (int) ((bytes_downloaded * 100l) / bytes_total);
runOnUiThread(new Runnable() {
#Override
public void run() {
getFileSize(fileSizeInKB);
mProgressDialog.setProgress((int) dl_progress);
}
});
As of now its showing %(ie..10/100)
If I set it to mProgressDialog.setProgressNumberFormat("%1d kb / %2d kB")
its showing as 1kb of 100kb but unable to get the actual size of the file which I'm trying to download
I need it display as 1.2MB/3.6MB
Issue is the progress is displaying as seen below 60/100 but I don't want that
Finally made it to work:
Here is the way
long downloadedsize, filesize;
public static final double SPACE_KB = 1024;
public static final double SPACE_MB = 1024 * SPACE_KB;
public static final double SPACE_GB = 1024 * SPACE_MB;
public static final double SPACE_TB = 1024 * SPACE_GB;
and set this to progressbar
mProgressDialog.setProgressNumberFormat((bytes2String(downloadedsize)) + "/" + (bytes2String(filesize)));
Method: Converting byte to string
public static String bytes2String(long sizeInBytes) {
NumberFormat nf = new DecimalFormat();
nf.setMaximumFractionDigits(2);
try {
if ( sizeInBytes < SPACE_KB ) {
return nf.format(sizeInBytes) + " Byte(s)";
} else if ( sizeInBytes < SPACE_MB ) {
return nf.format(sizeInBytes/SPACE_KB) + " KB";
} else if ( sizeInBytes < SPACE_GB ) {
return nf.format(sizeInBytes/SPACE_MB) + " MB";
} else if ( sizeInBytes < SPACE_TB ) {
return nf.format(sizeInBytes/SPACE_GB) + " GB";
} else {
return nf.format(sizeInBytes/SPACE_TB) + " TB";
}
} catch (Exception e) {
return sizeInBytes + " Byte(s)";
}
}
I have an issue when I am trying to download a file from server using FTP. I need to display seek-bar status of downloading file and download speed of the Internet. I am able to display seek-bar status and speed of the Internet for HTTP, but for FTP I am not able to perform that same task. In the attached image below I need to display seek-bar and network speed for FTP and HTTP. Below is the source code I used for HTTP and FTP. I don't know where I missed it?
HTTP Code:
class DownloadFileAsync extends AsyncTask<String, String, String> { //see the summary of asyncTask
long duration, pk;
private boolean sleep = false;
private HashMap<String, Object> map;
private ProgressBar bar;
private TextView real_time, test_avg, peak, status;
private ImageView pp;
//constructor
public DownloadFileAsync(HashMap<String, Object> map) {
this.map = map;
bar = (ProgressBar) map.get("bar");
// trans = (TextView) map.get("trans");
//real_time = (TextView) map.get("real_time");
test_avg = (TextView) map.get("test_avg");
//peak = (TextView) map.get("peak");
status = (TextView) map.get("status");
pp = (ImageView) map.get("pp");
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... aurl) {
int count = 0;
try {
updateUI(pp, R.drawable.pause);
updateUI(status, "Connecting");
URL url = new URL(map.get("url").toString());
URLConnection conexion = url.openConnection();
conexion.connect();
final int lenghtOfFile = conexion.getContentLength();
InputStream input = new BufferedInputStream(url.openStream());
updateUI(status, "Connected");
OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory()
+ File.separator
+ Info.getInfo(con).HTTP_DOWNLOAD_FILE_NAME);
byte data[] = new byte[1024];
long total = 0;
final long started = System.currentTimeMillis();
long sleepingTime= 0;
System.out.println("started time --"+started);
updateUI(status, "Downloading");
while ((count = input.read(data)) != -1) {
while (sleep) {
Thread.sleep(1000);
sleepingTime +=1000;
}
total += count;
final int progress = (int) ((total * 100) / lenghtOfFile);
final long speed = total;
duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;
runOnUiThread(new Runnable() {
public void run() {
bar.setProgress(progress);
// trans.setText("" + progress);
//duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;
//real_time.setText(duration + " secs");
if (duration != 0) {
test_avg.setText((speed / duration) / 1024 + " kbps");
if (pk <= (speed / duration) / 1024)
{
pk = (speed / duration) / 1024;
}
//peak.setText(pk + " kbps");
}
}
});
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
updateUI(status, "Success");
}
catch (final Exception e) {
e.printStackTrace();
updateUI(status, "Failed");
}
updateUI(pp, R.drawable.resume);
return null;
}
private void updateUI(final TextView tv, final String str) {
runOnUiThread(new Runnable() {
public void run() {
tv.setText(str);
}
});
}
private void updateUI(final ImageView iv, final int id) { // may create problem
runOnUiThread(new Runnable() {
public void run() {
iv.setImageResource(id);
}
});
}
public void gotosleep(boolean val) {
sleep = val;
}
public boolean areYouSleeping() {
return sleep;
}
#Override
protected void onPostExecute(String unused) {
try {
//System.out.println("Info.getInfo(con).data.indexOf(map)==="+Info.getInfo(con).data.indexOf(map)+" map "+map);
if (!PARALLEL_MODE //for sequence mode
&& (Info.getInfo(con).data.indexOf(map) + 1) <= Info.getInfo(con).data.size()
&& testRunning) {
/*System.out.println("Info.getInfo(con).data.indexOf(map) + 1 "+Info.getInfo(con).data.indexOf(map) + 1
+" Info.getInfo(con).data.size() "+Info.getInfo(con).data.size()+" testRunning "+testRunning);
System.out.println("Info.getInfo(con).data.indexOf(map)==="+Info.getInfo(con).data.indexOf(map)+" map "+map);*/
System.out.println("asynclist "+asynclist.size());
asynclist.remove(0); //asynclist contains objects of (downloadAsync(map))
if(asynclist.size() > 0){
System.out.println("tlist in post execute+++"+tlist);
//DownloadFileAsync dfa = new DownloadFileAsync(tlist.get(0));
DownloadFileAsync dfa = (DownloadFileAsync) asynclist.get(0);
dfa.execute();
tlist.remove(0);
}
else{
startTests();
}
}
else if (PARALLEL_MODE && stopCount < asynclist.size() && testRunning) { //for parallel mode
System.out.println("stopCount before condition= " + stopCount);
if (stopCount == asynclist.size() -1 && testRunning) {
System.out.println("stopCount inside 1st condition= " + stopCount);
stopCount = 0;
// stopTests(0);
startTests();
System.out.println("Tests Started");
}
else {
stopCount++;
System.out.println("stopCount after increment = " + stopCount);
;
}
}
}
catch (Exception ed) {
ed.printStackTrace();
go.setText(R.string.go);
//testRunning = false;
}
}
}
For FTP:--
class FTPAsync extends AsyncTask<String, String, String> {
//private int mode = -1;
//added
long duration, pk;
private boolean sleep1 = false;
private HashMap<String, Object> map;
private ProgressBar bar;
private TextView real_time, test_avg, peak, status;
private ImageView pp;
//
public FTPAsync(int mode) {
// this.mode = mode;
}
//added
public FTPAsync(HashMap<String, Object> map) {
//Toast.makeText(con, "ftpAsync constructer is called" ,Toast.LENGTH_SHORT).show();
this.map = map;
bar = (ProgressBar) map.get("bar");
// trans = (TextView) map.get("trans");
//real_time = (TextView) map.get("real_time");
test_avg = (TextView) map.get("test_avg");
//peak = (TextView) map.get("peak");
status = (TextView) map.get("status");
pp = (ImageView) map.get("pp");
}
//
#Override
protected void onPreExecute() {
//Toast.makeText(con, "onPreExecute() is called" ,Toast.LENGTH_SHORT).show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
int count = 0;
FTPClient ObjFtpCon = new FTPClient();
//Toast.makeText(con, "FTPasync doInBackground() is called" ,Toast.LENGTH_SHORT).show();
try {
runOnUiThread(new Runnable() {
public void run() {
bar.setProgress(0);
//real_time.setText(0 + " secs");
//test_avg.setText(0+ " kbps");
//peak.setText(0+" kbps");
}
});
updateUI(pp, R.drawable.pause);
//ObjFtpCon.connect("ftp.customhdclips.com");
ObjFtpCon.connect("ftp."+map.get("url").toString());
updateUI(status, "Connecting");
//if (ObjFtpCon.login("fstech#customhdclips.com", "fstech123")) {
if (ObjFtpCon.login(map.get("username").toString(), map.get("password").toString())) {
updateUI(status, "Connected");
// toast("Connected to FTP Server : ftp.customhdclips.com");
ObjFtpCon.enterLocalPassiveMode(); // important!
ObjFtpCon.cwd("/");// to send the FTP CWD command to the server, receive the reply, and return the reply code.
//if (mode == 0) {
if(Integer.parseInt((map.get("oprn").toString()))== 0){
// Download
System.out.println("download test is called");
File objfile = new File(
Environment.getExternalStorageDirectory()
+ File.separator + "/logo.png");
objfile.createNewFile();
FileOutputStream objFos = new FileOutputStream(objfile);
boolean blnresult = ObjFtpCon.retrieveFile("/logo.png",
objFos);
objFos.close();
if (blnresult) {
// toast("Download succeeded");
// toast("Stored at : " +
// objfile.getAbsolutePath());
}
}
else {
// Upload
System.out.println("upload test is called");
//Toast.makeText(con, "upload FTP test is called", Toast.LENGTH_SHORT).show();
//ContextWrapper context = null;
//assetManager= context.getAssets();
assetManager = getResources().getAssets();
input1 = assetManager.open("hello.txt");
final long started = System.currentTimeMillis();
int size = input1.available();
//byte[] buffer = new byte[size];
byte dataByte[] = new byte[1024];
//input1.read(buffer);
//String data = "ZK DATA TESTER TEST DATA1sdfsdf";
String data = input1.toString();
System.out.println("dat value is........"+data);
final int lenghtOfFile = data.getBytes().length;
//final int lenghtOfFile = input1.getBytes().length;
System.out.println("length of file....."+lenghtOfFile);
ByteArrayInputStream in = new ByteArrayInputStream(
data.getBytes());
//toast("Uploading /test.txt");
//Toast.makeText(con,"File Size : " +data.getBytes().length + " bytes",Toast.LENGTH_SHORT).show();
//byte b[] = new byte[1024];
long total = 0;
long sleepingTime= 0;
System.out.println("started time --"+started);
updateUI(status, "Uploading");
while ((count = in.read(dataByte)) != -1)
{
System.out.println("read value is...."+in.read(dataByte));
while (sleep1) {
Thread.sleep(1000);
System.out.println("ftp upload is in sleeping mode");
sleepingTime +=1000;
}
System.out.println("Total count --"+count);
total += count;
System.out.println("Only Total --"+total);
final int progress = (int) ((total * 100) / lenghtOfFile);
final long speed = total;
//duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;
boolean result = ObjFtpCon.storeFile("/test.txt", input1);
//boolean result = ObjFtpCon.storeFile(map.get("file_address").toString()+"/test.txt", input1);
duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;
runOnUiThread(new Runnable() {
public void run() {
bar.setProgress(progress);
// trans.setText("" + progress);
//duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;
//duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;
//real_time.setText(duration + " secs");
if (duration != 0) {
test_avg.setText((((speed / duration)*1000)*0.0078125)
+ " kbps");
/*if (pk <= (speed / duration) / 1024) {
pk = (speed / duration) / 1024;
}*/
if (pk <= ((speed / duration)*1000)*0.0078125) {
pk = (long)(((speed / duration)*1000)*0.0078125);
}
//peak.setText(pk + " kbps");
}
}
});
//in.close();
if (result) {
updateUI(status, "Uploaded");
// toast("Uploading succeeded");
// toast("Uploaded at /test.txt");
//duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;
System.out.println("curreent time..... "+System.currentTimeMillis());
System.out.println("started time --"+started);
System.out.println("sleep tome...."+sleepingTime);
System.out.println("duration is....."+duration);
/*runOnUiThread(new Runnable() {
public void run() {
bar.setProgress(progress);
// trans.setText("" + progress);
//duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;
real_time.setText(duration + " secs");
if (duration != 0) {
test_avg.setText((speed / duration) / 1024
+ " kbps");
if (pk <= (speed / duration) / 1024) {
pk = (speed / duration) / 1024;
}
peak.setText(pk + " kbps");
}
}
});*/
}
/*while(!result){Thread.sleep(1000);}*/
}
in.close();
}
}
else{
System.out.println("password entered is incorrect");
//Toast.makeText(con, "Username or/and password is incorrect", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e) {
e.printStackTrace();
// toast(e.getLocalizedMessage());
}
try {
ObjFtpCon.logout();
ObjFtpCon.disconnect();
}
catch (IOException e) {
e.printStackTrace();
// toast(e.getLocalizedMessage());
}
return null;
}
#override
protected void onPostExecute(String unused) {
try {
//System.out.println("Info.getInfo(con).data.indexOf(map)==="+Info.getInfo(con).data.indexOf(map)+" map "+map);
if (!PARALLEL_MODE //for sequence mode
&& (Info.getInfo(con).data.indexOf(map) + 1) <= Info.getInfo(con).data.size()
&& testRunning) {
System.out.println("ftpasynclist "+ftpasynclist.size());
ftpasynclist.remove(0); //asynclist contains objects of (FTPAsync(map))
if(ftpasynclist.size() > 0){
System.out.println("tlist in post execute+++"+ftplist);
//DownloadFileAsync dfa = new DownloadFileAsync(tlist.get(0));
FTPAsync dfa = (FTPAsync)ftpasynclist.get(0);
dfa.execute();
ftplist.remove(0);
}
else{
startTests();
}
}
else if (PARALLEL_MODE //for parallel mode
&& ftpStopCount <ftpasynclist.size()
&& testRunning) {
System.out.println("stopCount before condition= " +ftpStopCount);
if (ftpStopCount == ftpasynclist.size() -1 && testRunning) {
System.out.println("stopCount inside 1st condition= " + ftpStopCount);
ftpStopCount = 0;
// stopTests(0);
startTests();
System.out.println("Tests Started");
}
else {
ftpStopCount++;
System.out.println("stopCount after increment = " + ftpStopCount);
;
}
}
}
catch (Exception ed) {
ed.printStackTrace();
go.setText(R.string.go);
//testRunning = false;
}
super.onPostExecute(unused);
}
private void updateUI(final TextView tv, final String str) {
runOnUiThread(new Runnable() {
public void run() {
tv.setText(str);
}
});
}
private void updateUI(final ImageView iv, final int id) { // may create problem
runOnUiThread(new Runnable() {
public void run() {
iv.setImageResource(id);
}
});
}
public void gotosleep(boolean val) {
sleep1 = val;
}
public boolean areYouSleeping() {
return sleep1;
}
}
In my android project i need to display seekbar and network speed(With how much speed the file is Uploading/Downloading from server using FTP Protocol). In my situation when i try to upload a file from emulator sdcard then it's showing the speed and seekbar at the end when the file is stored in the server, but my requirement is i need to show sheekbar and network speed while the file is uploading into server. I am not understand where i did wrong in my code. In this attached image showing seekbar and TestAvarage speed for HTTP is fine like this i need to implement in FTP for upload a file to server. Below is my code for file upload using ftp to remote server:
Thanks In Advance.
#Override
protected String doInBackground(String... arg0) {
int count = 0;
FTPClient ObjFtpCon = new FTPClient();
//Toast.makeText(con, "FTPasync doInBackground() is called" ,Toast.LENGTH_SHORT).show();
try {
runOnUiThread(new Runnable() {
public void run() {
bar.setProgress(0);
//real_time.setText(0 + " secs");
//test_avg.setText(0+ " kbps");
//peak.setText(0+" kbps");
}
});
updateUI(pp, R.drawable.pause);
//ObjFtpCon.connect("ftp.customhdclips.com");
ObjFtpCon.connect("ftp."+map.get("url").toString());
updateUI(status, "Connecting");
//if (ObjFtpCon.login("fstech#customhdclips.com", "fstech123")) {
if (ObjFtpCon.login(map.get("username").toString(), map.get("password").toString())) {
updateUI(status, "Connected");
// toast("Connected to FTP Server : ftp.customhdclips.com");
ObjFtpCon.enterLocalPassiveMode(); // important!
ObjFtpCon.cwd("/");// to send the FTP CWD command to the server, receive the reply, and return the reply code.
//if (mode == 0) {
if(Integer.parseInt((map.get("oprn").toString()))== 0){
// Download
System.out.println("download test is called");
File objfile = new File(Environment.getExternalStorageDirectory()
+ File.separator + "/logo.png");
/* * toast("Downloading /logo.png"); toast("File Size : "
* + objfile.getTotalSpace() + " bytes");*/
objfile.createNewFile();
FileOutputStream objFos = new FileOutputStream(objfile);
boolean blnresult = ObjFtpCon.retrieveFile("/logo.png",
objFos);
objFos.close();
if (blnresult) {
// toast("Download succeeded");
// toast("Stored at : " +
// objfile.getAbsolutePath());
}
//***********************************************************
/*
File objfile = new File(
Environment.getExternalStorageDirectory()
+ File.separator + "/test.txt");
// System.out.println("total" + objfile.getTotalSpace() + " bytes");
objfile.createNewFile();
FileOutputStream objFos = new FileOutputStream(objfile);
boolean blnresult = ObjFtpCon.retrieveFile("/test.txt",
objFos);
objFos.close();
if (blnresult) {
System.out.println("download in ftp is successful");
// toast("Download succeeded");
// toast("Stored at : " +
// objfile.getAbsolutePath());
}*/
}
else {
ObjFtpCon.connect("ftp."+map.get("url").toString());
updateUI(status, "Connecting");
ObjFtpCon.login(map.get("username").toString(), map.get("password").toString());
ObjFtpCon.enterLocalPassiveMode();
ObjFtpCon.cwd("/var/www/html/BevdogAnd");
ObjFtpCon.setFileType(FTP.BINARY_FILE_TYPE);
final long started = System.currentTimeMillis();
long sleepingTime= 0;
String sourceFileUri =extStorageDirectory+"/zkfile"+filename;
File secondLocalFile = new File(sourceFileUri);
long fileSize = secondLocalFile.length();
int sentBytes = 0;
InputStream inputStream = new FileInputStream(secondLocalFile);
System.out.println("Start uploading second file");
OutputStream outputStream = ObjFtpCon.storeFileStream(filename);
byte[] bytesIn = new byte[512];
int read = 0;
while ((read = inputStream.read(bytesIn)) != -1) {
updateUI(status, "Uploading");
outputStream.write(bytesIn, 0, read);
sentBytes+=read;
final int progress = (int) ((sentBytes * 100) / fileSize);
final long speed = sentBytes;
duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;
runOnUiThread(new Runnable() {
public void run() {
bar.setProgress(progress);
if (duration != 0) {
//test_avg.setText((((speed / duration)*1000)*0.0078125) + " kbps");
test_avg.setText((speed / duration) / 1024 + " kbps");
if (pk <= (speed / duration) / 1024) {
pk = (speed / duration) / 1024;
}
/*if (pk <= ((speed / duration)*1000)*0.0078125) {
pk = (long)(((speed / duration)*1000)*0.0078125);
}*/
//peak.setText(pk + " kbps");
}
}
});
}
inputStream.close();
outputStream.close();
boolean completed = ObjFtpCon.completePendingCommand();
updateUI(status, "Completed");
if (completed) {
}
}
}
/*-------------------------------------------------------------*/
/*
URL url = new URL(map.get("url").toString());
URLConnection conexion = url.openConnection();
conexion.connect();
updateUI(status, "Connected");
final int lenghtOfFile = conexion.getContentLength();
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(
Environment.getExternalStorageDirectory()
+ File.separator
+ Info.getInfo(con).HTTP_DOWNLOAD_FILE_NAME);
byte data[] = new byte[1024];
long total = 0;
final long started = System.currentTimeMillis();
long sleepingTime= 0;
System.out.println("started time --"+started);
updateUI(status, "Downloading");
while ((count = input.read(data)) != -1) {
while (sleep) {
Thread.sleep(1000);
sleepingTime +=1000;
}
total += count;
final int progress = (int) ((total * 100) / lenghtOfFile);
final long speed = total;
duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;
runOnUiThread(new Runnable() {
public void run() {
bar.setProgress(progress);
*/
/*-----------------------------------------------------------------------*/
else{
System.out.println("password entered is incorrect");
//Toast.makeText(con, "Username or/and password is incorrect", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e) {
e.printStackTrace();
// toast(e.getLocalizedMessage());
}
try {
ObjFtpCon.logout();
ObjFtpCon.disconnect();
}
catch (IOException e) {
e.printStackTrace();
// toast(e.getLocalizedMessage());
}
return null;
}
mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// TODO Auto-generated method stub
if(fromUser){
mPlayer.seekTo(progress);
mSeekBar.setProgress(progress);
}
}
});