Android: how to run AsyncTask at regular interval in background service - android

How do I run an AsyncTask at regular interval of 2 mins sleep for 10 times in the background service?
As VM stops my service at any time, my AsyncTask is also getting closed.
I have tried ScheduledThreadPoolExecutor, Timer, TimerTask all gets stopped once Service gets stopped.
Is there a good option start with?
Any help is appreciated.

Your service will never get stopped but you should show notification. Try implementing foreground service. foreground service
Foreground service displays notification and is never stopped.
Implement this code snippet in your service
Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),
System.currentTimeMillis());
Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.notification_title),
getText(R.string.notification_message), pendingIntent);
startForeground(ONGOING_NOTIFICATION_ID, notification);

Have you tried the Handler? U can read more about this in this link

Related

Service which continuously runs in the background

I want to develop a voice application which has to respond when the user speaks some commands. I think I need a service to accomplish my task.But I have learnt from several resources that a service cannot run for a long time.The android system automatically destroys a service if it sits idle.
So my question is whether it is possible to run a service continuously without being destroyed and respond to user actions?
I am new to Android development.So if there is anything wrong in the question, please correct me.
Thanks for the help!
You can use startForeground.
Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),
System.currentTimeMillis());
Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.notification_title),
getText(R.string.notification_message), pendingIntent);
startForeground(ONGOING_NOTIFICATION_ID, notification);
They are killed only as a last resort—if memory is so low that they cannot all continue to run.
https://developer.android.com/guide/components/processes-and-threads.html
1st priority.

Is this service going to die when activity is destroyed?

I have a custom class which checks conditions and then runs MyService, otherwise it just does nothing if conditions are false. An instance of my custom class is created within MainActivity of an app.
Inside MyService: onStartCommand: returns sticky, onCreate: new thread is going to be created, in that thread, inside of a runnable the other stuff is going to be done, like creating new threads, async tasks and etc. The service has nothing to do UI except Notifications.
Is there any other ways for MyService to die except user kills it or system runs out of memory?
Service will die if user removes application from recent apps. Also, if application gets crash, service will die. If you want to run service even if low memory condition, start running service in foreground. But running service in foreground will cause a notification displayed continuously. Service running in foreground is not a candidate for the system to kill when low on memory. You can show your custom notification in case of foreground service as below :
Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),
System.currentTimeMillis());
Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.notification_title),
getText(R.string.notification_message), pendingIntent);
startForeground(ONGOING_NOTIFICATION_ID, notification);
Add above code in service class.
Even after passing notification as NULL, system will show his own notification using application default title and icon.
Check this link for more details http://developer.android.com/guide/components/services.html#Foreground

cancel Service when user clicks Notification

Similar to this post I got a service that does some work in the background. When the service starts, I'm displaying a notification. Usually you can assing an intent to the notification that is triggered when the user clicks onto the notification. Mostly an activity is then started.
But how can I use a notification to inform the background service that the user want's to cancel its operation?
You can have a BroadcastReceiver to stop the Service, which is triggered through the PendingIntent of the Notification.
Have a look at the PendingIntent.getBroadcast(...) and use it instead of the PendingIntent.getActivity() method. You can use it like this:
Intent broadcastIntent = new Intent(context, YourBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, broadcastIntent, 0);
Notification noti = new Notification.Builder(this)
...
.setContent(pendingIntent);
.build();
notification.setContent(pendingIntent);
The BroadcastReceiver could be an inner class in your Service to simply call stopService() in the onReceive() method.

How to keep a service running when it's swiped in recent tasks (Like pandora)

When I swipe my app from recent tasks, my service stops, then restarts in a few seconds. I'd like it to behave more like pandora.
When you're playing music with pandora and swipe pandora out of recent tasks, the music continues to play without stopping at all. I'm trying to implement this behavior in my app.
I saw this post: Android: keeping a background service alive (preventing process death) which seems to indicate that the way to do this was to use the startForeground method.
I copied this code from http://developer.android.com/guide/components/services.html#Foreground
Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),
System.currentTimeMillis());
Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.notification_title),
getText(R.string.notification_message), pendingIntent);
startForeground(ONGOING_NOTIFICATION_ID, notification);
And made sure that my notification id was not zero (it's 1). I also return START_STICKY. Any clue what I'm doing wrong?
EDIT: The above behavior happens on 4.2. On 4.4, the notification doesn't go away. However, the thread I'm running inside the service stops and does not restart. At least on 4.2 it restarts :/

Android Delayed Notification

I am trying to create a Notification using Android's Notification Manager, however, the trick is that I want the notification to show up 30 days in the future. In my code I'm doing this:
Intent notificationIntent = new Intent(this, MyClass.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
long when = System.currentTimeMillis() + (30 * 24 * 3600 * 1000);
Notification notification = new Notification(R.drawable.some_image, "A title", when);
notification.setLatestEventInfo(getApplicationContext(), "You're late", "Some description", contentIntent);
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify(NOTIFY_ATTEND_ID, notification);
However, the notification is still showing up instantaneously. From what I read, the "when" parameter to the Notification constructor is only used to sort the notifications in the StatusBar. Is there anyway to make the notification show up in at a future date/time? Thanks in advance.
Is there anyway to make the notification show up in at a future date/time?
No.
As Falmarri suggests, you will need to handle this yourself, though I disagree with his approach. You will need to use AlarmManager. However, I am skeptical that AlarmManager will work for 30-day durations, though you can try it. You may need to use AlarmManager for a daily/weekly task to schedule that day's/week's notifications via separate alarms. You will also need to reconstitute this roster of alarms on a reboot, since they get wiped, as Falmarri suggests.

Categories

Resources