I'm tryinig to create a service to download a file from a server, in my local network.Every think seems to be ok ,the service starts, when the download ends ,when i check for the file in the sdcard i found an emty file ,can someone help me to solve this problem ,Thank you in advance.
This the service DownloadService :
public class DownloadService extends Service{
private static String file_url = "http://192.168.1.150:8080/TestAndroid/DownloadServlet/Desert.pdf";
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(getBaseContext(), "Service started", Toast.LENGTH_LONG).show();
new DownloadFileFromURL().execute(file_url);//Appel vers Asynctask
return START_STICKY;
}
/**
* Background Async Task to download file
* */
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Before starting background thread
* Show Progress Bar Dialog
* */
public String[] listDebitDown = new String[163] ;
int compteur = 0;
#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();
// 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("/sdcard/downloadedfile.pdf");//jpg
int nombrePaquets ;
nombrePaquets = (lenghtOfFile / 1024 ) + (lenghtOfFile % 1024 );
byte data[] = new byte[1024];
String tabResult [] = new String [nombrePaquets];
long total = 0;
long startTotalTime = System.currentTimeMillis();
long passedTime =0;
// Get ListView object from xml
// listView = (ListView) findViewById(R.id.listView1);
while ((count = input.read(data)) != -1) {
total += count;
// 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;
}
/**
* After completing background task
* Dismiss the progress dialog
* **/
#Override
protected void onPostExecute(String file_url) {
Toast.makeText(getApplicationContext(),
"téléchargement términé " , Toast.LENGTH_LONG)
.show();
Toast.makeText(getApplicationContext(),
"Passagr "+ listDebitDown[10] , Toast.LENGTH_LONG)
.show();
// Displaying downloaded image into image view
// Reading image path from sdcard
String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.pdf";//jpg
Log.i("imagePath", imagePath);
Log.i("isExternalStorageWritable", isExternalStorageWritable() + "true" );
}
}
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
Log.i("isExternalStorageWritable", "true" );
return true;
}
return false;
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
PS:of corse i added permission ,the server can ping to the phone ,the wamp server is ON .
Try to store file in external storage.
File mFile= new File(Environment.getExternalStorageDirectory(), "downloadedfile.pdf");
if(!mFile.isExist()){
mFile.createNewFile();
}
then
OutputStream output = new FileOutputStream(mFile,true);
Related
I'm developing an Android application for downloading a file from
server and save that file to the path specified..
I want to make this happen in the background, So I code the downloading function in service. Now I'm getting an error when I used the code in my service..
Can anyone help me to find the error... Thank You..
My Service code Is...
public class MyService extends Service {
Contacts c = new Contacts();
// File url to download
private static String file_url = "http://f23.wapka-files.com/download/6/9/4/1408248_69459e029be95f96ff9f98ff.mp3/a0f9f2173d3d81a49c28/01-Podimeesha-Anand.Madhusoodhanan.mp3y";
public MyService() {
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
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.srt");
// starting new Async Task
new DownloadFileFromURL().execute(file_url);
MyService.this.stopService(intent);
return super.onStartCommand(intent, flags, startId);
}
/**
* 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();
}
* 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;
}
#Override
protected void onPostExecute(String file_url) {
Toast.makeText(MyService.this, "Downloaded Succesfully.. check Jithin's folder 2 see file...", Toast.LENGTH_LONG).show();
//my_image.setImageDrawable(Drawable.createFromPath(imagePath));
}
}
}
My Main Activity code is..
public void download(View view) {
String value = getIntent().getExtras().getString("id");
if (value.equals("Song0")) {
Intent i=new Intent(Song_List.this, MyService.class);
startActivity(i);
Toast.makeText(Song_List.this, "Downloading..........", Toast.LENGTH_SHORT).show();
}
}
Change your code from,
Intent i=new Intent(Song_List.this, MyService.class);
startActivity(i);
this to,
Intent i=new Intent(Song_List.this, MyService.class);
startService(i);
First of all you should start your service like this not with startActivity
public void download(View view) {
String value = getIntent().getExtras().getString("id");
if (value.equals("Song0")) {
Intent i=new Intent(Song_List.this, MyService.class);
startService(i);
Toast.makeText(Song_List.this, "Downloading..........", Toast.LENGTH_SHORT).show();
}
}
after stop service when your file download is completed
MyService is the extention of Service. So you have to use startService(Intent).
so your code may look like this :
public void download(View view) {
String value = getIntent().getExtras().getString("id");
if (value.equals("Song0")) {
Intent i=new Intent(Song_List.this, MyService.class);
startService(i);
Toast.makeText(Song_List.this, "Downloading..........", Toast.LENGTH_SHORT).show();
}
}
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 have good concept of starting and using the basic service. I mean not to complicated. In My app I want a service which should not be killed in any situation and should download some files from the server then it should call stopSelf. I have made my service in the following way. But before sharing its whole code just let me tell you what I am doing
In Service I am passing the series of url (string array) which has to download all files from the server.
I am using the async task to download from the server.
Under this whole process I am getting a 1st response that is in xml then I parse it , and get the JSON string (sorry about that my web service designer is a numb like me). so after these two conversion I store the data in the database and then starts downloading files and saving them to device and store their path in the database. (this all works fine)
I am calculating and updating progress in the notification bar. (showing user how much the files has been downloaded)
what I really want
I want that my service should not be killed when user removes it from the recent app list , so that it should continue to download and continue to update the status in notification bar. I am using Notification manager to update the progress.
What is really happening
When I close my app from recent app tray, I think my service gets killed and the downloading process stops, and It also stops updating the progress of notification in notification bar, Where As I want it to continue to run until the download process is finished.
Here is my code it is simplified as some methods are really not worthy
to be discussed here Such as Parsing the xml or JSON
Here is the Code
public class MyDemoService extends Service {
private static final String TAG = "MyDemoService";
private static final int NOTIFICATION_ID = 1;
private LocalBinder m_binder = new LocalBinder();
private NotificationManager mNotifyManager;
private NotificationCompat.Builder mBuilder;
myAsyncTask myWebFetch;
// Timer to update the ongoing notification
private final long mFrequency = 100; // milliseconds
private final int TICK_WHAT = 2;
public class LocalBinder extends Binder {
MyDemoService getService() {
return MyDemoService.this;
}
}
private Handler mHandler = new Handler() {
public void handleMessage(Message m) {
updateNotification();
sendMessageDelayed(Message.obtain(this, TICK_WHAT), mFrequency);
}
};
#Override
public IBinder onBind(Intent intent) {
Log.d(TAG, "bound");
return m_binder;
}
#Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "created");
mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_STICKY;
}
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
Log.d(TAG, "Removed");
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "Destroyed");
}
public void updateNotification() {
// Log.d(TAG, "updating notification");
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
}
public void hideNotification() {
Log.d(TAG, "removing notification");
mNotifyManager.cancel(NOTIFICATION_ID);
mHandler.removeMessages(TICK_WHAT);
}
public void start() {
Log.d(TAG, "start");
mBuilder =
new NotificationCompat.Builder(MyDemoService.this)
.setSmallIcon(R.drawable.download)
.setContentTitle("SMU")
.setContentText("Downloading Images");
Intent targetIntent = new Intent(MyDemoService.this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(MyDemoService.this, 0, targetIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(contentIntent);
mNotifyManager.notify(NOTIFICATION_ID, mBuilder.build());
myWebFetch = new myAsyncTask();
myWebFetch.execute();
}
class myAsyncTask extends AsyncTask<String, Integer, Void> {
MyDB myDB;
myAsyncTask() {
myDB = new MyDB(MyDemoService.this);
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
mBuilder.setContentText("Download complete");
// Removes the progress bar
mBuilder.setProgress(0, 0, false);
mNotifyManager.notify(NOTIFICATION_ID, mBuilder.build());
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
mBuilder.setProgress(100, values[0], false);
mNotifyManager.notify(NOTIFICATION_ID, mBuilder.build());
}
#Override
protected Void doInBackground(String... params) {
//set the download URL, a url that points to a file on the internet
getJSON("http://*****", 1000000);
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mBuilder.setProgress(100, 0, false);
mNotifyManager.notify(NOTIFICATION_ID, mBuilder.build());
}
public void getJSON(String url, int timeout) {
HttpURLConnection c = null;
try {
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.setConnectTimeout(timeout);
c.setReadTimeout(timeout);
c.setInstanceFollowRedirects(false);
c.connect();
int status = c.getResponseCode();
if (status == 200) {
String readStream = readStream(c.getInputStream());
if (readStream != null) {
JsonParser mJsonParser = new JsonParser(MyDemoService.this);
mJsonParser.parseJaSon(readStream);
ArrayList<SuitDetails> mImageList = new ArrayList<>(myDB.GetAllData());
if (mImageList != null) {
//NOW HERE DOWNLOADING IMAGES FROM URL WE GOT SAVED IN DB AFTER PARSING
downloadImages(mImageList);
}
}
}
} catch (MalformedURLException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} finally {
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
}
}
}
#TargetApi(Build.VERSION_CODES.KITKAT)
private String readStream(InputStream in) {
//parsing my input stream and sending back string
return jsonString.toString();
}
void downloadImages(ArrayList<SuitDetails> arrayList) {
try {
ArrayList<SuitDetails> imageUrl = arrayList;
URL url;
float progressImages = 0;
HttpURLConnection urlConnection = null;
for (int i = 0; i < imageUrl.size(); i++) {
progressImages += 100 / imageUrl.size();
publishProgress((int) progressImages);
url = new URL(imageUrl.get(i).getPath().toString());
//create the new connection
urlConnection = (HttpURLConnection) url.openConnection();
//set up some things on the connection
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(false);
urlConnection.setUseCaches(false);
urlConnection.setAllowUserInteraction(false);
urlConnection.setConnectTimeout(60000);
urlConnection.setReadTimeout(60000);
urlConnection.setInstanceFollowRedirects(false);
//and connect!
urlConnection.connect();
File storagePath = new File(MyDemoService.this.getExternalFilesDir("TEST") + "/Mytest");
storagePath.mkdirs();
String finalName = imageUrl.get(i).getImageName();
File myImage = new File(storagePath, finalName + ".png");
FileOutputStream fileOutput = new FileOutputStream(myImage);
InputStream inputStream = urlConnection.getInputStream();
int totalSize = urlConnection.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
//add the data in the buffer to the file in the file output stream (the file on the sd card
fileOutput.write(buffer, 0, bufferLength);
//add up the size so we know how much is downloaded
downloadedSize += bufferLength;
//this is where you would do something to report the prgress, like this maybe
}
//close the output stream when done
ContentValues contentValues = new ContentValues();
contentValues.put("Status", "1");
contentValues.put("Path", myImage.getPath().toString());
myDB.UpdateDownloadStatus(contentValues, imageUrl.get(i).getSImageID());
fileOutput.close();
}
myDB.closeDb();
//catch some possible errors...
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I Know this is length code but sharing if You want to analyse it deeply.
I will provide how I am using and calling this service in MainActivity if you demand it
why are you not using an IntentService if you want to do network stuff?
you should consider adding setIntentRedelivery(true); in your constructor
from the documentation
Sets intent redelivery preferences. Usually called from the
constructor with your preferred semantics.
If enabled is true, onStartCommand(Intent, int, int) will return
START_REDELIVER_INTENT, so if this process dies before
onHandleIntent(Intent) returns, the process will be restarted and the
intent redelivered. If multiple Intents have been sent, only the most
recent one is guaranteed to be redelivered.
If enabled is false (the default), onStartCommand(Intent, int, int)
will return START_NOT_STICKY, and if the process dies, the Intent dies
along with it.
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);