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.
Related
I had created downloading task using intent service. which shows notification with progress bar with percentage.I'm using local broadcast manager to pass data while downloading.I also add one button to cancel download in notification but the problem is while i'm clicking on cancel Download it not stop Intent service. how can i stop intent service. Here i put my code of Intent service and also broadcast receiver to close service.
public class DownloadService extends IntentService {
public DownloadService() {
super(DownloadService.class.getName());
}
#Override
protected void onHandleIntent(#Nullable Intent intent) {
InputStream input;
OutputStream output;
HttpURLConnection connection;
Intent intent1 = new Intent();
intent1.setAction("com.demo.downloading");
try {
URL url = new URL(urlToDownload);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return;
}
final int fileLength = connection.getContentLength();
input = connection.getInputStream();
output = new FileOutputStream(file);
byte data[] = new byte[8192];
long total = 0;
int count, latestPercentDone;
int percentDone = -1;
while ((count = input.read(data)) != -1) {
total += count;
latestPercentDone = (int) (total * 100 / fileLength);
if (percentDone != latestPercentDone) {
percentDone = latestPercentDone;
if (percentDone < 100) {
if (percentDone != 0) {
intent1.putExtra("progress", "" + percentDone);
intent1.putExtra("IsCancel", false);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent1);
}
}
if (percentDone == 100) {
intent1.putExtra("progress", "" + 0);
intent1.putExtra("IsCancel", false);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent1);
}
}
output.write(data, 0, count);
if (StaticFields.cancelDownload) {
Log.d(TAG, "onHandleIntent: Download Cancel");
this.stopSelf();
}
}
output.close();
} catch (IOException e) {
intent1.putExtra("progress", "" + (-1));
intent1.putExtra("IsCancel", true);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent1);
e.printStackTrace();
is_all_download = false;
}
}
}
My broadcast receiver class
OnReceive method ()
if (intent.getAction() != null) {
if (action.equals("notification_cancelled")) {
Global.cancelDownload = true;
Intent intent1 = new Intent();
intent1.setAction("com.demo.downloading");
intent1.putExtra("IsCancel", true);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent1);
}
}
}
LocalBroadcast manager receive method
boolean isCancel = intent.getBooleanExtra("IsCancel", false);
if (isCancel) {
Global.cancelDownload = true;
mContext.stopService(serviceIntent);
}
In an IntentService, onHandleIntent() is called on a worker (background) thread. When you call stopService(), this has no effect on the worker threads, as they will still run to completion. Calling stopService() on an IntentService makes no sense anyway, since an IntentService runs when it has work to do and stops itself when all of the work is finished.
Instead of calling stopService(), you need to set a flag in your Service that can be checked in the loop in your onHandleIntent() method. If the flag is set, you should abort further processing in your loop and end the worker thread yourself.
I have an intent service which is processing long running task. But while processing if an exception occurs lets say SocketTimeOutException the service stops. How to catch the exception and restart the process.
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
#Override
protected void onHandleIntent(Intent intent) {
String name = intent.getStringExtra("name");
String packageName = intent.getStringExtra("packageName");
String path = intent.getStringExtra("path");
int downloadedSoFar = 0;
Intent i = new Intent(getApplicationContext(), DownloadListViewApp.class);
PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 0, i, 0);
nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(this);
mBuilder.setContentTitle(name)
.setContentText("Download in progress")
.setSmallIcon(R.drawable.logo).setContentInfo("0%").setContentIntent(pi);
mBuilder.setOngoing(true);
try {
url = new URL(IPClass.SERVERIP + path + "/" + packageName);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setReadTimeout(7000);
int fileLength = connection.getContentLength();
connection.connect();
input = connection.getInputStream();
output = new FileOutputStream("/sdcard/Android/appdata/tmp/downloadtmp/" + packageName, true);
byte data[] = new byte[1024];
int count;
boolean continueLoop = true;
while ((count = input.read(data)) > 0 && continueLoop) {
progressChange((int) (downloadedSoFar * 100L) / fileLength, packageName);
downloadedSoFar = downloadedSoFar + count;
output.write(data, 0, count);
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (output != null) output.close();
if (input != null) input.close();
} catch (IOException ignored) {
}
if (connection != null) {
connection.disconnect();
}
}
You can't stop intent service till its duty has completed, if you want to stop it then you should have to stop alarm manager in intent service like this.
Intent DataSyncing = new Intent(getBaseContext(), DataSyncingScheduledReceiver.class);
DataSyncing.setAction(DataSyncingScheduledReceiver.ACTION_DATASYNC_RECEIVER);
PendingIntent DataSyncingIntent = PendingIntent.getBroadcast(getBaseContext(),1003, DataSyncing, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManagerdatasync = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManagerdatasync.cancel(DataSyncingIntent);
DataSyncingIntent.cancel();
Ref :- https://stackoverflow.com/a/12776012/2705391
You can use this for your problem.
#Override
protected void onHandleIntent(Intent intent)
{
try
{
// STOP SERVICE
// DO YOUR WORK HERE
}
finally
{
// START SERVICE
}
}
I think restarting a servise is not a solution you should handle it in catch
put your code to call api inside seperate function
supose your function is like callAPI()
} catch (final java.net.SocketTimeoutException e) {
// connection timed out...let's try again
callAPI()
}
This creates a recursion
by this your api will be called n time untill your api will give SocketTimeoutException
so you will not need to restart your IntentService. it will remain onrun until your api executed
if you want to prevent this you have to specify and implement logic of nuberofAttempts as in volley
volley inbuilt has retry policy you should read about it.
else i sugest volley or retrofit to use
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();
}
}
We have an app in the Google Play Store that runs in the foreground continuously. The devices that it runs on are out of our control and are not rooted. They run on either Android 4.2 or 4.4.
Our goal is to have the app update to the newest version that we release via the Play Store without user interaction. Restarting the device would be the only acceptable "interaction" option.
We find that a running app does not updated automatically when it is running even if the "automatic update" is turned on.
What is the way to achieve our goal?
Use an Alarm Manager to scheduled your update and then use a create a class and extend the service or IntentService class. Check if theres an internet connection if yes proceed to update like this: Check this link Android Services - Tutorial In this way you can update even not showing your Activity by using service.
Creating the Alarm Manager:
Calendar cal = Calendar.getInstance();
Intent intent = new Intent(this, MyService.class);
PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
// Start every 30 seconds
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 30*1000, pintent);
For service:
public class DownloadService extends IntentService {
private int result = Activity.RESULT_CANCELED;
public static final String URL = "urlpath";
public static final String FILENAME = "filename";
public static final String FILEPATH = "filepath";
public static final String RESULT = "result";
public static final String NOTIFICATION = "com.vogella.android.service.receiver";
public DownloadService() {
super("DownloadService");
}
// will be called asynchronously by Android
#Override
protected void onHandleIntent(Intent intent) {
String urlPath = intent.getStringExtra(URL);
String fileName = intent.getStringExtra(FILENAME);
File output = new File(Environment.getExternalStorageDirectory(),
fileName);
if (output.exists()) {
output.delete();
}
InputStream stream = null;
FileOutputStream fos = null;
try {
URL url = new URL(urlPath);
stream = url.openConnection().getInputStream();
InputStreamReader reader = new InputStreamReader(stream);
fos = new FileOutputStream(output.getPath());
int next = -1;
while ((next = reader.read()) != -1) {
fos.write(next);
}
// successfully finished
result = Activity.RESULT_OK;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
publishResults(output.getAbsolutePath(), result);
}
private void publishResults(String outputPath, int result) {
Intent intent = new Intent(NOTIFICATION);
intent.putExtra(FILEPATH, outputPath);
intent.putExtra(RESULT, result);
sendBroadcast(intent);
}
}
in my app i have 4 buttons and when the user clicks any of the button it starts downloading a file and the progress bar gets shown in the notification area. The downloading and progress bar is working fine, but i have the following two problems
When the download completes the progress bar is not getting closed, it remains in the notification area
As i said above i have 4 buttons and when the first button is clicked download gets started and when the other three buttons are clicked immediately download is not taking place. I thought it may start after first download completes. But nothing happens. How to show all the progress bar when all buttons clicked
Following is my code(here i have added only 2 buttons) pls help me
b1 = (Button)findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
i =1;
Intent intent = new Intent(NotificationProgressTestActivity.this, UploadService.class);
startService(intent);
}
});
b2 = (Button)findViewById(R.id.button2);
b2.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
i = 2;
Intent intent = new Intent(NotificationProgressTestActivity.this, UploadService.class);
startService(intent);
}
});
Next following is my Uplaod Service.class
public class UploadService extends IntentService
{
private NotificationManager notificationManager;
private Notification notification;
private int progress = 10;
private static String fileName = "folder/";
private static URL url;
public UploadService(String name)
{
super(name);
}
public UploadService()
{
super("UploadService");
}
#Override
protected void onHandleIntent(Intent intent)
{
notificationManager = (NotificationManager) getApplicationContext().getSystemService(getApplicationContext().NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
notification = new Notification(R.drawable.icon,"Uploading file", System.currentTimeMillis());
notification.flags = notification.flags | Notification.FLAG_ONGOING_EVENT;
notification.contentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.upload_progress_bar);
notification.contentIntent = contentIntent;
notification.contentView.setProgressBar(R.id.progressBar1, 100, progress, false);
notificationManager.notify(42, notification);
notificationManager.notify(42, notification);
Thread download = new Thread()
{
#Override
public void run()
{
Log.e("download", "start");
try
{
for (int i = 1; i < 100; i++)
{
progress++;
notification.contentView.setProgressBar(R.id.progressBar1, 100, progress, false);
if(i==1)
{
if(NotificationProgressTestActivity.i ==1 )
{
url = new URL("http://xxxxxxxxxxxxxxxx.mp4");
}
else if(NotificationProgressTestActivity.i == 2)
{
url = new URL("http://xxxxxxxxxxxxxxxx.mp4");
}
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH = Environment.getExternalStorageDirectory()+ "/";
Log.e("PATH:", PATH);
File file = new File(PATH);
if (!file.exists())
{
file.mkdir();
Log.e("destination", "created");
}
else
{
Log.e("destination", "exist");
}
File outputFile = new File(file, fileName);
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[10171188];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1)
{
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
// -----------------------
if (!outputFile.exists())
{
Log.e(outputFile.toString(), "not created");
}
else
{
Log.e(outputFile.toString(), "created");
Log.e(outputFile.toString(), "" + outputFile.length());
}
Log.e("download", "end");
}
notificationManager.notify(42, notification);
try
{
Thread.sleep(1017);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
catch (IOException e)
{
Log.e("log_tag", "Error: " + e);
}
Log.e("log_tag", "Check: ");
// remove the notification (we're done)
notificationManager.cancel(42);
}
};
download.run();
}
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
1- in this above line, the 2nd parameter in getActivity() is requestCode, it should be a unique number for each button. currently it is 0 for both buttons.
notificationManager.notify(42, notification);
2- in the above line, the notification index you are passing as 42, it should be unique for both buttons. currently no matter how many buttons you create it will never show you a new notification because you are passing 42 for each. it will keep updating the current one.
also you might need to look again the code you are doing in onHandleIntent(). there are better ways to do this.
What you need is an AsyncTask and a ListView.
Your downloadmagic happens in AsyncTask.
Make for example an Array that indicates which download is running and the progress of each running download.
Now in your AsyncTask there is a publishProgress-Method which calls onProgressUpdate.
In onProgressUpdate you have to update the respective progress-variable and call notifyDataSetChanged on your ListView Adapter.
This will cause the ListView to reload all Data.
Finally in your ListView-Adapter you got a Method getView, where you have to create the View for each row of your ListView.
There you can decide to show the ProgressBar (download running) or not.
More Information about AsyncTask can be found here: http://labs.makemachine.net/2010/05/android-asynctask-example/
And more about the ListView here: Android : BaseAdapter how to?