How to Restart Android IntentService - android

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

Related

Intent service not stop explicitly

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.

Sticky Service is getting killed when user closes app from recent apps

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.

How to auto update a continuously running Android app without user interaction

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);
}
}

Download in android

I am trying to build an application in which I Am playing videos and images simultaneously. Every one hour or so the app has to download materials from internet. so to use the new materials I am trying to make it restart. I have implemented a runnable and put the code for download and restart in the run method. The problem is that the app freezes soon after start-
synchronized public void run() {
download("http://www.justieltsshaddi.com/pankaj/list.txt",
Environment.getExternalStorageDirectory() + "/alpha/list.txt");
File beta = new File(Environment.getExternalStorageDirectory()
+ "/beta/");
File betalist = new File(beta + "/list.txt");
File alpha = new File(Environment.getExternalStorageDirectory()
+ "/alpha/");
File alphalist = new File(alpha + "/list.txt");
if (alphalist.lastModified() == betalist.lastModified()) {
return;
}
try {
FileReader inAlpha = new FileReader(alphalist);
BufferedReader br = new BufferedReader(inAlpha);
String s;
Toast.makeText(this, "Starting Download...", Toast.LENGTH_SHORT)
.show();
while ((s = br.readLine()) != null) {
download("http://www.justieltsshaddi.com/pankaj" + "/" + s,
Environment.getExternalStorageDirectory() + "/alpha/"
+ s);
}
// stop the activity to rename folders
Toast.makeText(this, "Download done. Restarting...",
Toast.LENGTH_SHORT).show();
Log.d("Pankaj", "Download Done");
Intent intent = getIntent();
overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
Log.d("Pankaj", "MainActivity Killed");
// rename alpha to beta
deleteSubFolders(beta.toString());
alpha.renameTo(beta);
if (!alpha.exists()) {
alpha.mkdir();
}
File upper = new File(alpha + "/upper/");
if (!upper.exists())
upper.mkdirs();
File lower = new File(alpha + "/lower/");
if (!lower.exists())
lower.mkdirs();
// restart the activity
overridePendingTransition(0, 0);
startActivity(intent);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
any help is appreciated. thanks in advance.
I would suggest you use Aysnc Task to download the files
private class DownloadFile extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... sUrl) {
try {
//do your download
while ((s = br.readLine()) != null) {
download("http://www.justieltsshaddi.com/pankaj" + "/" + s,
Environment.getExternalStorageDirectory() + "/alpha/"
+ s);
}
} catch (Exception e) {
}
return null;
}
call the download task as below
// execute this when the downloader must be fired
DownloadFile downloadFile = new DownloadFile();
downloadFile.execute("the url to the file you want to download");
may be thinking of firing the download task in loop.
Use Service and Alarm Manager
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 10);
Intent intent = new Intent(this, reciever.class);
PendingIntent pi = PendingIntent.getBroadcast(context, _id, i, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
//for 30 mint 60*60*1000
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
60*60*1000, pi );
In broadcast reciever start the service
public class reciever extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
}

progress bar in Notification area is not closing and not starting the second progress bar

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?

Categories

Resources