Hi Today i am going to present a blog regarding the download process+async task+ custom prohress downloader.
for this purpose make a project with the name CustomProgress and have a main activity with following code
package com.jitesh.customprogress;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
public class MainActivity extends Activity {
ProgressBar progressBar2;
Button button2;
ImageView my_image;
private static String filedownload_url = "https://lh4.googleusercontent.com/-9z69eoAzRd8/UOjP_igcmtI/AAAAAAAAAsc/-yunBbz8eJI/s300/tour-Ha-Noi-Sword-Lake.jpg";
File myNewFolder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar2 = (ProgressBar) findViewById(R.id.progressBar);
button2 = (Button) findViewById(R.id.download);
my_image = (ImageView) findViewById(R.id.my_image);
}
public void button_click(View view) {
new DownloadFileFromURL().execute(filedownload_url);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
/* Background Async Task to download file */
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/* Before starting background thread. Show Progress Bar Dialog */
@SuppressWarnings("deprecation")
@Override
protected void onPreExecute() {
super.onPreExecute();
//showDialog(CUSTOM_PROGRESS_DIALOG);
progressBar2.setVisibility(View.VISIBLE);
}
/* 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/filedownload.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... value) {
// setting progress percentage
//pDialog.setProgress(Integer.parseInt(value[0]));
//pDialog.setSecondaryProgress(Integer.parseInt(value[0]) + 5);
}
/* After completing background task. Dismiss the progress dialog */
@SuppressWarnings("deprecation")
@Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
//dismissDialog(CUSTOM_PROGRESS_DIALOG);
progressBar2.setVisibility(View.GONE);
// Displaying downloaded image into image view
// Reading image path from sdcard
String imagePath = Environment.getExternalStorageDirectory().toString() + "/filedownload.jpg";
// setting downloaded into image view
my_image.setImageDrawable(Drawable.createFromPath(imagePath));
}
}
}
download the source code from link CustomProgress
for this purpose make a project with the name CustomProgress and have a main activity with following code
package com.jitesh.customprogress;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
public class MainActivity extends Activity {
ProgressBar progressBar2;
Button button2;
ImageView my_image;
private static String filedownload_url = "https://lh4.googleusercontent.com/-9z69eoAzRd8/UOjP_igcmtI/AAAAAAAAAsc/-yunBbz8eJI/s300/tour-Ha-Noi-Sword-Lake.jpg";
File myNewFolder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar2 = (ProgressBar) findViewById(R.id.progressBar);
button2 = (Button) findViewById(R.id.download);
my_image = (ImageView) findViewById(R.id.my_image);
}
public void button_click(View view) {
new DownloadFileFromURL().execute(filedownload_url);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
/* Background Async Task to download file */
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/* Before starting background thread. Show Progress Bar Dialog */
@SuppressWarnings("deprecation")
@Override
protected void onPreExecute() {
super.onPreExecute();
//showDialog(CUSTOM_PROGRESS_DIALOG);
progressBar2.setVisibility(View.VISIBLE);
}
/* 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/filedownload.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... value) {
// setting progress percentage
//pDialog.setProgress(Integer.parseInt(value[0]));
//pDialog.setSecondaryProgress(Integer.parseInt(value[0]) + 5);
}
/* After completing background task. Dismiss the progress dialog */
@SuppressWarnings("deprecation")
@Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
//dismissDialog(CUSTOM_PROGRESS_DIALOG);
progressBar2.setVisibility(View.GONE);
// Displaying downloaded image into image view
// Reading image path from sdcard
String imagePath = Environment.getExternalStorageDirectory().toString() + "/filedownload.jpg";
// setting downloaded into image view
my_image.setImageDrawable(Drawable.createFromPath(imagePath));
}
}
}
now the activity_main.xml is having the following layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/download"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:layout_marginBottom="20dp"
android:onClick="button_click"
android:text="Start download file" />
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|center_vertical" >
<ProgressBar
android:id="@+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|center_vertical"
android:layout_margin="5dip"
android:indeterminateDrawable="@drawable/my_progress_indeterminate"
android:visibility="gone" />
<ImageView
android:id="@+id/my_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|center_vertical"
/>
</RelativeLayout>
</LinearLayout>
res/drawable/my_progress_indeterminate
<?xml version="1.0" encoding="utf-8"?>
<animated-rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:drawable="@drawable/loadingicon"
android:pivotX="50%"
android:pivotY="50%" />
the manifest should have following permissions
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET" />
the used res/drawable/loadingicon is given below
the screen shot of the output is as follows
download the source code from link CustomProgress
Very helpful. Thanks :)
ReplyDelete