What I want to do now is loop download pdf from URL that has about 875 Files.
I have already done this by using Asynctask and update the progress in progress dialog also everything is working fine, but what I had a problem is when the user clicks on my DOWNLOAD IN BACKGROUND button, the download is still going on and then I want to re-open the activity again. but the progress and name of the file that displays to the user is not showing anymore.
I know that when we start new activity it will ignore the background running process of our last Asynctask, so how could we solve this problem? (sorry for my English, it's my first time through on StackOverflow)
my code is similar to this
Here sample of my code:
class DownloadFileFromURL extends AsyncTask<ArrayList<LawDocument>,Integer, String> {
private boolean running = true;
Exception error;
#Override
protected void onPreExecute() {
super.onPreExecute();
if(haveNetworkConnection()){
showDialog(progress_bar_type);
}else {
running = false;
showdailog();
}
}
#Override
protected void onCancelled() {
super.onCancelled();
running = false;
}
#Override
protected String doInBackground(ArrayList<LawDocument>[] f_url) {
ArrayList<LawDocument> passed = f_url[0]; //get passed arraylist
System.out.println("Data::" + passed.size());
int count;
InputStream input = null;
OutputStream output = null;
while(!isCancelled()) {
try {
for (int i = 0; i < passed.size(); i++) {
File file = getBaseContext().getFileStreamPath(passed.get(i).getActualFilename());
if (file.exists()){
countfile+=1;
pDialog.setMessage(" Exist / "+ConstantClass.filecount);
}else{
Log.d("checkFilecount" + i, "fileName: " + passed.get(i).getFileName());
String filename = passed.get(i).getFileName().substring(passed.get(i).getFileName().lastIndexOf("/") + 1);
Log.d("checkFile", "name: " + filename);
URL url = new URL(passed.get(i).getFileName());
System.out.println("Data::" + passed.get(i).getFileName());
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
input = new BufferedInputStream(url.openStream(), 8192);
//input = new BufferedInputStream(url.openStream(), 20000);
System.out.println("Data::" + passed.get(i).getFileName());
System.out.println("Data::" + filename);
// Output stream to write file
output = new FileOutputStream(getApplicationContext().getFilesDir() + "/" + filename);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress((int) ((total * 100) / lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
countfile+=1;
runOnUiThread(new Runnable() {
#Override
public void run() {
pDialog.setMessage(countfile+" / "+ConstantClass.filecount);
}
});
}
}
} catch (Throwable t) {
Log.e("AsyncTask", "OMGCrash", t);
// maybe throw it again
Toast.makeText(DownloadLoading.this,"There is a problem",Toast.LENGTH_SHORT).show();
throw new RuntimeException(t);
} finally {
if (output != null) {
try {
output.flush();
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return null;
}
/**
* Updating progress bar
*/
protected void onProgressUpdate(Integer... progress) {
// setting progress percentage
pDialog.setProgress(progress[0]);
}
/**
* After completing background task Dismiss the progress dialog
**/
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
//dismissDialog(progress_bar_type);
if (error !=null){
Toast.makeText(DownloadLoading.this, error.getMessage(),
Toast.LENGTH_SHORT).show();
}else if(!running){
Log.d("Faild","Download fail connection");
}else{
Toast.makeText(DownloadLoading.this, "Success", Toast.LENGTH_SHORT).show();
}
}
}
}
}
I guess the Best solution to you is using Service with BroadCast
which Mean but all your download In Service
lets say
public class DowloadService extends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Bundle extras = intent.getExtras();
your_data = extras.get() // just example
for (int i = 0; i < passed.size(); i++) {
File file = getBaseContext().getFileStreamPath(passed.get(i).getActualFilename());
if (file.exists()){
countfile+=1;
pDialog.setMessage(" Exist / "+ConstantClass.filecount);
}else{
Log.d("checkFilecount" + i, "fileName: " + passed.get(i).getFileName());
String filename = passed.get(i).getFileName().substring(passed.get(i).getFileName().lastIndexOf("/") + 1);
Log.d("checkFile", "name: " + filename);
URL url = new URL(passed.get(i).getFileName());
System.out.println("Data::" + passed.get(i).getFileName());
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
input = new BufferedInputStream(url.openStream(), 8192);
//input = new BufferedInputStream(url.openStream(), 20000);
System.out.println("Data::" + passed.get(i).getFileName());
System.out.println("Data::" + filename);
// Output stream to write file
output = new FileOutputStream(getApplicationContext().getFilesDir() + "/" + filename);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress((int) ((total * 100) / lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
countfile+=1;
// send broadcast with data you want
ntent.putExtra("dataType",dataType);
intent.putExtra("getAccuracy",gpsSignal);
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
}
});
return START_NOT_STICKY;
}
}
and then in your activiy Setup Local BroadCast To get Data send
private class BroadCastLocal extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent) {
if (Constrains.PEDOMETERBROADCAST.equalsIgnoreCase(intent.getAction()))
{
int dataType = intent.getIntExtra("dataType",-1);
}
}
Now whenever the user start/end your activity .. the process will not be effected
Related
In following code, When Download completed and User click on notification then it directly goes to File Manager and open "My Application" Folder
In Folder Image files, PDF as well as excel,word or zip file is there.
Folder path is : /storage/emulated/0/My Application
My Code is :
ProgressDialog pDialog;
public static final int progress_bar_type = 0;
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Bar Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
build.setProgress(100, 0, false);
mNotifyManager.notify(ID, build.build());
pDialog = new ProgressDialog(activity);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Downloading file in background thread
* */
#Override
protected String doInBackground(String... f_url) {
int count;
try {
String NoticeUrl = "http://" + DOMAIN +"//NoticeBoard/";
System.out.println("============ Notice : =============" + NoticeUrl);
Log.d("file name exec", f_url[0] + "");
URL url = new URL( NoticeUrl
+ Uri.encode(f_url[0].trim()));
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);
direct = new File(Environment.getExternalStorageDirectory()+"/My Application");
if(!direct.exists()) {
if(direct.mkdir()); //directory is created;
}
// Output stream to write file
OutputStream output = new FileOutputStream(
direct + "/" + f_url[0].trim());
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
// Displaying downloaded image into image view
// Reading image path from sdcard
FilePath = direct + "/" + f_url[0].trim();
// setting downloaded into image view
//my_image.setImageDrawable(Drawable.createFromPath(imagePath));
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
int i;
for (i = 0; i <= 100; i += 5) {
// Sets the progress indicator completion percentage
publishProgress(String.valueOf(Math.min(i, 100)));
try {
// Sleep for 5 seconds
Thread.sleep(2 * 1000);
} catch (InterruptedException e) {
Log.d("Failure", "sleeping failure");
}
}
return null;
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
build.setProgress(100, Integer.parseInt(progress[0]), false);
mNotifyManager.notify(ID, build.build());
super.onProgressUpdate(progress);
}
/**
* After completing background task Dismiss the progress dialog
* **/
#Override
protected void onPostExecute(String f_url) {
// dismiss the dialog after the file was downloaded
pDialog.dismiss();
Toast.makeText(activity, "File Downloaded at : - " + FilePath , 4600).show();
System.out.println("==================" + FilePath);
Toast.makeText(activity, "Download Completed", 200).show();
// build.setSmallIcon(android.R.drawable.ic_dialog_alert);
/*File file = new File(FilePath);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "");
PendingIntent pendingIntent = PendingIntent.getActivity(activity.getApplication(), 0, intent, 0);
build.setContentIntent(pendingIntent);
build.setLargeIcon(BitmapFactory.decodeResource(activity.getResources(), R.drawable.ic_launcher));*/
build.setContentText("Download complete");
build.setProgress(0, 0, false);
mNotifyManager.notify(ID, build.build());
//Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//Uri uri = Uri.parse(FilePath); // a directory
//intent.setDataAndType(uri, "*/*");
//activity.startActivity(Intent.createChooser(intent, "Open folder"));
}
}
First of all you need to set an Activity which will be opened on the notification click and then you need a ListView to show the desired files in your ListView.
the following code may help you. It helps you to view the files in listview and
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
myList = new ArrayList<String>();
String root_sd = Environment.getExternalStorageDirectory().toString();
file = new File( root_sd + "/external_sd" ) ;
File list[] = file.listFiles();
for( int i=0; i< list.length; i++)
{
myList.add( list[i].getName() );
}
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, myList ));
}
implement onClick method as per your implementation of what you want to do.
i hope it helps.
Hi I need to show summary progress of AsyncTask. I want to show ProgressBar or ProgressDialog of Downloading, but I have know idea what to do, I know how to show dialog, but only when I download one file, and how do when I have a lot of files to download. Can somebody help????
Here is My AyncTaskClass
public class DownloadProgramTask extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
String path = sUrl[1];
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();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
output = new FileOutputStream(path);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
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();
}
return null;
}
}
And I create new instance of that class for every execute,
File voiceFile = new File(dirVoice, a.getPose_id() + ".mp3");
if (!voiceFile.exists()) {
voiceList.add(a.getVoice());
new DownloadProgramTask().execute(MYurl.BASE_URL + a.getVoice(), voiceFile.getPath());
Log.e("LINK", MYurl.BASE_URL + a.getVoice());
Log.e("Path voice", "" + voiceFile.getPath());
}
File imgLargeFile = new File(dirImageLarge, a.getId() + ".png");
if (!imgLargeFile.exists()) {
imgLargeList.add(a.getVoice());
new DownloadProgramTask().execute(MYurl.BASE_URL + "/" + a.getImgLarge(), imgLargeFile.getPath());
}
you can use the overridden method OnProgressUpdate of Async Task. call publishProgress in doingBackground of asynctask with interger
something like this..
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
Log.i("makemachine", "onProgressUpdate(): " +
percentBar.setProgress((values[0] * 2) + "%");
}
I have a list view. When user selects an item of my list view, I open DetailActivity that user can download a file in that activity and I show the user download percentage using ProgressWheel.
My problem is when user closes the activity and then returns back to activity, the ProgressWheel doesn't update anymore.
Here is my code:(I download the file using AsynchTask)
/**
* Background Async Task to download file
* */
class DownloadTask extends AsyncTask<String, String, Boolean> {
/**
* Downloading file in background thread
* */
#Override
protected Boolean doInBackground(String... params) {
try {
URL url = null;
try {
String link = params[0];
fileExtention = getFileExtention(link);
url = new URL(link);
} catch (Exception e) {
e.printStackTrace();
return false;
}
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
// set some parameters for httpUrlConnection
connection.setConnectTimeout(JSONConstants.CONNECTION_TIMEOUT);
connection.setReadTimeout(JSONConstants.READ_TIMEOUT);
connection.connect(); // Connection Complete here.!
// Get from Server and Catch In Input Stream Object.
InputStream inputStream = connection.getInputStream();
int lenghtOfFile = connection.getContentLength();
String PATH = Environment.getExternalStorageDirectory()
+ "/download/";
File file = new File(PATH);
if (!file.exists()) {
file.mkdirs();
}
File outputFile = new File(file, "fileTitle"
+ ".mp3" );
FileOutputStream fileOutputStream = new FileOutputStream(
outputFile);
byte[] buffer = new byte[4096];
int length = 0;
long total = 0;
while ((length = inputStream.read(buffer)) != -1) {
total += length;
// publishing the progress....
// After this onProgressUpdate will be called
if (lenghtOfFile > 0)
publishProgress(""
+ (int) ((total * 100) / lenghtOfFile));
// Write In FileOutputStream.
fileOutputStream.write(buffer, 0, length);
}
fileOutputStream.flush();
fileOutputStream.close();
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
private void publishProgress(String percent) {
// Sets the progress indicator to a max value, the
// current completion percentage, and "determinate"
// state
downloadProgressWheel.setProgress(Integer.valueOf(percent));
}
How can I set my ProgressWheel still updated when user returns back to it's associated activity.
I have one problem in url like"http://sample.com/test" that have large amout of xml data i am not able to show progress bar in mainUI.
Please do needful.
In AsyncTask ,background task save the xml in local memory.
int count;
try {
URL url = new URL("http://sample.com/test");
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);
// Output stream to write file
OutputStream output = new FileOutputStream("/data/data/com.pc.demo/temp.xml");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
int progress = (int)((total*100)/lenghtOfFile) ;
System.out.println("update---"+progress);
publishProgress(progress);
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
onPostExecute
File yourFile = new File("/data/data/com.pc.demo/temp.xml");
InputStream input = new BufferedInputStream(new FileInputStream(yourFile), 8086);
onProgressUpdate
setProgressPercent(progress[0])
you can override the onProgressUpdate() function of your AsyncTask, and use the publishProgress(Progress... values) in the doInBackgroud() to push your saving status to the progress then update it, here is my simple code, wish can help you.
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]); //change this with your progress bar
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
I need to get the time of download when I launch my android application. So, I added 2 Log and System.currentTimeMillis(). But, I can’t find the exact location to put these tools.
To get the start time, I added this :
period=System.currentTimeMillis();
System.out.println("Début téléchargement : "+System.currentTimeMillis());
To ser the end time, I added this :
System.out.println("Fin téléchargement : "+System.currentTimeMillis());
period=(System.currentTimeMillis()-period);
System.out.println("La durée de téléchargement : "+period+"ms");
And this is all the code to download file :
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... aurl) {
int count;
try {
File vSDCard = null;
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
vSDCard = Environment.getExternalStorageDirectory();
File vFile = new File(vSDCard.getParent() + "/" + vSDCard.getName() + "/"
+ "image.jpg");
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
conexion.connect();
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(vFile);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
}
} catch (Exception e) {
Log.d("ImageManager", "Error: " + e);
}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC", progress[0]);
ProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
I need your suggestion please.
First block before open URL connection or just before you start reding from input stream.
Second block after close of connection or just after the loop.
What's so difficult about it? Am I missing something ?