How to download multiple images and have one progressBar using AsynTask (Android) - java

I want my program to download many images (around 500) from the internet and store them in my external storage. Currently when I download a single image, it shows a progressBar and downloads the image properly. However when I am trying to replicate w/ two images, it gives the Toast for "Download complete" for both images being downloaded, however no progressBar for either image is shown and only the first image is properly downloaded.
Here is the code for my onCreate method for activity.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Remove Title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//force portrait orientation. (No landscape orientation).
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_quran);
//Instantiate ProgressDialog (Used for downloading quran pages).
myProgressDialog = new ProgressDialog(QuranActivity.this);
myProgressDialog.setMessage("Downloading Quran");
myProgressDialog.setIndeterminate(true);
myProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
myProgressDialog.setCancelable(true);
//execute when the downloader must be fired.
final DownloadTask downloadTask = new DownloadTask(QuranActivity.this);
DownloadTask second = new DownloadTask(getApplicationContext());
myHTTPURL = "https://ia601608.us.archive.org/BookReader/BookReaderImages.php?zip=/10/items/05Quran15LineWhitePageWithVioletBorderWww.Momeen.blogspot.com/05%20Quran%2015%20Line%20[White%20page%20with%20Violet%20border]%20-%20www.Momeen.blogspot.com_jp2.zip&file=05%20Quran%2015%20Line%20[White%20page%20with%20Violet%20border]%20-%20www.Momeen.blogspot.com_jp2/05%20Quran%2015%20Line%20[White%20page%20with%20Violet%20border]%20-%20www.Momeen.blogspot.com_0001.jp2&scale=1&rotate=0";
myHTTPURL2 = "https://ia601608.us.archive.org/BookReader/BookReaderImages.php?zip=/10/items/05Quran15LineWhitePageWithVioletBorderWww.Momeen.blogspot.com/05%20Quran%2015%20Line%20[White%20page%20with%20Violet%20border]%20-%20www.Momeen.blogspot.com_jp2.zip&file=05%20Quran%2015%20Line%20[White%20page%20with%20Violet%20border]%20-%20www.Momeen.blogspot.com_jp2/05%20Quran%2015%20Line%20[White%20page%20with%20Violet%20border]%20-%20www.Momeen.blogspot.com_0002.jp2&scale=1&rotate=0";
//First check if the file has already been created. (Only need to download 1ce, or
//in the case where the user deleted the files, we reinstall them again).
if (isExternalStorageWritable()) {
File makeDirectory = getQuranStorageDir(QuranActivity.this, "Quran_Pages");
for (int i = 0; i < 2; i++) {
Bundle myBundle = new Bundle();
myBundle.putInt("i", i);
if (i == 0) {
downloadTask.execute(myHTTPURL);
try {
downloadTask.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
myProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
downloadTask.cancel(true);
}
});
} else {
/*if (downloadTask.getStatus() == AsyncTask.Status.FINISHED) {
downloadTask.execute(myHTTPURL2);
} else if (downloadTask.getStatus() == AsyncTask.Status.RUNNING) {
try {
downloadTask.execute(myHTTPURL2).wait(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} */
second.execute(myHTTPURL2);
try {
second.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
// downloadTask.execute(myHTTPURL2);
}
}
}
and this is the code for my AsynTask Class.
#TargetApi(Build.VERSION_CODES.FROYO)
private class DownloadTask extends AsyncTask {
private Context context;
private PowerManager.WakeLock myWakeLock;
public DownloadTask(Context context) {
this.context = context;
}
#Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("GET");
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
//Display download percentage.
int fileLength = connection.getContentLength();
//create folder to place the downloaded file in.
// File Path:E:\Android\data\com.syedabdullah.syed.quran_memorization_application
// \files\Quran Memorization Application\Quran_Pictures
//So first create a root folder Quran Memorization Application then inside that
//folder we create another folder named Quran Pictures.
/* File rootFolder = new File(getExternalFilesDir("Quran Memorization Application"),
"Quran_Pages"); */
//Here we insert inside the Quran_Pictures folder the quran_pages.
//String myFileName = "quran_01.jpg";
Bundle y = new Bundle();
int retrievePos = y.getInt("i");
String quranFilePageName = "_" + retrievePos + ".jpg";
// String fileName = "justwork.jpg";
File sup = new File(getExternalFilesDir("Quran Memorization Application"), "Quran_Pages");
File myFile = new File(sup, quranFilePageName);
myFile.createNewFile();
//downlaod the file.
input = connection.getInputStream();
output = new FileOutputStream(myFile);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
//allow cancel with back button.
if (isCancelled()) {
input.close();
return null;
}
total += count;
//publish the progress.
if (fileLength > 0) {
publishProgress((int) (total * 100 / fileLength));
}
output.write(data, 0, count);
}
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(myFile));
QuranActivity.this.sendBroadcast(intent);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (output != null) {
output.close();
}
if (input != null) {
input.close();
}
} catch (IOException e) {
e.printStackTrace();
}
if (connection != null) {
connection.disconnect();
}
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//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);
myWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());
myWakeLock.acquire();
myProgressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
//If we get here length is known, so setIndertimante to false.
myProgressDialog.setIndeterminate(false);
myProgressDialog.setMax(100);
myProgressDialog.setProgress(progress[0]);
}
#Override
protected void onPostExecute(String result) {
myWakeLock.release();
myProgressDialog.dismiss();
if (result != null) {
Toast.makeText(context, "Download error: " + result, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Download Complete", Toast.LENGTH_SHORT).show();
}
}
} }
I was hoping to have a for loop that would create hundreds of downloadTasks and download all the images I need, and then I would call the get method. However in order for that to work, I first need too know why when I try for 2 images only the first one gets downloaded and why no progressbar shows up. Also if possible if I could get a hint as to how I can make my progressBar update for all the images and not be designed for just 1. Thanks in advance. (Note all URLs are currect.)

Thank you so much! figured out that my loops were suppose to go inside doInBackground. Also to anyone else having a similar issue. To download multiple files and display a decent progressBar, here is a very great tutorial: http://theopentutorials.com/tutorials/android/dialog/android-download-multiple-files-showing-progress-bar/

Related

Downloading list of audio from URL

So I'm implementing audio Playlist app that imports audios from Parse.com, and when I retrieve them by streaming them directly from their URls, it took maybe one minute to play after clicking play button.
So I don't want to use streaming from URL methods to play my audio from server because it makes it so slow. Instead I want to download list of audios from server (Parse.com) at once and then playing them by retrieving from sdcard.
I have the class that downloads single audio from single URL .. I want to edit the code to make it downloads more than one audio at once.
here is the class I have to download audio from URL.
class DownloadMusicfromInternet extends AsyncTask<String, String, String> {
private Context mContext;
private MediaPlayer mPlayer;
public DownloadMusicfromInternet(Context context) {
mContext = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
// Download Music File from Internet
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// Get Music file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 10 * 1024);
// Output stream to write file in SD card
OutputStream output = new
Also if you could help me in how to set a name for the audios, I don't want to write static name because I'm downloading more than one audio at a time .
FileOutputStream(Environment.getExternalStorageDirectory().getPath() + "/"+"how to put unique name for each audio here ?"+".mp3");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
// Write data to file
output.write(data, 0, count);
}
// Flush output
output.flush();
// Close streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
// While Downloading Music File
// Once Music File is downloaded
#Override
protected void onPostExecute(String file_url) {
// Play the music
playMusic();
}
// Play Music
protected void playMusic() {
// Read Mp3 file present under SD card
Uri myUri1 = Uri.parse("file:///sdcard/"+"the same unique name that was set previously ! "+".mp3");
mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mPlayer.setDataSource(mContext.getApplicationContext(), myUri1);
mPlayer.prepare();
// Start playing the Music file
mPlayer.start();
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
// Once Music is completed playing, enable the button
// btnPlayMusic.setEnabled(true);
Toast.makeText(mContext.getApplicationContext(), "Music completed playing", Toast.LENGTH_LONG).show();
}
});
} catch (IllegalArgumentException e) {
Toast.makeText(mContext.getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (SecurityException e) {
Toast.makeText(mContext.getApplicationContext(), "URI cannot be accessed, permissed needed", Toast.LENGTH_LONG).show();
} catch (IllegalStateException e) {
Toast.makeText(mContext.getApplicationContext(), "Media Player is not in correct state", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(mContext.getApplicationContext(), "IO Error occured", Toast.LENGTH_LONG).show();
}
}
}
and this is my adapter, and here is where my problem occurs and crashes my app. I don't know how to call ( DownloadMusicfromInternet ) more than once from the following adapter .
public class mAdapter extends ParseQueryAdapter<ParseObject> {
public mAdapter (Context context) {
super(context, new ParseQueryAdapter.QueryFactory<ParseObject>() {
public ParseQuery create() {
ParseQuery query = new ParseQuery("MusicPlaylist");
return query;
}
});
}
#Override
public View getItemView(final ParseObject object, View v, ViewGroup parent) {
if (v == null) {
v = View.inflate(getContext(), R.layout.list_music, null);
}
super.getItemView(object, v, parent);
//Audio retrieving
final ImageButton btn = (ImageButton) v.findViewById(R.id.play_btn);
final ParseFile fileObject = object.getParseFile("music");
**// here I put a loop because I want it to download a list of audios at once and I think here is the problem**
if (fileObject != null) {
for (int i = 10; i >= j; j++) {
new DownloadMusicfromInternet().execute(fileObject.getUrl());
}
fileObject.getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] bytes, com.parse.ParseException e) {
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
}//end on click
}//end listener
);
}//end done
});//end get data
}//end if
return v;
}//end getItem View
}//end mAdapter
Any help would be appreciated ..

Download function with overwrite

I am doing a function to download files to android device, works fine but I want to do that if the downloaded file exists already in the device will overwrite it. Here is my code:
class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
private PowerManager.WakeLock mWakeLock;
public DownloadTask(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// 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);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
getClass().getName());
mWakeLock.acquire();
mProgressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// if we get here, length is known, now set indeterminate to false
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgress(progress[0]);
}
#Override
protected void onPostExecute(String result) {
mWakeLock.release();
mProgressDialog.dismiss();
if (result != null){
this.finish();
}
else
{
Descargar.this.finish();
}
}
#Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
HttpURLConnection connection = null;
for (i=0; i< sUrl.length; i++) {
try {
URL url = new URL(sUrl[i]);
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();
fOut = openFileOutput(i+".json",MODE_PRIVATE);
//fOut = new FileOutputStream("/aste/tiempobilbao.json");
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));
fOut.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (fOut != null)
fOut.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
}
return null;
}
}
If the file exist, delete it first.
you can delete file before starting download with below code :
File myFile = new File(fileName);
if(myFile.exists())
myFile.delete();

Download a large pdf with jsoup

I would like to download a large pdf file with jsoup. I have try to change timeout and maxBodySize but the largest file I could download was about 11MB. I think if there is any way to do something like buffering. Below is my code.
public class Download extends Activity {
static public String nextPage;
static public Response file;
static public Connection.Response res;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Bundle b = new Bundle();
b = getIntent().getExtras();
nextPage = b.getString("key");
new Login().execute();
finish();
}
private class Login extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
try {
res = Jsoup.connect("http://www.eclass.teikal.gr/eclass2/")
.ignoreContentType(true).userAgent("Mozilla/5.0")
.execute();
SharedPreferences pref = getSharedPreferences(
MainActivity.PREFS_NAME, MODE_PRIVATE);
String username1 = pref.getString(MainActivity.PREF_USERNAME,
null);
String password1 = pref.getString(MainActivity.PREF_PASSWORD,
null);
file = (Response) Jsoup
.connect("http://www.eclass.teikal.gr/eclass2/")
.ignoreContentType(true).userAgent("Mozilla/5.0")
.maxBodySize(1024*1024*10*2)
.timeout(70000*10)
.cookies(res.cookies()).data("uname", username1)
.data("pass", password1).data("next", nextPage)
.data("submit", "").method(Method.POST).execute();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
String PATH = Environment.getExternalStorageDirectory()
+ "/download/";
String name = "eclassTest.pdf";
FileOutputStream out;
try {
int len = file.bodyAsBytes().length;
out = new FileOutputStream(new File(PATH + name));
out.write(file.bodyAsBytes(),0,len);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I hope somebody could help me!
I think, it's better to download any binary file via HTTPConnection:
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL("http://example.com/file.pdf");
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("/sdcard/file_name.extension");
byte data[] = new byte[4096];
int count;
while ((count = input.read(data)) != -1) {
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();
}
Jsoup is for parsing and loading HTML pages, not binary files.

Download the video before play it on android VideoView

I need to program my apps to download the video first from server and save into sdcard before playing it. Where can i get this tutorial?
Current now, I stream the video, but i don't want this way.
final VideoView videoView = (VideoView)rootView.findViewById(R.id.styleVideo);
videoView.setVideoURI(Uri.parse(videoPath));
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
videoView.setBackground(mScarfBuffer.getDrawable(position));
}
});
videoView.setMediaController(new MediaController(rootView.getContext()));
videoView.requestFocus();
videoView.start();
Use the following to download the file:
void downloadFile(){
try {
URL url = new URL(dwnload_file_path);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//connect
urlConnection.connect();
//set the path where we want to save the file
String SDCardRoot= Environment.getExternalStorageDirectory() ;
//create a new file, to save the downloaded file
File file = new File(SDCardRoot,"mydownloadmovie.mp4");
FileOutputStream fileOutput = new FileOutputStream(file);
//Stream used for reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file which we are downloading
totalSize = urlConnection.getContentLength();
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
}
//close the output stream when complete //
fileOutput.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
catch (Exception e) {
}
}
Don't forget to wrap inside an AsyncTask.
Then use MediaPlayer to play your downloaded file( now local file).
this the code download and play the video on completed
public class Testing extends AppCompatActivity {
VideoView videoView;
MediaController mediaController;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_testing);
videoView = (VideoView) findViewById(R.id.vid258);
mediaController = new MediaController(this);
// Enter Your Server Link
final DownloadTask downloadTask = new DownloadTask(Testing.this);
downloadTask.execute("http://codechair.com/video/1496139752333.mp4");
});
}
private class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
private PowerManager.WakeLock mWakeLock;
public DownloadTask(Context context) {
this.context = context;
}
#Override
protected String doInBackground(String... sUrl) {
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();
}
// 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("/sdcard/file_name.mp4");
byte data[] = new byte[4096];
Log.d("Orignalvalu1",String.valueOf(new byte[4096]));
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
Log.d("Orignalvalu1",String.valueOf(input.read(data)));
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
Log.d("Orignalvalu2",String.valueOf(total));
// 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;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// 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);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
getClass().getName());
mWakeLock.acquire();
mProgressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// if we get here, length is known, now set indeterminate to false
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgress(progress[0]);
}
#Override
protected void onPostExecute(String result) {
mWakeLock.release();
mProgressDialog.dismiss();
if (result != null)
Toast.makeText(context,"Download error: "+result, Toast.LENGTH_LONG).show();
else
Toast.makeText(context,"File downloaded", Toast.LENGTH_SHORT).show();
videoView.setVideoPath("/storage/emulated/0/file_name.mp4");
videoView.setMediaController(mediaController);
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.setLooping(true);
}
});
videoView.requestFocus();
videoView.start();
}
}

How to cancel an AsyncTask after it has been executed?

I use AsyncTask with Progress Dialog for downloading a database from a server. I want to provide user with an option of cancellation the downloading task.
My purpose is to dismiss Progress Dialog and cancel AsyncTask when user click on Cancel button on Progress Dialog.
I have applied numerous code examples but they help to dismiss Progress Dialog only and fail to stop or cancel the downloading task.
Regarding my code lines below, can you please give a little help? Many thanks.
EDITED VERSION
public class Download_gram extends Activity {
// File url to download
private static String url = "https://dl.dropbox.com/u/15034088/Anhroid_Dict/grammar.nvk.zip";
private static DownloadFile newTask;
// Progress Dialog
private ProgressDialog progressDialog;
// Progress dialog type (0 - for Horizontal progress bar)
public static final int progress_bar = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.download_gram);
newTask = new DownloadFile();
startDownload_gram = (Button) findViewById(R.id.btnProgressBar_gram);
//start download event and show progress bar
startDownload_gram.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Checi if file exists
File fgram = new File(Environment.getExternalStorageDirectory()+"/my_Folder/db/my_file/my_file.nvk");
if(fgram.exists())
{
Toast.makeText(getApplicationContext(), "File installed.", Toast.LENGTH_LONG).show();
}
else
{
//checking if the user has an internet connection
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null) {
if (!info.isConnected()) {
Toast.makeText(getApplicationContext(), "No Internet connection!", Toast.LENGTH_SHORT).show();
}
// execute async task
else
//new DownloadFile().execute(url);
newTask.execute(url);
}
else {
Toast.makeText(getApplicationContext(), "No Internet connection!", Toast.LENGTH_SHORT).show();
}
}
}});
}
//show progress dialog
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar:
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Downloading… Please wait.");
progressDialog.setIndeterminate(false);
progressDialog.setMax(100);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setCancelable(false);
progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dismissDialog(progress_bar);
newTask.cancel(true);
}
});
progressDialog.show();
return progressDialog;
default:
return null;
}
}
//backgroound downloading
class DownloadFile extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar);
}
#Override
protected String doInBackground(String... args) {
while (url != null) {
int count;
try {
URL url = new URL(args[0]);
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int fileLength = conection.getContentLength();
InputStream is = new BufferedInputStream(url.openStream(), 8192);
OutputStream os = new FileOutputStream(Environment.getExternalStorageDirectory().getPath() + "/_nvk_gram.zip");
byte data[] = new byte[1024];
long total = 0;
while ((count = is.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/fileLength));
// writing data to file
os.write(data, 0, count);
}
// flush output
os.flush();
os.close();
is.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
//Unzip the downloaded zip file
{
String destinationDirectory = Environment.getExternalStorageDirectory().getPath() + "/my_Folder/db/my_file/";
int BUFFER = 2048;
List<String> zipFiles = new ArrayList<String>();
File sourceZipFile = new File(Environment.getExternalStorageDirectory().getPath() + "/_nvk_gram.zip");
File unzipDestinationDirectory = new File(destinationDirectory);
unzipDestinationDirectory.mkdir();
ZipFile zipFile = null;
// Open Zip file for reading
try {
zipFile = new ZipFile(sourceZipFile, ZipFile.OPEN_READ);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// Create an enumeration of the entries in the zip file
Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries();
// Process each entry
while (zipFileEntries.hasMoreElements()) {
// grab a zip file entry
ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
String currentEntry = entry.getName();
File destFile = new File(unzipDestinationDirectory, currentEntry);
//destFile = new File(unzipDestinationDirectory, destFile.getName());
if (currentEntry.endsWith(".zip")) {
zipFiles.add(destFile.getAbsolutePath());
}
// grab file's parent directory structure
File destinationParent = destFile.getParentFile();
// create the parent directory structure if needed
destinationParent.mkdirs();
try {
// extract file if not a directory
if (!entry.isDirectory()) {
BufferedInputStream is =
new BufferedInputStream(zipFile.getInputStream(entry));
int currentByte;
// establish buffer for writing file
byte data[] = new byte[BUFFER];
// write the current file to disk
FileOutputStream fos = new FileOutputStream(destFile);
BufferedOutputStream dest =
new BufferedOutputStream(fos, BUFFER);
// read and write until last byte is encountered
while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, currentByte);
}
dest.flush();
dest.close();
is.close();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
try {
zipFile.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (Iterator<String> iter = zipFiles.iterator(); iter.hasNext();) {
String zipName = (String)iter.next();
doUnzip(
zipName,
destinationDirectory +
File.separatorChar +
zipName.substring(0,zipName.lastIndexOf(".zip"))
);
if(isCancelled())return (null);
}
}
}
File fav_ifo = new File(Environment.getExternalStorageDirectory()+"/my_Folder/db/my_file/my_file.nvk");
if(fav_ifo.exists())
{
try {
AssetManager am = getAssets();
String fileName = "my_file.ifo";
File destinationFile = new File(Environment.getExternalStorageDirectory()+"/my_Folder/db/my_file/" + fileName);
InputStream in = am.open("my_file.ifo");
FileOutputStream f = new FileOutputStream(destinationFile);
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
Log.d("CopyFileFromAssetsToSD", e.getMessage());
}
}
else
{
}
//Delete the downloaded zip
File folder = Environment.getExternalStorageDirectory();
String fileName = folder.getPath() + "/_nvk_gram.zip";
File myFile = new File(fileName);
if(myFile.exists())
myFile.delete();
return null;
}
private void doUnzip(String zipName, String string) {
// TODO Auto-generated method stub
}
//updating progress bar
protected void onProgressUpdate(String... progress) {
//progress percentage
progressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String file_url) {
dismissDialog(progress_bar);
//toast to notify user of download completion
Toast.makeText(getApplicationContext(), "Database successfully downloaded.", Toast.LENGTH_LONG).show();
Intent mainIntent = new Intent(Download_gram.this, my_Main_class.class);
Download_gram.this.startActivity(mainIntent);
}
}
}
see you should keep track of your DownloadFile(aSyncTask) class object.
Create a new variable in your
public class Download_gram extends Activity {
// File url to download
private static String url = "http://www.abc.123.zip";
private static DownloadFile newTask; // ADDED BY ME
// ... ...
you should save the object reference when you call
new DownloadFile().execute("Url String"); //you must be doing this
//instead you should do
newTask = new DownloadFile();
newTask.execute("Url String"); // YOUR OBJECT IS IN newTask
...
// keep track of this newTask variable
// when ever you want to cancel just call
newTask.cancel(true); // ADDED BY ME
dialog.dismiss();//In fact, I want to apply the code to stop both Progress Dialog and AsynTask here.
after setting newTask to cancel, you should check timely in doInBackground that is you task is canceled ? if yes then exit doInBackground
// YOU CAN USE THIS IN WHILE LOOP OF doInBakcground
if(isCancelled())return (null);
//This will exit doInBackground function and hence cancel task.
// you can perform other operations too in this "if" statement as per your need.
for reference of these functions
http://developer.android.com/reference/android/os/AsyncTask.html#cancel(boolean)
##################### New Version ################.
you haven't checked is the task is canceled or not. you have to check everywhere downloading is taking place in asynctask if iscancelled is true return (null); to halt asynctask and stop downloading.
you should replace following code:
while ((count = is.read(data)) != -1) { // inside doInBackground
total += count;
publishProgress(""+(int)((total*100)/fileLength));
// writing data to file
os.write(data, 0, count);
if(isCancelled())return (null); // ADDED BY ME
}
above added line is must this will check if task is canceled this doInBackground function should be over.
You should to
yourAsyncTask.cancel(true);
and, inside your class DownloadFile, you should to check for isCanceled() and do a return if true.
You can do it in this way,
progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener(){
public void onCancel(DialogInterface dialog) {
yourAysncTask.cancel(true);
}
});

Categories

Resources