Android FTP file Uploading then Display Seekbar & network speed status issue - android

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);
}
}
});

Related

How can i cancel running download file?

I want to cancel currently download file from notification area & I want to add cancel button at the bottom of notification download progress. By clicking on that cancel button, download should be cancel. Here is my class DownloadSong using which I perform download file. What modifications I need to do?
public class DownloadSong extends AsyncTask<String, Integer, String> {
Activity activity;
public static String songName, songURL;
private NotificationHelper mNotificationHelper;
public static int notificationID = 1;
boolean download = false;
NotificationManager nm;
public DownloadSong(Activity activity, String songName, String songURL) {
this.activity = activity;
this.songName = songName;
this.songURL = songURL;
mNotificationHelper = new NotificationHelper(activity, songName);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
notificationID++;
mNotificationHelper.createNotification(notificationID);
}
#Override
protected String doInBackground(String... file_URL) {
try {
URL url = new URL(songURL);
HttpURLConnection URLconnection = (HttpURLConnection) url.openConnection();
URLconnection.setRequestMethod("GET");
URLconnection.setDoOutput(true);
URLconnection.connect();
// Detect the file length
int fileLength = URLconnection.getContentLength();
File fSDcard = Environment.getExternalStorageDirectory();
String strSdcardPath = fSDcard.getAbsolutePath();
File fDirectory = new File(strSdcardPath + "/GSD");
if (!fDirectory.exists()) {
fDirectory.mkdir();
}
File fMyFile = new File(fDirectory.getAbsolutePath() + "/" + songName + ".mp3");
Log.e("Download file name ", fMyFile.toString());
FileOutputStream out = new FileOutputStream(fMyFile, true);
InputStream input_File = URLconnection.getInputStream();
byte[] data = new byte[1024];
int total = 0;
int count;
while ((count = input_File.read(data)) != -1) {
total += count;
publishProgress((int) (total * 100 / fileLength));
out.write(data, 0, count);
}
out.flush();
out.close();
input_File.close();
} catch (IOException e) {
Log.e("Download Error : ", "Failed");
}
Log.e("Download status", " Complete ");
return null;
}
#Override
protected void onPostExecute(String s) {
Toast.makeText(activity, "Song " + "'" + songName + "'" + " downloaded successfully", Toast.LENGTH_LONG).show();
//pDialog.dismiss();
if (download) {
Toast.makeText(activity, "Could Not Connect to Server.", Toast.LENGTH_LONG).show();
mNotificationHelper.clearNotification();
} else
mNotificationHelper.completed();
}
#Override
protected void onProgressUpdate(Integer... progress) {
//pDialog.setProgress(progress[0]);
mNotificationHelper.progressUpdate(progress[0]);
super.onProgressUpdate(progress);
}
}
Most of the time is spent in the loop
while ((count = input_File.read(data)) != -1) {
total += count;
publishProgress((int) (total * 100 / fileLength));
out.write(data, 0, count);
}
You can add a check to see if the task is cancelled,
while ((count = input_File.read(data)) != -1 && !isCancelled()) {
total += count;
publishProgress((int) (total * 100 / fileLength));
out.write(data, 0, count);
}
and cancel the download by calling
yourAsyncTask.cancel()
You can cancel asynctask forcefully
Check This
declare your asyncTask in your activity:
private YourAsyncTask mTask;
instantiate it like this:
mTask = new YourAsyncTask().execute();
kill/cancel it like this:
mTask.cancel(true);

how to all file download in android and save all file in sd card?

In my case i click download button when download all file but in show all file sdcard and some file display . and i used thread .what me wrong in my code : and Cancel(cl) button working but in i used delted download file is not working and {cl and dl button} setVisibitly not changed. My Code Below: Please Helpme>
mainDownloadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
adtf.setAllDownload();
}
});
}
public class MyListAdapter extends BaseAdapter {
private LayoutInflater mInflater;
ProgressBar pr;
ProgressBar[] prArray = new ProgressBar[list.size()];
Button cl, dl;
ImageView im;
DownloadFileFromURL downloadFileFromURL;
public MyListAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return list.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public void setAllDownload() {
if (prArray.length > 0) {
for (int i = 0; i < prArray.length; i++) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
downloadFileFromURL = new DownloadFileFromURL(dl, cl);
downloadFileFromURL.execute(pr, list.get(i).url_video, i);
}
}
}
public View getView(final int position, View convertView,
ViewGroup parent) {
convertView = mInflater.inflate(R.layout.custome_list_view, null);
cl = (Button) convertView.findViewById(R.id.cancle_sedual);
dl = (Button) convertView.findViewById(R.id.download_sedual);
pr = (ProgressBar) convertView.findViewById(R.id.listprogressbar);
prArray[position] = pr;
im = (ImageView) convertView.findViewById(R.id.list_image);
im.setImageResource(list.get(position).images[position]);
getProgress(pr, position, cl, dl);
// pr.setProgress(getItem(position));
cl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.v("log_tag","Cancle Button Click");
// dl.setVisibility(View.VISIBLE);
dl.setVisibility(View.VISIBLE);
cl.setVisibility(View.GONE);
downloadFileFromURL = new DownloadFileFromURL(dl, cl);
//downloadFileFromURL.cancel(true);
downloadFileFromURL.downloadFile();
pr.setProgress(0);
}
});
dl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
str_start = list.get(position).url_video;
dl.setVisibility(View.GONE);
cl.setVisibility(View.VISIBLE);
Log.v("log_tag","Start Button Click ");
//
// new DownloadFileFromURL().execute(str_start);
downloadFileFromURL = new DownloadFileFromURL(dl, cl);
downloadFileFromURL.execute(pr, str_start, position);
}
});
return convertView;
}
}
class DownloadFileFromURL extends AsyncTask<Object, String, Integer> {
int count = 0;
ProgressDialog dialog;
ProgressBar progressBar;
int myProgress;
int position;
Button start, cancel;
boolean download1 = false;
public DownloadFileFromURL(Button start, Button cancel) {
this.start = start;
this.cancel = cancel;
}
/**
* Before starting background thread Show Progress Bar Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
ProgressBar progressBar;
download1 = true;
}
public void downloadFile() {
this.download1 = false;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
/**
* Downloading file in background thread
* */
#Override
protected Integer doInBackground(Object... params) {
//Log.v("log_tag", "params :::; " + params);
int count;
progressBar = (ProgressBar) params[0];
position = (Integer) params[2];
try {
// URL url = new URL(f_url[0]);
URL url = new URL((String) params[1]);
//Log.v("log_tag", "name ::: " + url);
name = ((String) params[1]).substring(((String) params[1])
.lastIndexOf("/") + 1);
//Log.v("log_tag", "name Substring ::: " + name);
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(),
8192);
download = new File(Environment.getExternalStorageDirectory()
+ "/download/");
if (!download.exists()) {
download.mkdir();
}
String strDownloaDuRL = download + "/" + name;
Log.v("log_tag", " down url " + strDownloaDuRL);
FileOutputStream output = new FileOutputStream(strDownloaDuRL);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
if (this.download1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
// publishProgress("" + (int) ((total * 100) /
// lenghtOfFile));
// writing data to file
progressBar
.setProgress((int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
setProgress(progressBar, position, start, cancel, this);
}
}
// flushing output
output.flush();
if(!this.download1){
File delete = new File(strDownloaDuRL);
delete.delete();
}
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return 0;
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
// Log.v("log_tag", "progress :: " + values);
// setting progress percentage
// pDialog.setProgress(Integer.parseInt(progress[0]));
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
Log.v("log", "login ::: 4::: " + download);
String videoPath = download + "/" + name;
String chpName = name;
Log.v("log_tag", "chpName ::::" + chpName + " videoPath "
+ videoPath);
db.execSQL("insert into videoStatus (chapterNo,videoPath) values(\""
+ chpName + "\",\"" + videoPath + "\" )");
}
}
private void setProgress(final ProgressBar pr, final int position,
final Button Start, final Button cancel,
final DownloadFileFromURL downloadFileFromURL) {
ProgressBarSeek pbarSeek = new ProgressBarSeek();
pbarSeek.setPosition(position);
pbarSeek.setProgressValue(pr.getProgress());
//Log.v("log_tag", position + " progress " + pr.getProgress());
progreeSeekList.add(pbarSeek);
/* cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.v("log_tag","Cancle Button Click Set progress");
Start.setVisibility(View.VISIBLE);
cancel.setVisibility(View.GONE);
downloadFileFromURL.cancel(true);
pr.setProgress(0);
}
});
Start.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.v("log_tag","Start Button Click set Progress");
str_start = list.get(position).url_video;
Start.setVisibility(View.GONE);
cancel.setVisibility(View.VISIBLE);
Log.v("log_tag", "str_start " + str_start);
//
// new DownloadFileFromURL().execute(str_start);
DownloadFileFromURL downloadFileFromU = new DownloadFileFromURL(
Start, cancel);
downloadFileFromU.execute(pr, str_start, position);
}
});*/
}
private void getProgress(ProgressBar pr, int position, Button cl, Button dl) {
if (progreeSeekList.size() > 0) {
for (int j = 0; j < progreeSeekList.size(); j++) {
if (position == progreeSeekList.get(j).getPosition()) {
pr.setProgress(progreeSeekList.get(j).getProgressValue());
dl.setVisibility(View.GONE);
cl.setVisibility(View.VISIBLE);
}
}
}
}
}
You can try using the below code to download the files from the url and save into the sdcard:
public void DownloadFromUrl(String DownloadUrl, String fileName) {
try {
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath() + "/xmls");
if(dir.exists()==false) {
dir.mkdirs();
}
URL url = new URL(DownloadUrl); //you can write here any link
File file = new File(dir, fileName);
long startTime = System.currentTimeMillis();
Log.d("DownloadManager", "download url:" + url);
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
ByteArrayBuffer baf = new ByteArrayBuffer(5000);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.flush();
fos.close();
Log.d("DownloadManager", "download ready in" + ((System.currentTimeMillis() - startTime) / 1000) + " sec");
} catch (IOException e) {
Log.d("DownloadManager", "Error: " + e);
}
}
Also keep in mind that you specify the below permissions in your manifest file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
I hope it will help you.
Thanks

How to Use Android SeekBar For File Upload and Download using FTP?

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;
}
}

Android Fileupload using FTP Protocal Not showing ProgressBar

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.

force close, download file with asynctask

i have a running download function. but when i run it, like 80% of the time it make my phone laggy, force close, not responding for a very long time like 1~2 minutes. this case happened very randomly, i cant really trace what is the problem. the device will turn back to normally after the download is complete. i have tried on various devices such as galaxy S2, galaxy note, SE xperia Arc S, and few tables. problem remains the same. can anyone advice me how to improve my code? below is my existing code:
public void onClickDownload(View view){
String url = "http://www.mydomain.com./" + fileURL;
url = url.replaceAll(" ","%20");
String sourceUrl = url;
new DownloadFileAsync().execute(sourceUrl);
}
public class DownloadFileAsync extends AsyncTask<String, Integer, Void> {
private boolean run_do_in_background = true;
#Override
protected void onPreExecute(){
super.onPreExecute();
}
#Override
protected Void doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lengthOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lengthOfFile);
File folder = new File(Environment.getExternalStorageDirectory() + "/MaxApps");
boolean success = false;
if (!folder.exists()) {
success = folder.mkdirs();
}
if (!success) {
} else {
}
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/MaxApps/" + apkURL);
byte data[] = new byte[100*1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
int progressPercent = (int) ((total*100)/lengthOfFile);
if(progressPercent % 5 == 0){
publishProgress(progressPercent);
}
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
notificationManager.cancel(Integer.parseInt(ID.toString()));
Notification MyN = new Notification(); MyN.icon = R.drawable.logo1;
MyN.tickerText = "Download Failed";
MyN.number = 1;
MyN.setLatestEventInfo (getApplicationContext(), apkURL + " Download Failed.", "Please try again", MyPI);
MyN.flags |= Notification.FLAG_AUTO_CANCEL;
MyNM.notify(1, MyN);
run_do_in_background = false;
}
return null;
}
#Override
protected void onProgressUpdate(Integer... progress) {
notification.contentView.setProgressBar(R.id.pbStatus, 100, progress[0], false);
notificationManager.notify(Integer.parseInt(ID.toString()), notification);
}
#Override
protected void onPostExecute(Void unused) {
if(run_do_in_background) {
notificationManager.cancel(Integer.parseInt(ID.toString()));
Notification MyN = new Notification(); MyN.icon = R.drawable.logo1;
MyN.tickerText = "Download Complete";
MyN.number = 1;
MyN.setLatestEventInfo (getApplicationContext(), "Download Complete, Click to install.", apkURL, MyPI);
MyN.flags |= Notification.FLAG_AUTO_CANCEL;
MyNM.notify(Integer.parseInt(ID.toString()) , MyN);
}
}
}
It might be that updating UI is taking long? Maybe you can try to test like this and see if it makes a difference:
#Override
protected void onProgressUpdate(Integer... progress) {
Log.d("ANDRO_ASYNC", "Progress: " + progress[0]);
}
By the way, this is not related to what you are asking, but I think you have problem in your code that handles the progress:
int progressPercent = (int) ((total*100)/lengthOfFile);
if(progressPercent % 5 == 0){
publishProgress(progressPercent);
}
That will update the progress only when it is exactly 5,10,15,20% etc... I guess you actually want to update progress when it is at least %5 further than before.
int previousProgress = 0;
while ((count = input.read(data)) != -1) {
total += count;
int progressPercent = (int) ((total*100)/lengthOfFile);
if(progressPercent - previousProgress >= 5) {
previousProgress = progressPercent;
publishProgress(progressPercent);
}
output.write(data, 0, count);
}

Categories

Resources