change progress music when clicked on seekbar in android - android

hello all developer!
(this code is mediaplayer with seekbar)
the following code work properly but I want when clicked on the seekbar change progress music for example defalt musicplayer android
what can i do?
what add to my code?
public class DoaMatn1 extends Activity implements OnClickListener {
MediaPlayer mp;
ImageButton btndowndoa;
ImageButton btnplaydoa;
SeekBar seek_bar;
Handler seekHandler = new Handler();
private ProgressDialog pDialog;
public static final int progress_bar_type = 0;
private static String file_url = "http://upir.ir/files92be/9e6cbb43de76.mp3";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.doamatn);
mp = MediaPlayer.create(this,Uri.fromFile(audioFile));
btnplaydoa = (ImageButton) findViewById(R.id.btnplaydoa);
btnplaydoa.setOnClickListener(this);
btndowndoa = (ImageButton) findViewById(R.id.btndowndoa);
btndowndoa.setOnClickListener(this);
getInit();
seekUpdation();
}
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
File sdcard = Environment.getExternalStorageDirectory();
File audioFile = new File(sdcard.getPath() + "/EBKH/basem-tavasol.mp3");
public void getInit() {
if(audioFile.exists())
{
seek_bar = (SeekBar) findViewById(R.id.sbdoa);
seek_bar.setMax(mp.getDuration());
}
}
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.btnplaydoa :
if(audioFile.exists())
{
if(mp!=null)
{
if(mp.isPlaying())
{
mp.pause();
btnplaydoa.setImageResource(R.drawable.play);
}
else
{
mp.start();
btnplaydoa.setImageResource(R.drawable.pause);
}
}
}
break;
case R.id.btndowndoa :
if(!new File(Environment.getExternalStorageDirectory().toString() + "/EBKH/basem-tavasol.mp3").exists())
new DownloadFileFromURL().execute(file_url);
break;
}
}
Runnable run = new Runnable() {
#Override
public void run() {
seekUpdation();
}
};
public void seekUpdation() {
if(audioFile.exists())
{
seek_bar.setProgress(mp.getCurrentPosition());
seekHandler.postDelayed(run, 1000);
}
}
#Override
public void onBackPressed() {
if( mp != null && mp.isPlaying() ) {
mp.stop();
}
super.onBackPressed();
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type:
pDialog = new ProgressDialog(this);
pDialog.setMessage("در حال دانلود،لطفا صبور باشید...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
pDialog.show();
return pDialog;
default:
return null;
}
}
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/EBKH/basem-tavasol.mp3");
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);
}
}
}

you have to implement SeekBar.OnSeekBarChangeListener to your class, then set the listener like this songProgressBar.setOnSeekBarChangeListener(this); and than implement these methods:
/*/
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch)
{
}
/**
* When user starts moving the progress handler
* */
#Override
public void onStartTrackingTouch(SeekBar seekBar)
{
// remove message Handler from updating progress bar
handler.removeCallbacks(mUpdateTimeTask);
}
/**
* When user stops moving the progress hanlder
* */
#Override
public void onStopTrackingTouch(SeekBar seekBar)
{
handler.removeCallbacks(mUpdateTimeTask);
int totalDuration = mediaPlayer.getDuration();
int currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration);
// forward or backward to certain seconds
mediaPlayer.seekTo(currentPosition);
// update timer progress again
updateProgressBar();
}
Here is a link of a fully working Media Player Example with seekbar touch listener and song progress update:
http://www.androidhive.info/2012/03/android-building-audio-player-tutorial/
Regarding the tutorial the only thing that will not work is retrieving and filtering the song from the given file path. Somehow I couldn't get it to work. But I found another solution which was to write your own FileFilter. But in your case you are using a URL so that doesn't matter.

Related

How to change this class to download audio file?

I have this class that downloads an image from a server and that I carry it on my main activity
public class imgDownloader extends AsyncTask<Void, Integer, Void> {
private ProgressBar pb;
private String url;
private Button save;
private Context c;
private int progress;
private ImageView img;
private Bitmap bmp;
private TextView percent;
private ImageLoaderListener listener;
/*--- constructor ---*/
public ImageDownloader(String url, ProgressBar pb, Button save,
ImageView img, TextView percent, Context c, Bitmap bmp, ImageLoaderListener listener) {
/*--- we need to pass some objects we are going to work with ---*/
this.url = url;
this.pb = pb;
this.save = save;
this.c = c;
this.img = img;
this.percent = percent;
this.bmp = bmp;
this.listener = listener;
}
/*--- we need this interface for keeping the reference to our Bitmap from the MainActivity.
* Otherwise, bmp would be null in our MainActivity*/
public interface ImageLoaderListener {
void onImageDownloaded(Bitmap bmp);
}
#Override
protected void onPreExecute() {
//progress = 0;
//pb.setVisibility(View.VISIBLE);
//percent.setVisibility(View.VISIBLE);
//Toast.makeText(c, "starting download", Toast.LENGTH_SHORT).show();
Log.d("Script", "//" + "starting download");
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
bmp = getBitmapFromURL(url);
/*
while (progress < 10) {
progress += 1;
publishProgress(progress);
SystemClock.sleep(200);
}
*/
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
/*--- show download progress on main UI thread---*/
// pb.setProgress(values[0]);
// percent.setText(values[0] + "%");
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Void result) {
if (listener != null) {
listener.onImageDownloaded(bmp);
}
img.setImageBitmap(bmp);
//save.setEnabled(true);
//Toast.makeText(c, "download complete", Toast.LENGTH_SHORT).show();
Log.d("Script", "//" + "download complete");
super.onPostExecute(result);
}
}
I need instead of downloading an image to download a mp3 audio file and use the call of my NOTIFICATION
This is where I use some flags and use an audio that is in my raw pasta.
noti.sound = Uri.parse("android.resource://"
+ _context.getPackageName() + "/" + R.raw.galo);
noti.flags |= Notification.FLAG_NO_CLEAR;
noti.defaults |= Notification.DEFAULT_LIGHTS;
noti.flags |= Notification.FLAG_ONLY_ALERT_ONCE;
noti.priority = Notification.PRIORITY_MAX;
mNotificationManager.notify(MESSAGE_NOTIFICATION_ID, noti);
Here I need to use the same class adapted upon to download the audio, but do not know how I can do this. Download the audio file and let the SDCARD is out of the question.
noti.sound = Uri.parse("android.resource://" + _context.getPackageName() + "/" + R.raw.galo);
You can try this class to download file
//to call
new DownloadFileFromURL().execute("download_url");
//Class to download file
class DownloadFileFromURL extends AsyncTask<String, String, String>
{
/**
* Before starting background thread
* Show Progress Bar Dialog
* */
#Override
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* Downloading file in background thread
* */
#Override
protected String doInBackground(String... f_url)
{
int count;
try
{
//file name with extension
File file=new File("/directory/file.mp3");
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// this will be useful so that you can show a tipical 0-100% progress bar
int lenghtOfFile = conection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream
OutputStream output = new FileOutputStream(file);
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
pDialog.dismiss();
}
}

downloading images with progessbar percentage

Hi in the below downloading images for showing progessbar to 100 but completeld 100% images are not showing still downloading and not showing .i want after 100% i want to move to activity.
But it's taking time to move next activity.
java
public class DownloadTask extends AsyncTask<Void, Void, String> {
protected void onPreExecute() {
super.onPreExecute();
final DialogProgressBarRunnable progressDialog =
new DialogProgressBarRunnable(getActivity(), false, 2);
progressDialog.show();
// the dialog box shouldn't get cancelled when clicking outside it or pressing back button.
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setCancelable(false);
// pd.setMessage("Downloading catalogue images.");
// pd.show();
}
protected String doInBackground(Void... Params) {
parsingObject = new ParsingForFinalImages(catid, responseJson);
/* ConnectionDetector cd = new ConnectionDetector(getActivity().getBaseContext());
Boolean isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent==true)
{
}
*/
// put your code here
// JSON parsing begins here via the parsing class
// Put this code in async task
return "Success";
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
// pd.hide();
// pd.dismiss();
Intent intent = new Intent(getActivity(), ImageGallery.class);
startActivity(intent);
}
}
private class DialogProgressBarRunnable extends ProgressDialog implements
Runnable {
private boolean showSecondary;
private int incrementAfter;
public DialogProgressBarRunnable(Context context,
boolean showSecondary, int incrementAfter) {
super(context);
setCancelable(true);
setMessage(getString(R.string.download_message));
setSecondaryProgress(0);
setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
setMax(100);
setProgress(0);
this.showSecondary = showSecondary;
this.incrementAfter = incrementAfter;
}
#Override
public void show() {
super.show();
new Thread(this).start();
}
#Override
public void run() {
while (progress < 100) {
progress++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// increment the first/second progress bar after every %
progressBar();
}
}
private void progressBar() {
if (progress % incrementAfter == 0) {
progressFirstBar();
}
if (showSecondary) {
progressSecondaryBar();
}
}
private void progressSecondaryBar() {
while (secondaryProgress < 100) {
secondaryProgress++;
try {
Thread.sleep(50000);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
#Override
public void run() {
setSecondaryProgress(secondaryProgress);
}
});
}
}
private void progressFirstBar() {
secondaryProgress = 0;
handler.post(new Runnable() {
#Override
public void run() {
setProgress(progress);
if (progress == 100) {
dismiss();
}
}
});
}
}
class DownloadFileFromURL extends AsyncTask {
/**
* Before starting background thread Show Progress Bar Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
/**
* After completing background task Dismiss the progress dialog
* **/
#SuppressWarnings("deprecation")
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
// Declear Variables
int count;
try {
URL url1 = new URL(url);
URLConnection conection = url1.openConnection();
conection.connect();
// this will be useful so that you can show a tipical 0-100%
// progress bar
int lenghtOfFile = conection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url1.openStream(),
8192);
// Output stream
OutputStream output = new FileOutputStream(Environment
.getExternalStorageDirectory().toString() + "/Report.xls");
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);
Log.d("Downloding"+data,"Count"+count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
/**
* Updating progress bar
* */
#Override
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
/**
* After completing background task Dismiss the progress dialog
* **/
#SuppressWarnings("deprecation")
#Override
protected void onPostExecute(String reString) {
// dismiss the dialog after the file was downloaded
super.onPostExecute(null);;
dismissDialog(progress_bar_type);
Log.d("Download","Completed");
Intent intent1=new Intent(DownloadExcle.this,MainActivity.class);
intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent1);
}
}

Progressbar with percentage in Asynctask Android

I am writing a code in which I need to move all file and folders to the sdcard. I used Async task for this purpose. During this activity I am showing a progressbar with percentage on my screen instead of just showing me the "Loading..." popup. But it does not meet my requirement.
public class syncMgr extends AsyncTask<String, Long, String> {
public LoginActivity activity;
public Context context;
syncMgr(LoginActivity activity1,Context c)
{
activity = activity1;
context=c;
}
//public ProgressDialog progress;
protected void onPreExecute() {
super.onPreExecute();
activity.progress = ProgressDialog.show(context,"","Files Downloading, Please Wait...",true);
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
copyFilesToSdCard();
return null;
}
private void copyFilesToSdCard() {
copyFileOrDir("");
}
private void copyFileOrDir(String path) {
AssetManager assetManager = activity.getAssets();
String assets[] = null;
try {
Log.i("tag", "copyFileOrDir() " + path);
assets = assetManager.list(path);
if (assets.length == 0) {
copyFile(path);
} else {
String fullPath = TARGET_BASE_PATH + path;
Log.i("tag", "path=" + fullPath);
File dir = new File(fullPath);
if (!dir.exists() && !path.startsWith("images")
&& !path.startsWith("sounds")
&& !path.startsWith("webkit"))
if (!dir.mkdirs())
Log.i("tag", "could not create dir " + fullPath);
for (int i = 0; i < assets.length; ++i) {
publishProgress((int) ((i / (float) 658) * 100));
String p;
if (path.equals(""))
p = "";
else
p = path + "/";
if (!path.startsWith("images")
&& !path.startsWith("sounds")
&& !path.startsWith("webkit"))
copyFileOrDir(p + assets[i]);
}
}
} catch (IOException ex) {
Log.e("tag", "I/O Exception", ex);
}
}
private void publishProgress(int i) {
// TODO Auto-generated method stub
activity.progress.setProgress(i);
}
#Override
protected void onProgressUpdate(Long... values) {
activity.progress.setProgress(values[0].intValue());
}
#Override
protected void onPostExecute(String result) {
activity.progress.dismiss();
super.onPostExecute(result);
//return "asdas";
//return result;
}
}
Here is my Activity Class Code...
ProgressDialog progress;
public static final int progress_bar_type = 0;
/**
* Showing Dialog
* */
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type: // we set this to 0
progress = new ProgressDialog(this);
progress.setMessage("Downloading file. Please wait...");
progress.setIndeterminate(false);
progress.setMax(100);
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progress.setCancelable(true);
progress.show();
return progress;
default:
return null;
}
}
Have you tried putting the asyncTask initiation code into a worker thread like this?
// set progressBar .VISIBLE first
// then...
new Thread(new Runnable() {
public void run() {
// webview initiation code
}
}).start();
I turn on progressBar visibility beforehand and not in onPreExecute().
Here is how it solved my own problem & here are the docs.

why not delete incomplete file in asynctask

Im useing onCancelled() in asynctask for delete incomplete file but when download incomplete file donnt delete it.
(file is music)
why not delete incomplete file in the following code?
my api is 8
this is my code:
public class ZiaratMatn4 extends Activity implements OnClickListener {
MediaPlayer mp;
ImageButton btndownziarat;
ImageButton btnplayziarat;
SeekBar seek_bar;
Handler seekHandler = new Handler();
private ProgressDialog pDialog;
public static final int progress_bar_type = 0;
private static String file_url = "http://upir.ir/files92be/2eda2a6a5434.mp3";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ziaratmatn);
mp = MediaPlayer.create(this,Uri.fromFile(audioFile));
btnplayziarat = (ImageButton) findViewById(R.id.btnplayziarat);
btnplayziarat.setOnClickListener(this);
btndownziarat = (ImageButton) findViewById(R.id.btndownziarat);
btndownziarat.setOnClickListener(this);
getInit();
seekUpdation();
}
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
File sdcard = Environment.getExternalStorageDirectory();
File audioFile = new File(sdcard.getPath() + "/EBKH/basem-vares.mp3");
public void getInit() {
if(audioFile.exists())
{
seek_bar = (SeekBar) findViewById(R.id.sbziarat);
seek_bar.setMax(mp.getDuration());
}}
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.btnplayziarat :
if(audioFile.exists())
{
if(mp!=null)
{
if(mp.isPlaying())
{
mp.pause();
btnplayziarat.setImageResource(R.drawable.play);
}
else
{
mp.start();
btnplayziarat.setImageResource(R.drawable.puse);
}}}
break;
case R.id.btndownziarat :
if(!new File(Environment.getExternalStorageDirectory().toString() + "/EBKH/basem-vares.mp3").exists())
new DownloadFileFromURL().execute(file_url);
break;
}}
Runnable run = new Runnable() {
#Override
public void run() {
seekUpdation();
}
};
public void seekUpdation() {
if(audioFile.exists())
{
seek_bar.setProgress(mp.getCurrentPosition());
seekHandler.postDelayed(run, 1000);
}}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type:
pDialog = new ProgressDialog(this);
pDialog.setMessage("در حال دانلود،لطفا صبور باشید...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
pDialog.show();
return pDialog;
default:
return null;
}
}
class DownloadFileFromURL extends AsyncTask<String, String, String> {
#Override
protected void onCancelled() {
File file= new File("/sdcard/EBKH/basem-vares.mp3");
file.delete();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
int lenghtOfFile = conection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream(), 8192);
OutputStream output = new FileOutputStream("/sdcard/EBKH/basem-vares.mp3");
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.e("Error: ", e.getMessage());
}
return null;
}
protected void onProgressUpdate(String... progress) {
pDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String file_url) {
dismissDialog(progress_bar_type);
}}}
I am unsure as to what is going on here but what might help is adding a finally{} block at the end which checks if the total bytes read is equal to the length of the file. If not, delete the file.
It's because you're never cancelling the AsyncTask!!! You need to call cancel() on the AsyncTask object, but to do that you need to keep the instance in a variable first.
So first, keep the instance of the AsyncTask, so declare the task in your class
DownloadFileFromURL downloadTask;
When you create the task, assign it to your variable
downloadTask = new DownloadFileFromURL().execute(file_url);
And whenever you want to cancel, call this:
downloadTask.cancel();

How to add ProgressDialog

I am downloading a file from dropbox which is taking a few seconds. I want to add a ProgressDialog for the download but I don't know how to do that.
public class DownloadFile extends AsyncTask<Void, Long, Boolean> {
DownloadFile(Context context ,DropboxAPI<?> mApi ,String dropboxpath,String sdpath,int pos,int s,ArrayList<String> folder) throws DropboxException {
FileOutputStream mFos;
File file=new File(sdpath);
String path = dropboxpath;
try{
mFos = new FileOutputStream(file);
mApi.getFile(path, null, mFos, null);
}catch (Exception e) {
// TODO: handle exception
}
}
#Override
protected Boolean doInBackground(Void... params) {
// TODO Auto-generated method stub
return null;
}
}
Do it this way:
public final class DownloadFile extends AsyncTask<Void, Long, Boolean> {
private Context context;
private ProgressDialog progressDialog;
public DownloadFile (Context context) {
this.context = context;
}
/*
* #see android.os.AsyncTask#onPreExecute()
*/
#Override
protected void onPreExecute() {
try {
progressDialog = ProgressDialog.show(context, "", "message", true);
} catch (final Throwable th) {
//TODO
}
}
/*
* #see android.os.AsyncTask#doInBackground(Params[])
*/
#Override
protected Boolean doInBackground(Void... arg0) {
//do something
}
#Override
protected void onProgressUpdate(String... progress) {
//do something
super.onProgressUpdate(progress);
}
/*
* #see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
#Override
protected void onPostExecute(Boolean result) {
progressDialog.dismiss();
} }
Use this simple code #sachin
public class DownloadFile extends AsyncTask<Void, Void, Void> {
Home home;
ProgressDialog dialog = null;
public DownloadFile(Home home) {
// TODO Auto-generated constructor stub
this.home = home;
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
//Call hare method for download
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialog.dismiss();
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog = ProgressDialog.show(home, "Downloading......", "", true);
}
}
This article can be useful for you:
http://huuah.com/android-progress-bar-and-thread-updating/
Where inside the run() method of your thread you can invoke a function like this:
public boolean download(String url, String path, String fileName, Handler progressHandler) {
try {
URL sourceUrl = new URL(formatUrl(url));
if (fileName == null || fileName.length() <= 0) {
fileName = sourceUrl.getFile();
}
if (fileName == null || fileName.length() <= 0) {
throw new Exception("EMPTY_FILENAME_NOT_ALLOWED");
}
File targetPath = new File(path);
targetPath.mkdirs();
if (!targetPath.exists()) {
throw new Exception("MISSING_TARGET_PATH");
}
File file = new File(targetPath, fileName);
URLConnection ucon = sourceUrl.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(100);
int current = 0;
int totalSize = ucon.getContentLength();
while ((current = bis.read()) != -1) {
baf.append((byte) current);
// BEGIN - Handler feedback
if (progressHandler != null && (baf.length() % 100) == 0) {
Message msg = progressHandler.obtainMessage();
Bundle b = new Bundle();
if (totalSize > 0) {
b.putInt("total", totalSize);
b.putInt("step", baf.length());
b.putBoolean("working", true);
}
msg.setData(b);
progressHandler.handleMessage(msg);
}
// END
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
// BEGIN - Handler feedback
if (progressHandler != null) {
Message msg = progressHandler.obtainMessage();
Bundle b = new Bundle();
if (totalSize > 0) {
b.putInt("total", 0);
b.putInt("step", 0);
b.putBoolean("working", false);
}
msg.setData(b);
progressHandler.handleMessage(msg);
}
// END
return file.exists();
}
Doing this way, you have a more accurate feedback about real progress of you download (byte per byte).
See there are actually 4 methods of AsyncTask:
onPreExecute() - you can do some pre execution task here.
doInBackground() - you can perform some background work here.
onPostExecute() - you can perform post execution task here. Means like displaying data in ListView, update TextView, etc.
onProgressUpdate() - To update UI while background operation is going on.
So in your case, you can show progress dialog or progress bar inside onPreExecute() method of AsyncTask and dismiss(() the same inside onPostExecute().

Categories

Resources