I made an app that downloads videos from our server.
The issue is:
When i cancel the downloading i call:
myAsyncTask.cancel(true)
I noticed, that myAsyncTask doesn't stops on calling cancel... my ProgressDialog still goes up and its like jumping from status to status showing me that each time I cancel and start again an AsyncTask by clicking the download button, a new AsyncTask starts...
Each time I click download.. then cancel, then again download a separate AsyncTask starts.
Why is myAsynTask.cancle(true) not cancelling my task ? I don't want it anymore on the background. I just want to completely shut it down if I click cancel.
How to do it ?
E D I T:
Thanks to gtumca-MAC, and the others who helped me did it by:
while (((count = input.read(data)) != -1) && (this.isCancelled()==false))
{
total += count;
publishProgress((int) (total * 100 / lenghtOfFile));
output.write(data, 0, count);
}
Thanks!!!
AsyncTask does not cancel process on
myAsynTask.cancel(true)
For that you have to stop it manually.
for example you are downloading video in doInBackground(..) in while/for loop.
protected Long doInBackground(URL... urls) {
for (int i = 0; i < count; i++) {
// you need to break your loop on particular condition here
if(isCancelled())
break;
}
return totalSize;
}
Declare in your class
DownloadFileAsync downloadFile = new DownloadFileAsync();
then On Create
DownloadFileAsync downloadFile = new DownloadFileAsync();
downloadFile.execute(url);
in Your Background ()
if (isCancelled())
break;
#Override
protected void onCancelled(){
}
and you can kill your AsyncTask by
downloadFile.cancel(true);
When you start a separate thread(AyncTask) it has to finish. You have to manually add a cancel statement to your code inside the AsyncTask.
A task can be cancelled at any time by invoking cancel(boolean). Invoking this method will cause subsequent calls to isCancelled() to return true. After invoking this method, onCancelled(Object), instead of onPostExecute(Object) will be invoked after doInBackground(Object[]) returns. To ensure that a task is cancelled as quickly as possible, you should always check the return value of isCancelled() periodically from doInBackground(Object[]), if possible (inside a loop for instance.)
Checkout more in the documentation: http://developer.android.com/reference/android/os/AsyncTask.html
I have been researching from the last 2 weeks and I don't get to know that how we kill the Async operation manually. Some developers use BREAK; while checking in for loop. But on my scenario I am not using the loop inside of background thread.
But I have got to know how it woks its a stupid logic but works perfectly fine.
downloadFile.cancel(true); //This code wont work in any case.
Instead of canceling and doing so much work on background thread turn off the wifi programmatically
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(false);
where do you want to kill the operation and turn on it where do you need that.
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(true);
What happens is your try block jumps in to the IOException killing the background tasks.
You better use vogella asyncTask library which have a lot of features like priority and canceling background task. And a great tutorial or using it is here
You can use this code. I am downloading a OTA file as follow:
static class FirmwareDownload extends AsyncTask<String, String, String> {
public String TAG = "Super LOG";
public String file;
int lenghtOfFile;
long total;
#Override
protected String doInBackground(String... f_url) {
try {
int count;
Utilies.getInternet();
URL url = new URL(f_url[0]);
URLConnection connection = url.openConnection();
connection.connect();
lenghtOfFile = connection.getContentLength();
mProgressBar.setMax(lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream(), 8192);
String fileName = f_url[0].substring(f_url[0].lastIndexOf("/"), f_url[0].length());
File root = Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + fileName);
Log.d(TAG, "trying to download in : " + dir);
dir.getAbsolutePath();
OutputStream output = new FileOutputStream(dir);
byte data[] = new byte[1024];
while ((count = input.read(data)) != -1) {
if (isCancelled())
break;
total += count;
mProgressBar.setProgress(Integer.parseInt("" + total));
Log.d("Downloading " + fileName + " : ", " " + (int) ((total * 100) / lenghtOfFile));
mPercentage.post(new Runnable() {
#Override
public void run() {
mPercentage.setText(total / (1024 * 1024) + " Mb / " + lenghtOfFile / (1024 * 1024) + " Mb");
}
});
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
//new InstallHelper().commandLine("mkdir data/data/ota");
File fDest = new File("/data/data/ota/" + fileName);
copyFile(dir, fDest);
FirmwareInstaller fw = new FirmwareInstaller();
fw.updateFirmware();
} catch (Exception a) {
System.out.println("Error trying donwloading firmware " + a);
new InstallHelper().commandLine("rm -r data/data/ota");
dialog.dismiss();
}
return null;
}
}
So, If you want to cancel, just use this code:
fDownload.cancel(true);
I have used with success inside an activity with TextView onclick ...
//inside the doInBackground() ...
try {
while (true) {
System.out.println(new Date());
//should be 1 * 1000 for second
Thread.sleep(5 * 1000);
if (isCancelled()) {
return null;
}
}
} catch (InterruptedException e) {
}
and in my onCreate() ...
//set Activity
final SplashActivity sPlashScreen = this;
//init my Async Task
final RetrieveFeedTask syncDo = new RetrieveFeedTask();
syncDo.execute();
//init skip link
skip_text = (TextView) findViewById(R.id.skip_text);
skip_text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//cancel Async
syncDo.cancel(true);
//goto/start another activity
Intent intent = new Intent();
intent.setClass(sPlashScreen, MainActivity.class);
startActivity(intent);
finish();
}
});
and my xml TextView element ...
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/skip_text"
android:layout_marginTop="20dp"
android:text="SKIP"
android:textColor="#color/colorAccent"/>
Related
I am working on an Android Application , Here I am working with a ProgressBar , for which I am using runOnUiThread() to make VISIBLE/GONE from doInBackground() method of AsyncTask , I did not find other places except doInBackground() suitable to make VISIBLE/GONE ProgressBar to meet the UI requirement .
In this coding scenario ProgressBar is visible but not rotating , It is rotating when I make visible ProgressBar from onCreate() method of Activity .
I am not getting why it is happening , I visited few posts on Stackoveflow , they are saying that UI thread is not able to rotate ProgressBar since it is available in processing other tasks so as a fix I am not able to find other way to make it working .
So please help me what should be the fix of this issue .
Here is the code which I am using to make VISIBLE/GONE ProgressBar .
#Override
protected String doInBackground(String... f_url) {
int count;
try {
zipfileName = f_url[1];
fUrl3 = f_url[2];
if (fUrl3.equals("DontDownloadZip")) {
return "DownloadSuccess";
} else {
Log.d("Downloading ", zipfileName);
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// Hide ProgressBar after server connection .
runOnUiThread(new Runnable() {
#Override
public void run() {
tipLayout.setVisibility(GONE);
}
});
// Code to download a file .
int lenghtOfFile = conection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream(),
8192);
OutputStream output = new FileOutputStream(MyBooks.screen
.getFilesDir().getAbsolutePath()
+ "/BookZips/"
+ f_url[1]);
byte data[] = new byte[1024];
long total = 0;
int counter = 0;
while ((count = input.read(data)) != -1) {
counter++;
total += count;
// Display ProgressBar when percentage is 99 .
if ((int) ((total * 100) / lenghtOfFile) == 99) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (!identifier1.equals("BookZips9Download"))
tipLayout.setVisibility(VISIBLE);
}
});
}
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
android.os.FileUtils.setPermissions(MyBooks.screen
.getFilesDir().getAbsolutePath()
+ "/BookZips/"
+ f_url[1], FileUtils.S_IRWXU | FileUtils.S_IRWXG
| FileUtils.S_IROTH | FileUtils.S_IWOTH
| FileUtils.S_IXOTH, -1, -1);
}
} catch (Exception e) {
e.printStackTrace();
return "DownloadFailed";
}
return "DownloadSuccess";
}
Try to add following line in your manifest file:
<activity android:name=".MainActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
>
Here, Replace ".MainActivity" to that activity where you used your async task code.
Make the progress bar visible in onPreExecute method and hide your progress bar on onPostExecute method. this should resovle your problem as such you would not need to use runOnUIThread method
Do not put your UI code on doInBackground() (doInBackground() is executed on a background thread). This will crash because you are trying to access a UI thread's object (in this case, View object) in another thread.
If you want to update your progress bar:
In doInBackground(), trigger this method
publishProgress(Integer... progress)
#Override
protected String doInBackground(String... f_url) {
// Do your background tasks
publishProgress(progress);
}
Override onProgressUpdate() method (You can safely access View objects here)
protected void onProgressUpdate(Integer... progress) {
// Updates your progress bar here
}
I am new in android and i ask a question about my thread that i create. I think it is stupid question but I am sorry.I have a onClick button listener. Its job is get the URL download link and stores in a variable.
/**
* this method invoke from setPositiveButton's dialog
*
* #param rootView
*/
private void addURLToList(View rootView) {
editTextAddURL = (EditText) rootView.findViewById(R.id.editText_add_url);
Log.i("===", "addURLToList: " + editTextAddURL.getText());
stringUrl = editTextAddURL.getText().toString();
*start GetSizeOfFile thread for getting size file and store
* in lenghtOfFile variable
*/
new GetSizeOfFile().start();
Log.i("====", "size of file after Thread: " + lenghtOfFile);
}
I create a Thread because I want to get file size.
private class GetSizeOfFile extends Thread {
#Override
public void run() {
super.run();
try {
URL url = new URL(stringUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
lenghtOfFile = connection.getContentLength();
Log.i("====", "size of file in Thread: " + lenghtOfFile);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
everything is ok but when thread is started ,after few second my lenghtOfFile variable is initialized and I got 0 in lenghtOfFile in this Line Log.i("====", "size of file after Thread: " + lenghtOfFile);
this is my logcat:
02-22 10:02:11.352 11333-11333/com.example.manifest.simplefiledownloadmanager I/===: addURLToList: http://dl2.soft98.ir/soft/a/Adobe.Shockwave.Player.12.2.7.197.IE.rar
02-22 10:02:11.352 11333-11333/com.example.manifest.simplefiledownloadmanager I/====: file name : Adobe.Shockwave.Player.12.2.7.197.IE.rar
02-22 10:02:11.352 11333-11333/com.example.manifest.simplefiledownloadmanager I/====: size of file after Thread: 0
02-22 10:02:36.544 11333-11495/com.example.manifest.simplefiledownloadmanager I/====: size of file in Thread: 13524394
I want to get file's size from thread first.is it correct that I have to sleep the thread or exit standard way?sorry I am new in android
When working with threads you cannot assume their order of execution.
What happens in your case I presume is that while your new thread is waiting on the connection to be established, the original thread is being run with the uninitialized lenghtOfFile variable so the log looks like it does. Another possibility is that the new thread didn't even begin running when the lenghtOfFile=0 line was logged. That is just how threads work.
For this exact purpose the ASyncTask class exists in Android.
Your code should be somewhat like this:
private class GetSizeOfFile extends AsyncTask<String, Void, Long> {
// runs on a background thread
protected Long doInBackground(String... stringUrls) {
String stringUrl = stringUrls[0];
try {
URL url = new URL(stringUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
long lenghtOfFile = connection.getContentLength();
return lenghtOfFile;
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
// runs on main thread
protected void onPostExecute(Long lenghtOfFile) {
if (lenghtOfFile == -1) {
// something went wrong
} else {
Log.i("====", "size of file: " + lenghtOfFile);
// whatever else you want to do
}
}
}
new GetSizeOfFile().execute(stringUrl);
I have followed some online tutorials and created this code to download the files that i have hosted in dropbox
I am using async task to do this
// AsyncTask to download a file
private class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
public DownloadTask(Context context) {
this.context = context;
}
#Override
protected String doInBackground(String... sUrl) {
// take CPU lock to prevent CPU from going off if the user
// presses the power button during download
PowerManager pm = (PowerManager) context
.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(
PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());
wl.acquire();
try {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error
// report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
return "Server returned HTTP "
+ connection.getResponseCode() + " "
+ connection.getResponseMessage();
// TODO
File file = new File(Environment
.getExternalStorageDirectory().getPath()
+ "/kathmandu.map");
if (file.exists()) {
Log.i("File Exists", "Code Gets here, file exists");
return "exists";
// if (connection.getResponseCode() ==
// HttpURLConnection.HTTP_NOT_MODIFIED) {
//
// return null;
// }
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
Log.i("Length", String.valueOf(fileLength));
// download the file
input = connection.getInputStream();
output = new FileOutputStream(Environment
.getExternalStorageDirectory().getPath()
+ "/kathmandu.map");
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled())
return null;
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
} finally {
wl.release();
}
return null;
}
I call the download code when the download options menu is clicked.
final DownloadTask downloadTask = new DownloadTask(MapActivity.this);
downloadTask
.execute("https://dl.dropboxusercontent.com/u/95497883/kathmandu-2013-8-12.map");
mProgressDialog
.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
downloadTask.cancel(true);
}
});
The code works fine but at the times the outputstream does not write full file and exits. Everything looks okay. The file is downloaded but it is corrupted.
The getContentLength() also returns -1 so i cannot check if the whole file has been downloaded using the content length. The file is a offline vector map and i need it to display offline maps. The corrupted file causes a runtime exception while trying to access it. Is there is any way to ensure that the file has been downloaded correctly.
Also i would like to provide the data with the app itself. Can i put this in the assets folder of my app. What is the best way to access the files in the assets folder during runtime.
Your assets folder is not writable as it is a part of the apk. you can of course use your application's sandbox storage (using Environment.getDir() ) or external storage (using Environment.getExternalStorageDirectory()) like you have done in your code.
I think using the DownloadManager would be a great idea to achieve exactly what you want please refer : http://developer.android.com/reference/android/app/DownloadManager.html
a short solution
DownloadManager.Request req=new DownloadManager.Request(url);
req.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI
| DownloadManager.Request.NETWORK_MOBILE)
.setTitle("Downloading")
.setDescription("Map is Being Downloaded")
.setDestinationInExternalPublicDir(Environment.getExternalStorageDirectory,
"+/maps_app/something.map");
I have an application that downloads multiple files (and checks the download speed) within an Asynctask. However, when I am connected to 3G (and there is a handover) or the device switches form WiFi to 3G, my application freezes and I can not handle this problem
#Override
protected Integer doInBackground(String... sUrl) {
try {
speed=0; //initial value
int i=0;
while ((i<sUrl.length)) {
URL url = new URL(sUrl[i]);
URLConnection connection = url.openConnection();
connection.setReadTimeout(10000);
connection.connect();
int fileLength = connection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(file);
byte data[] = new byte[1024*1024]; //1MB buffer
long total = 0;
int count;
long start = System.currentTimeMillis();
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
long finish = System.currentTimeMillis();
long tempSpeed= (fileLength *8)/(finish-start);
if (tempSpeed>speed) {
speed=tempSpeed;
}
output.flush();
output.close();
input.close(); // connection is closed
i++;
}
}catch(SocketTimeoutException e) {
exceptions.add(e);
messageProgressDialog.setCancelable(true);
AlertDialog alertDialog;
alertDialog = new AlertDialog.Builder(gui.getActivity()).create();
alertDialog.setTitle("Network problem");
alertDialog.setMessage("connection dropped");
alertDialog.show();
} catch (IOException e) {
exceptions.add(e);
messageProgressDialog.setCancelable(true);
AlertDialog alertDialog;
alertDialog = new AlertDialog.Builder(gui.getActivity()).create();
alertDialog.setTitle("IOException");
alertDialog.setMessage("IOException error");
alertDialog.show();
} catch(Exception e) {
exceptions.add(e);
AlertDialog alertDialog;
alertDialog = new AlertDialog.Builder(gui.getActivity()).create();
alertDialog.setTitle("Exception");
alertDialog.setMessage("Exception error");
alertDialog.show();
}
return 1;
}
I have read many topics on stackoverflow, however none of them could help me solve the prolem I have with my application. I have the try/catch clause, but it doesn't seem to make a difference. When I am using 3G and the phone connects to annother antenna, or there is a network problem the application freezes. What can I do ?
I have found the problem. It was this line InputStream input = new BufferedInputStream(url.openStream()); I use as inputstream the url. I replaced it with this line: InputStream input = new BufferedInputStream(connection.getInputStream()); Now it seems to work better, when it times-out, the application crashes.
}catch(SocketTimeoutException e) {
String erro=Integer.toString(count);
Log.d("error socketTimeout",erro);//1st log
exceptions.add(e);
onPostExecute(1);
Log.d("error sockteTimeout", "here"); //2nd log to see if onPostExecute worked
AlertDialog alertDialog;
alertDialog = new AlertDialog.Builder(gui.getActivity()).create();
alertDialog.setTitle("Network problem");
alertDialog.setMessage("connection dropped");
alertDialog.show();
This is the catch that I use. It seems that when I try to call the within the catch clause the onPostExecute method my application crashes.
protected void onPostExecute(Integer result) {
Log.d("onpost was called", "here");
messageProgressDialog.setMessage("Your speed is: " + speed +" KBit/sec");
messageProgressDialog.setCancelable(true);
}
Looking on the Log viewer, only the 1st Log appears. When onPostExecute is called, the app crashes. onPostExecute is never actually executed.
Any ideas?
Your problem is likely related to your handling of the return value of input.read(). If a socket is closed, input.read() may return 0 (it may also return -1 in other error situations). If it does return 0, then your loop will hang. I suggest something like:
while ((count = input.read(data)) > 0) {
That way, your loop will run while you are still making progress on the download.
I'm making an Android app where the user can download files from a FTP-server. For the ftp parts I am using apache.org.commons-net package.
When I have connected to server I get a list of the filenames, and then I want to download each file. I start the download routine which runs in a thread of it's own.
The problem I'm experiencing is, that if I have say 6 files on the server, and I run this code on my emulator, it will download the first two files, and then just freeze (with the progressbar hanging on 34 %). When I run it on my phone it will download three files and freeze.
If I debug my way through the code on the emulator it will download all six files just fine and not freeze.
Does anyone have any idea what might be the problem?
Thanks in advance,
LordJesus
This is my code (the client is already initialized):
private void downloadFiles2() {
dialog = new ProgressDialog(this);
dialog.setCancelable(true);
dialog.setMessage("Loading...");
// set the progress to be horizontal
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
// reset the bar to the default value of 0
dialog.setProgress(0);
dialog.setMax(DownloadCount);
// display the progressbar
dialog.show();
// create a thread for updating the progress bar
Thread background = new Thread (new Runnable() {
public void run() {
InputStream is = null;
try {
for (String filename : fileNames) {
is = client.retrieveFileStream(filename);
byte[] data = new byte[1024];
int x = 0;
x = is.read(data, 0, 1024);
boolean downloadIsNewer = true;
File fullPath = new File(path + "/" + filename);
Log.d("FTP", "Starting on " + filename);
if (fullPath.exists()) {
downloadIsNewer = checkIfNewer(data, fullPath);
}
if (downloadIsNewer) {
Log.d("FTP", "Need to download new file");
FileOutputStream fos = new FileOutputStream(fullPath);
fos.write(data,0,x);
while((x=is.read(data,0,1024))>=0){
fos.write(data,0,x);
}
fileText += filename + " - downloaded OK." + FileParser.newline;
is.close();
client.completePendingCommand();
fos.flush();
fos.close();
}
else {
Log.d("FTP", "No need to download");
is.close();
fileText += filename + " - own copy is newer." + FileParser.newline;
}
// active the update handler
progressHandler.sendMessage(progressHandler.obtainMessage());
}
client.logout();
client.disconnect();
}
catch (Exception e) {
// if something fails do something smart
}
}
});
// start the background thread
background.start();
}
Handler progressHandler = new Handler() {
public void handleMessage(Message msg) {
dialog.incrementProgressBy(1);
InfoTextView.setText(fileText);
if(dialog.getProgress()== dialog.getMax())
{
dialog.dismiss();
}
}
};
OK, found the problem:
When the boolean downloadIsNewer is false I do not call client.completePendingCommand(). When I add that before the line is.close() it works like a charm.