I am downloading pdf file in AsynchTask, so as it downloading the file, my progress dialog is getting update. However Problem is that if i press the back button than my alert box gets pop up and the downloading gets stop in background. I want that it should continue its downloading even after alert dialog gets called or pause the download once alert gets pop up and continue downloading once if i click the cancel button of alert dialog.
Here is a snippet,
#Override
protected Dialog onCreateDialog(int id)
{
switch (id)
{
case progress_bar_type:
pDialog = new ProgressDialog(this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
pDialog.show();
pDialog.setOnKeyListener(new DialogInterface.OnKeyListener()
{
#Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event)
{
if(keyCode == KeyEvent.KEYCODE_BACK)
{
running = false;
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
AlertDialog.setIcon(R.drawable.ic_launcher);
alertDialog.setTitle("Ariisto");
alertDialog.setMessage("Do you Want to Cancel the Download ?");
alertDialog.setCancelable(true);
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
// TODO Auto-generated method stub
File externalFile = new File(Environment.getExternalStorageDirectory(),"downloadedfile.pdf");
externalFile.delete();
pDialog.dismiss();
running = false;
Log.d("External File", "DELETED");
pDialog.setProgress(0);
count = 2;
}
});
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
new DownloadFileFromURL().execute(file_url);
running = true;
count = 0;
}
});
AlertDialog alert = alertDialog.create();
alert.show();
}
return false;
}
});
return pDialog;
default:
return null;
}
}
class DownloadFileFromURL extends AsyncTask<String, String, String>
{
/**
* Before starting background thread
* Show Progress Bar Dialog
* */
#SuppressWarnings("deprecation")
protected void onPreExecute()
{
super.onPreExecute();
showDialog(progress_bar_type);
publishProgress(""+(int)(0));
running = true;
}
#Override
protected void onCancelled() {
// TODO Auto-generated method stub
Log.d("------------","iNSIDE ON CANCELLED METHOD");
super.onCancelled();
}
#Override
protected String doInBackground(String... file_url)
{
// TODO Auto-generated method stub
int count;
try
{
URL url = new URL(file_url[0]);
URLConnection connection = url.openConnection();
connection.connect();
// getting file length
int lenghtOfFile = connection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream to write file
FileOutputStream output = new FileOutputStream("/sdcard/downloadedfile.pdf");
byte data[] = new byte[1024];
long total = 0;
while ( ((count = input.read(data)) != -1) && (running == true) )
{
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);
}
output.flush();
// closing streams
output.close();
input.close();
}
catch (Exception e)
{
Log.e("Error: ", " "+e.getMessage());
}
return null;
}
protected void onProgressUpdate(String... progress)
{
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
#SuppressWarnings("deprecation")
protected void onPostExecute(String file_url)
{
// dismiss the dialog after the file was downloaded
if(running == true){
dismissDialog(progress_bar_type);
// Displaying downloaded image into image view
// Reading image path from sdcard
String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.pdf";
// setting downloaded into image view
Log.d(imagePath, "show file");
File file = new File(Environment.getExternalStorageDirectory(),"downloadedfile.pdf");
Uri external = Uri.fromFile(file);
viewPdf(external);
}
}
}
I have a requirement very similar to this. A user will click on a listItem and an AsyncTask will start downloading it, and then displays it when done. Should the user tap the back-button before the download is complete, an alert dialog is displayed asking whether to abort the download. Should the download complete WHILE that dialog is displayed, it simply dismisses the dialog and finishes that activity. I don't have time to pull and sanitize the code, but the pattern is as follows:
The activity has two private fields:
private DownloadTask downloader = null;
private AlertDialog dlgCancel = null;
in onBackPressed:
if( downloader != null ) {
dlgCancel =....
dlgCancel.show();
} else
finish();
in the DownloadTask's onPostExecute:
if( isCancelled() ) {
... dismiss the download
} else {
if( dlgCancel == null ) {
... handle the download here ...
} else {
dlgCancel.dismiss();
dlgCancel = null;
Activity.finish();
}
}
and finally, in the onClick for the Abort-Download button:
downloader.cancel( true );
Activity.finish();
Note that you'll need to watch for isCancelled() in your AsyncTask's doInBackground() so that you can react as quickly as possible. Some operations won't return immediately.
Related
I'm Developing an android application to download .mp3 from Server.
When clicked on the download button ProgressBar will appear,displaying the
percentage on screen.
This works fine. Now i want to make that download work in background by Showing Notification with a ProgressBar
can anyone help me to find a code to Use the Service and Building Notification?Thank You
My MainActivity.java code:
public class MainActivity extends Activity {
final MediaPlayer mp=new MediaPlayer();
//---------------------
Clone c=new Clone();
//------------------
// button to show progress dialog
Button btnShowProgress;
// Progress Dialog
private ProgressDialog pDialog;
ImageView my_image;
// Progress dialog type (0 - for Horizontal progress bar)
public static final int progress_bar_type = 0;
// File url to download
private static String file_url = "http://www.eecindia.co.in/up/01%20-%20Pretham%20-%20Oruthikku%20Pinnil%20[Maango.me].mp3";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// show progress bar button
btnShowProgress = (Button) findViewById(R.id.btnProgressBar);
// Image view to show image after downloading
my_image = (ImageView) findViewById(R.id.my_image);
/**
* Show Progress bar click event
* */
btnShowProgress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//----------------------------------------------
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Select The Extension To Download...");
builder.setItems(new CharSequence[]
{".mp3", ".mp4", ".txt", ".srt"},
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
switch (which) {
case 0:
/////////////////////////////////////////////////////////////////
File folder = new File(Environment.getExternalStorageDirectory().getPath() + "/Jithin's/");
if (!folder.exists()) {
try {
folder.mkdirs();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Default Save Path Creation Error:" + folder);
}
}
c.setA(Environment.getExternalStorageDirectory().toString() + "/Jithin's/downloadedfile.mp3");
// starting new Async Task
new DownloadFileFromURL().execute(file_url);
/////////////////////////////////////////////////////////////
break;
case 1:
////////////////////////////////////////////////////////////
File folde = new File(Environment.getExternalStorageDirectory().getPath() + "/Jithin's/");
if (!folde.exists()) {
try {
folde.mkdirs();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Default Save Path Creation Error:" + folde);
}
}
c.setA(Environment.getExternalStorageDirectory().toString() + "/Jithin's/downloadedfile.mp4");
// starting new Async Task
new DownloadFileFromURL().execute(file_url);
////////////////////////////////////////////////
break;
case 2:
File fold = new File(Environment.getExternalStorageDirectory().getPath() + "/Jithin's/");
if (!fold.exists()) {
try {
fold.mkdirs();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Default Save Path Creation Error:" + fold);
}
}
c.setA(Environment.getExternalStorageDirectory().toString() + "/Jithin's/downloadedfile.txt");
// starting new Async Task
new DownloadFileFromURL().execute(file_url);
break;
case 3:
File fol = new File(Environment.getExternalStorageDirectory().getPath() + "/Jithin's/");
if (!fol.exists()) {
try {
fol.mkdirs();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Default Save Path Creation Error:" + fol);
}
}
c.setA(Environment.getExternalStorageDirectory().toString() + "/Jithin's/downloadedfile.srt");
// starting new Async Task
new DownloadFileFromURL().execute(file_url);
break;
}
}
});
builder.create().show();
/////-------------------------------------
}
});
}
/**
* Showing Dialog
* */
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type:
pDialog = new ProgressDialog(this);
pDialog.setMessage("Downloading File. Please Wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(false);
pDialog.show();
return pDialog;
default:
return null;
}
}
/**
* Background Async Task to download file
* */
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Before starting background thread
* Show Progress Bar Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
/**
* Downloading file in background thread
*/
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
// 6yi7 conection.connect();
conection.setRequestProperty("Accept-Encoding", "identity");
// 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(c.getA());
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();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
/**
* Updating progress bar
*/
protected void onProgressUpdate(String... progress) {
// setting progress percentage
try {
pDialog.setProgress(Integer.parseInt(progress[0]));
} catch (Exception d) {
Log.d("Error .. ", d.getMessage());
}
}
/**
* 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);
Toast.makeText(MainActivity.this, "Downloaded Succesfully.. check Jithin's folder 2 see file...", Toast.LENGTH_LONG).show();
//my_image.setImageDrawable(Drawable.createFromPath(imagePath));
}
}
//---------------------------------
protected void onStop(){
super.onStop();
Intent intent = new Intent(MainActivity.this,MyService.class);
startService(intent);
}
}
You can use foreground Notification.Here is your Example
project demonstrating the use of startForeground().
i am download some data from URL. and i want to display the number of bytes and the % of bytes download together in the progress dialog.
now i can only show the % of bytes downloads.
here is my code
public class MainActivity extends ActionBarActivity {
// button to show progress dialog
Button btnShowProgress;
// Progress Dialog
private ProgressDialog pDialog;
private ImageView my_image;
// Progress dialog type (0 - for Horizontal progress bar)
public static final int progress_bar_type = 0;
// File url to download
private static String file_url = "http://ibuildmartdev.agicent.com/data/projs/3/11_01.pdf?5";
DownloadFileFromURL df;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setContentView(R.layout.activity_main);
// show progress bar button
btnShowProgress = (Button) findViewById(R.id.btnProgressBar);
// Image view to show image after downloading
my_image = (ImageView) findViewById(R.id.my_image);
/**
* Show Progress bar click event
* */
btnShowProgress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// starting new Async Task
df =new DownloadFileFromURL();
df.execute(file_url);
}
});
}
/**
* Background Async Task to download file
* */
class DownloadFileFromURL extends AsyncTask<String, String, String> implements OnKeyListener {
/**
* Before starting background thread Show Progress Bar Dialog
* */
#SuppressWarnings("deprecation")
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(500);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
pDialog.show();
pDialog.setOnKeyListener(this);
}
/**
* Downloading file in background thread
* */
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
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(
"/sdcard/downloadedfile.jpg");
byte data[] = new byte[2048];
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();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(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
pDialog.dismiss();
// Displaying downloaded image into image view
// Reading image path from sdcard
/*String imagePath = Environment.getExternalStorageDirectory()
.toString() + "/downloadedfile.jpg";
// setting downloaded into image view
my_image.setImageDrawable(Drawable.createFromPath(imagePath));*/
}
#Override
protected void onCancelled() {
Log.i("main Activity", "Asyn task Cancled");
super.onCancelled();
}
#Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
df.cancel(false);
pDialog.dismiss();
Log.i("main Activity", "true");
return true;
}
return false;![enter image description here][1]
}
}
this code only show the download progress in %. but i want to show the download progress in % as well as total no of bytes download.
You can do this :
publishProgress("" + (int) ((total * 100) / lenghtOfFile)+ "lengthOfFile="+lengthOfFile); //You can use as a thing to split variable.Here, i used the name "lengthOfFile=" and i will get this through publish progress and split it there
#Override
protected void onProgressUpdate(String... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
String str[]=values[0].split("lengthOfFile=");
String percent=str[0];
String bytes=str[1];
}
I am developing an app that downloads files and show 2 progress bars, the first one for the current downloading file, and the 2nd one for total progress based on the number of files.
I am using the DoubleProgressBar library in my app:
I succeeded to update the first ProgressBar, but stuck with the 2nd one.
Here is my code for the AsyncTask class:
private DoubleProgressDialog pDialog;
class DownloadFileFromURL extends AsyncTask<String, Integer, String> {
Context mContext;
public DownloadFileFromURL(Context ctx) {
// TODO Auto-generated constructor stub
this.mContext = ctx;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(CUSTOM_PROGRESS_DIALOG);
}
/* Downloading file in background thread */
#Override
protected String doInBackground(String... f_url) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(f_url[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// getting file length
int fileLength = connection.getContentLength();
for (int i = 0; i <= ArrayOfFiles.length; i++){
File f = new File(Environment.getExternalStorageDirectory() + "/Folder/", ArrayOfFiles[i]);
// input stream to read file - with 8k buffer
input = new BufferedInputStream(url.openStream(), 8192);
// Output stream to write file
output = new FileOutputStream(f);
byte data[] = new byte[8192];
long total = 0;
int count;
int EntireProgress = 0;
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);
/*Here is my trouble, the 2nd ProgressBar is updating as the same of the first one, I need the 2nd one to update itself slowly till all files get downloaded*/
int CurrentProgress = pDialog.getProgress();
pDialog.setSecondaryProgress(CurrentProgress );
publishProgress(CurrentProgress );
}
} 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 onPostExecute(String result) {
// dismiss the dialog after the file was downloaded
dismissDialog(CUSTOM_PROGRESS_DIALOG);
if (result != null)
Toast.makeText(mContext,"Download error: " + result, Toast.LENGTH_LONG).show();
else
Toast.makeText(mContext,"File downloaded", Toast.LENGTH_SHORT).show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// if we get here, length is known, now set indeterminate to false
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgress(progress[0]);
}
}
I also used this method in my activity class:
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case CUSTOM_PROGRESS_DIALOG:
pDialog = new DoubleProgressDialog(NetworkActivity.this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setMax(100);
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.setButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
pDialog.show();
return pDialog;
default:
return null;
}
}
Any idea?
First part is to move pDialog.setSecondaryProgress to the onProgressUpdate(Integer... progress) method.
You are also resetting the secondary progress in each download task by setting it to CurrentProgress which is set to pDialog.getProgress();. Hence the second progress will always be reset after the download is finished.
Edit:
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int)(total * 100 / fileLength), pDialog.getSecondaryProgress());
(...)
int CurrentProgress = pDialog.getProgress();
// do not update secondary progress here
// pDialog.setSecondaryProgress(CurrentProgress );
int secondaryProgress = (CurrentProgress + 100 * i)/ArrayOfFiles.length;
publishProgress(CurrentProgress, secondaryProgress);
And the onProgressUpdate
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
(...)
pDialog.setProgress(progress[0]);
pDialog.setSecondaryProgress(progress[1]);
}
If you are not setting your DownloadFileFromUrl outside your main class I would suggest something like this
int CurrentProgress = pDialog.getProgress();
int secondaryProgress = (CurrentProgress + 100 * id_treated_file)/number_of_files;
// id_treated_file - 0, 1, 2, ... , number_of_files - 1
pDialog.setSecondaryProgress(CurrentProgress);
// secondaryProgress will be progress[1] in your onProgressUpdate method
publishProgress(CurrentProgress, secondaryProgress);
your onProgressUpdate method should look like this :
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// if we get here, length is known, now set indeterminate to false
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgress(progress[0]);
pDialog.setSecondaryProgress(progress[1]);
}
EDIT
or you can try
pDialog.setSecondaryProgress((progress[0] + 100 * id_treated_file)/number_of_files);
I am working on Android app.
I need to show a progress dialog box when I click on button.
In that button I am converting video file to .zip file and calculating that file size.
In this process I need to show a ProgressDialog, but it is not showing.
Screen get struck while calculating and after calculation it shows ProgressDialog and then screen navigating to the next screen.
My Code:
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaCheck.this.runOnUiThread(new Runnable() {
public void run() {
pd = ProgressDialog.show(MediaCheck.this, "",
"Checking the video compatability. Please wait", true);
}
});
video_Path= makeZip(video_Path);
if (video_Path.equalsIgnoreCase("File size is too large")) {
pd.dismiss();
Toast.makeText(getApplicationContext(),
"Large video", Toast.LENGTH_LONG)
.show();
return;
}
pd.dismiss();
// Doing screen navigation here.
}
});
Code to make a zip and know the size
private static String makeZip(String videoPath) {
byte[] buffer = new byte[1024];
String[] videoFileName = videoPath.split("/");
File directory = null;
try {
ContextWrapper cw = new ContextWrapper(context_this);
// path to /data/data/yourapp/app_data/imageDir
directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
FileOutputStream fos = new FileOutputStream(directory
+ "/IRCMS_Video.zip");
ZipOutputStream zos = new ZipOutputStream(fos);
ZipEntry ze = null;
ze = new ZipEntry(videoFileName[5]);
zos.putNextEntry(ze);
FileInputStream in = new FileInputStream(videoPath);
int len;
while ((len = in.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
File videoZip = new File(directory + "/IRCMS_Video.zip");
videoLength = videoZip.length() / (1024 * 1024);
if (videoLength > 3)
return "File size is too large";
in.close();
zos.closeEntry();
// remember close it
zos.close();
System.out.println("Done");
} catch (IOException ex) {
ex.printStackTrace();
}
return directory.toString() + "/IRCMS_Video.zip";
}
}
Please help...
then you should try ASYNCTASK to easily perform your operation and reduce the complexity of using threads
private class Converter extends AsyncTask<String, Void, Void> { //Converter is class name
protected String doInBackground(String... urls) {
//THIS METHOD WILL BE CALLED AFTER ONPREEXECUTE
//YOUR NETWORK OPERATION HERE
return null;
}
protected void onPreExecute() {
super.onPreExecute();
//THIS METHOD WILL BE CALLED FIRST
//DO OPERATION LIKE SHOWING PROGRESS DIALOG PRIOR TO BEGIN NETWORK OPERATION
}
protected void onPostExecute(String result) {
super.onPostExecute();
//TNIS METHOD WILL BE CALLED AT LAST AFTER DOINBACKGROUND
//DO OPERATION LIKE UPDATING UI HERE
}
}
You are doing calculation on UI thread therfore it hangs your app. Do calculation on background thread. You can resolve this by-
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pd = ProgressDialog.show(MediaCheck.this, "",
"Checking the video compatability. Please wait", true);
Thread background = new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
video_Path= makeZip(video_Path);
MediaCheck.this.runOnUiThread(new Runnable()
{
public void run()
{
if (video_Path.equalsIgnoreCase("File size is too large")) {
pd.dismiss();
Toast.makeText(getApplicationContext(),
"Large video", Toast.LENGTH_LONG)
.show();
pd.dismiss();
return;
}
}
});
}
});
background.start();
// Doing screen navigation here.
}
});
I am trying to download a image file on the internet by android and I use this code:
public class AndroidDownloadFileByProgressBarActivity extends Activity {
// button to show progress dialog
Button btnShowProgress;
// Progress Dialog
private ProgressDialog pDialog;
ImageView my_image;
// Progress dialog type (0 - for Horizontal progress bar)
public static final int progress_bar_type = 0;
// File url to download
private static String file_url = "http://api.androidhive.info/progressdialog/hive.jpg";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// show progress bar button
btnShowProgress = (Button) findViewById(R.id.btnProgressBar);
// Image view to show image after downloading
my_image = (ImageView) findViewById(R.id.my_image);
/**
* Show Progress bar click event
* */
btnShowProgress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// starting new Async Task
new DownloadFileFromURL().execute(file_url);
}
});
}
/**
* Showing Dialog
* */
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type:
pDialog = new ProgressDialog(this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
pDialog.show();
return pDialog;
default:
return null;
}
}
/**
* Background Async Task to download file
* */
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Before starting background thread
* Show Progress Bar Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
/**
* Downloading file in background thread
* */
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
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("/sdcard/downloadedfile.jpg");
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();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(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);
// Displaying downloaded image into image view
// Reading image path from sdcard
String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.jpg";
// setting downloaded into image view
my_image.setImageDrawable(Drawable.createFromPath(imagePath));
}
}
}
but in LogCat i have an error. it show that: /sdcard/downloadedfile.jpg (Permission denied).
I am using android 3.1, and I don't know how to solve it, please help me!
thank so much.
Add WRITE_EXTERNAL_STORAGE permission to the manifest file.