Run service frequently also after app was closed - java

For my app I want to fetch data from a server in the background. When the user wants to be notified about specific changes, I want my app to keep fetching data even when the app was closed. I was researching about this topic and found out that the possibilities of running services continuously also after the app is closed changed with Android Oreo. What I don‘t see are the alternatives to handle running services in background with newer versions of android. The most proposed solution I saw is using a Foreground Service. But since I don‘t have any user interaction, I don‘t think this solution fits perfectly. Also I read about the WorkManager but unfortunately it has a minimum time interval of 15 minutes. Are there other alternatives to process data in the background continuously than a Foreground service and a WorkManager?

You don't need "user interaction" to have a Foreground Service, what you need is a Notification that cannot be removed while the service is in foreground.
If your notification Context is the service itself, tapping on the notification will take the user to the "settings" where he/she can force close the service for example).
You can start your FG service in a BOOT_COMPLETED broadcast receiver. You have to quickly (5 seconds or less) send it to Foreground or android will throw an exception. Unfortunately, there's a bug which Google thinks it's ok and closed as "won't fix" but you'll still need to work around.
Long story short, have an onCreate in your service:
#Override
public void onCreate() {
super.onCreate();
final Notification notification = createNotification();
startForeground("SOME_UNIQUE_ID", notification);
}
You get the idea (the createNotification() is whatever you want to create a Channel (if O+) + Notification.
HOWEVER, all this is nice, but it will have a service running all the time, which is probably not what you should do.
You can use an Alarm a trigger a more efficient (in terms of scope) Intent Service to do the job, schedule another alarm in, say 5 minutes, and do it again.
Or -as commented- you could use Firebase, and Notifications to react to a change.
All in all, those are the options.
I'd say that unless you truly need "real time" updating, the 15 ~ of WorkManager is usually fine, if you can deal with the fact that you have to design your code to be very independent, because WorkManager cannot receive much information and it's a pain to use for some things...

Related

how to perform long running operation using foreground services in android

When I used foreground service then when I kill the application then foreground service is automatically killed but I want to alive foreground service when the application is killed. this issue appeared in android 10 and android 11. how to solve this issue.
You can't do that as you should not be able to keep alive a foreground service after the application is killed.
You should only use a foreground service when your app needs to perform a task that is noticeable by the user even when they're not directly interacting with the app. If the action is of low enough importance that you want to use a minimum-priority notification, create a background task instead.
If you what to have some background service working, that will be possible.
You can find some useful information here :
https://developer.android.com/guide/components/foreground-services
https://developer.android.com/training/run-background-service/create-service
It should not get killed. When starting foreground service you need to create notification too. You have done that, right?
If you done everything right there is possibility that you have xiaomi phone. Xiaomi deletes everything when app killed. You need to add specific intent protection...

Looking for a proper solution for a case which requires: Service, Timer, GPS, Notification, Activity

In my Android application I have this scenario:
An activity starts a service.
The service needs to run in foreground.
That's why I've created a notification.
When the service starts, will start a GPS class.
At each second, the service will retrieve data from the GPS class and update the notification text. And also broadcast to the activity that data.
To check at every second, I need a task repeater.
The current code fails probably because of the performance.
The last message I got was !!! FAILED BINDER TRANSACTION !!!
This service can work up to 5-8 hours.
Most of the time the app fails after 15-40 minutes, so is quite slow to debug it.
Is there any proper solution for this case?
The story is long, but I'll try to simplify the answer.
Just for future reading.
I solved the problem.
I've used a simple Service, a foreground sticky Notification, a Handler, a BroadcastReceiver, a TimerTask, and of course a GPS class.
The issue I had was caused by the fact that the service was updating the notification every second and the app was using too many resources for that.

How to send notification even if app is killed

I am working on an Android project that has a part which dose this:
1) the user enter a data from a data field and save it in a text file
2) the app should send notification even if the application is killed by the os, at that date, the one wrote by the user.
For example:
I write 31.01.2015
The app will notify my only on 31.01.2015 even if i don't open that app anymore.
The question is how do i have to do this?
Thanks!
It sounds like you want a notification to be posted to the notification bar.
If so I advise using an alarm.
However, chances are if this is days in the future, the phone may be shut off. So you should store when the alarm should go off, create a Broadcast receiver for the on boot complete event (this requires a permission), and re-setup the alarm when the boot is complete.
This should allow the notification to appear, independent of the apps life-cycle, as long as the app is not uninstalled.
Note: You will have to calculate the milliseconds between the date for the alarm, and the current time. Calendar should help.

Is it possible that the service still runs after the app got killed with task manager?

Hello im triying to run a service in background that it doesn't stop when app is destroyed by task manager. The idea of the service is verify every "x" min if there a new insert in a database that i got in a server.
The service is running great even if i close the app but when i use the task manager to destroy my app all the threads are closed too.
So i want to know if its possible to run a thread that ask in background forever unless user cancel it in the app itself, that ignore the destroy caused by task manager so in the future i can use notification bar to tell the user that a new insert happened in the database.
Tryed:
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
askServer(); // i made a timertask that ask every "x" minute
return START_STICKY;
}
As i read START_STICKY should run again the service if it get killed for some reason and i know that this can be done since some app get closed by taskmanager and still get notifications from it as whatsapp,bbms and others. Please tell me if im wrong in anything and thank you for reading!.
UPDATE: Im not trying to break any law or security rule from Android and im not trying to ignore the stoping services option from an app in settings. I want that the service that listen for new incoming "events " inserts in my case keep running after user used the interface that appear when you press home for a while :
UPDATE : sorry for talking to much about this app but is the one that i can use as an example. In whatsapp when i close the app by the interface that i showed above the process and services are killed but after a couple of second they relaunch, this is exactly what i want to do to keep user informed about database events. From setting you still can stop the service without problem or even i can put the option in the app itself to stop notifiying.
Is a bad implementation call in OnDestroy() method an instance of the service so it relaunch after destroy?
UPDATE : welp looks like my service is still running on background after i close the app. I will just have to work on my service design to not waste battery life and resources. Also i was using the log.i() to check if service was running, looks like when main process closes i can't use log or toast just notifications ( still not implemented) because the service is there running just won't show in log .
UPDATE : now is working using using startForeground(0, null). In future i will send a notification to show when a event on database happen building it and calling startForeground(1, notification).
For services, look at Settings -> Applications -> Services. and see if it is running.
However, poorly designed services may run more often or perform syncing operations. So yes it is possible.
I had a problem similar to this when developing my first android game; force-stop was the only way to kill it.
START_NOT_STICKY will kill the background service when you swipe the app away from the task manager. START_STICKY is, as the name implies, "sticky", Meaning it sticks to the android system even when the app is gone.
That's from my experience, anyway.

How to force an application to stay open?

I have seen apps like Lookout, JuiceDefender, and MagicJack run in the background indefinitely, unless force closed by a user directly through the task manager. (And even then, in Gingerbread, it wouldn't close unless you browsed to the application that was running under "Downloaded Apps" in the settings and force closed it once you were at the menu where you have options to manage the app like "Clear Memory" and "Force Close".
I am wondering how this is accomplished? I need to do something similar for an app of mine but I don't know how to avoid the Android OS's automatic task killing.. And don't say it's not possible because if that were true, JuiceDefender, MagicJack, and Lookout would not work.
What you can have is a service that stays alive indefinitely. You achieve that returning Service.START_STICKY on your Service's onStartCommand method.
Whenever the os needs resources and chooses to kill your app, your service will be respawned as soon as the resources are available again.
Bear in mind that having an application that is continuously alive will result in consuming the phone's battery. You should (at least) notify the user with a notification that your app is still alive in the background.
On top of that, you can register a broadcast receiver for the BOOT_COMPLETED event in order to restart your service while the device gets restarted. Yet, bear in mind that this could result in eating the phone's battery and so be careful on what you are doing in the service.
I believe these apps are launching a Service when their Activity get started (i.e when onCreate() is called).
A Service keeps running when the application get paused. When the Service is launched, you may return START_STICKY in your onStartCommand.
Also, to prevent a Service from being killed by Android's memory killer, you can specify that your Service is important to the user by calling startForeground(). Android Developers website states that :
A foreground service is a service that's considered to be something
the user is actively aware of and thus not a candidate for the system
to kill when low on memory.
I am creating an app and I have to use one or more of the following super functions inside OnCreate():
onDestroy()
onPause()
onResume()
onSaveInstanceState()
to close an app completely from the memory. And also do not use Activity.finish() method. Usually Android does a pretty good job in closing the app when memory is needed, called pop out of stack and not recommended to forcefully stay in memory, unless there is a very very good reason to. Hope it helps.
You can also check the Android DOC website for more information and examples to your request.
You need to start a service. Services runs in background and is useful to push alerts.
This some links about it:
http://developer.android.com/guide/components/services.html
http://www.vogella.com/articles/AndroidServices/article.html
In the service onStartCommand method return "START_STICKY".
http://developer.android.com/guide/components/services.html
/Thomas

Categories