Hello, Jumpa lagi dengan saya 😀
nah, di artikel saya ini saya ingin membuat Download file dengan android yang menggunakan Progress Dialog atau Progress Bar.
Progress bar adalah salah satu komponen yg bersifat grafis yang fungsinya biasanya menampilkan proses tertentu, seperti proses download file, copy file, ataupun mengindikasikan proses lainnya.
sudah aga ngurdeng? :D… seperti ini gambaran umumnya

progress bar

Di artikel ini saya menggunakan webserver untuk mendownload file, file yang saya gunakan adalah file gambar. Selain untuk mendownload file dari webserver kita juga bisa membatalkan gambar yang ingin kita download haha :D.
ya mungkin teman-teman pembaca sudah mulai tidak sabar lagi ya.

pertama install dulu webserver teman-teman, mau xampp, apache2triad, atau wampp terserah saja asalkan bisa di run. kemudian jangan lupa buat folder baru bernama “android” di dalam folder htdocs nya :).
kemudian letakkan file gambar terserah anda di dalam folder “android” tadi.

ayo langsung ke TKP 😀

Berikut langkah-langkahnya :

1. Buat New Project dari File>New>Android Application dengan ketentuan berikut:

  • Project Name : testDownloadProgress
  • Build Target : Android2.3
  • Application name : testDownload
  • Package name : progress.com
  • Activity : Progress
  • MinSDK : 9
  • Click Finish

2. Setelah project tercreate maka secara otomatis membentuk 3 file yaitu:

  • main.xml
  • string.xml
  • Progress.java

3. Edit main.xml ketikkan kode berikut ini

[java]
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android= "http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<Button android:id="@ id/btnProgressBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Download File dengan Progress Bar"
android:layout_marginTop="50dip"/>

<!– Image view to show image after downloading –>
<ImageView android:id="@ id/my_image"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>

</LinearLayout>
[/java]

4. Edit file Progress.java copykan file dibawah package progress.com;
[java]
package progress.com;
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class Progress extends Activity {
// button to show progress dialog
Button btnShowProgress;

// Progress Dialog
private DownloadFileFromURL download = new DownloadFileFromURL();
private ProgressDialog pDialog;
ImageView my_image;
// Progress dialog type (0 – for Horizontal progress bar)
public static final int progress_bar_type = 0;

boolean a;
// File url to download
private static String file_url = "http://10.0.2.2/android/test.jpg";

InputStream input;

// Output stream to write file
OutputStream output;

<a href="http://www.nbso.ca/">mobile casino</a> @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
<a href="http://www.lockervecasino.com">lockervecasino</a> 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("Sedang mengunduh. Tunggu Sebentar…");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);

pDialog.setButton("batal", new CancelOnClickListener());

pDialog.show();
return pDialog;
default:
return null;
}
}

private final class CancelOnClickListener implements DialogInterface.OnClickListener{

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
//Progress.this.finish();
dismissDialog(progress_bar_type);
download.cancel(true);
download.oncancel(true);

}

}

/**
* In this example, the index is zero, which means that the first column of the <a href="http://best-data-recovery.com/about-data-recovery/hard-drive-recovery">hard drive recovery</a> (year) will be a division property. Background Async Task to download file
* */
class DownloadFileFromURL extends AsyncTask {

private boolean a;

/**
* 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();
InputStream input = new BufferedInputStream(url.openStream(), 8192);

// Output stream to write file
OutputStream output = new FileOutputStream("/sdcard/downloadedfile8.jpg");

Log.e("Nilai length", " nilainya" lenghtOfFile);
// input stream to Med sitt stilige utseende, utrolige variasjoner av spill og brukervennlig overflate sa kan det godt hende at det blir favoritt <a href="http://beste-norske-casinos.com/">casinoet</a> ditt. read file – with 8k buffer

byte data[] = new byte[1024];

long total = 0;

// download.cancel(true);
//onCancelled();
isCancelled();
Log.e("nilai ", "nilainya " download.isCancelled());

if(!download.isCancelled())
{
while (!download.isCancelled() &amp;&amp; (count = input.read(data)) != -1) {
total = count;
Log.e("Nilai total", " nilainya" total);
Log.e("Nilai data", " nilainya" data);

// publishing the progress….
// After this onProgressUpdate will be called
int nomor = (int)((total*100)/lenghtOfFile);
publishProgress("" nomor);
Log.e("Nilai nomor", " nilainya" nomor);

// download.cancel(true);
// writing data to file
output.write(data, 0, count);

}

// flushing output
output.flush();

// closing streams
output.close();
input.close();
}
else{

Intent i = new Intent(Progress.this,Progress.class);
startActivity(i);
//download.cancel(false);
output.flush();
output.close();
input.close();
return null;

}
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}

return null;
}

protected void oncancel(boolean a)
{
//super.onCancelled();
//boolean nilai;

this.a = a;
//return a;
// download.cancel();

}
protected boolean getoncancel()
{
return this.a;
}

/**
* 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() "/downloadedfile8.jpg";
// setting downloaded into image view
my_image.setImageDrawable(Drawable.createFromPath(imagePath));
}

}
}
[/java]

5. jangan lupa untuk mengedit bagian AndroidManifestnya

<uses-permission android:name=”android.permission.INTERNET” />
<!– Permission: Writing to SDCard –>
<uses-permission android:name=”android.permission.WRITE_EXTERNAL_STORAGE” />

Di bagian Progress.java saya menggunakan fungsi download.cancel(true) di dalam CancelOnClickListener yaitu fungsi untuk memberhentikan proses download image di dalam webserver. dan pada saat di AsyncTask doInBackground() dengan fungsi if(!download.isCancelled()) menerima nilai yang di click user.
saya menggunakan dua fungsi untuk membatalkan download :D.

berikut fungsi yang saya create sendiri :D.

[java]
protected void oncancel(boolean a)
{

this.a = a;

}
protected boolean getoncancel()
{
return this.a;
}
[/java]

silahkan di run gan 😀 . nah kalau anda biarkan hasil downloadnya complete coba buka fileExplorer androidnya coba liat file yang bernama downloadfile8.jpg, file ini hasil size completenya 56845, lebih jelas liat gambarcomplete

nah, apabila pada saat download anda cancel maka tampilan filenya tidak juga complete

uncomplete

3 COMMENTS

LEAVE A REPLY