keep service running in background in android - android

I am developing a chat application in android . and need to keep service running
even after exit from application .
I am usin
return START_STICKY;
in onStartCommand() of my service .
but because of limitation of services in android oreo , service will destroyed after seconds when exit from application.
So far users lost new messages notifications.
I can not use Fcm beacause of local networking and no access to internet.
And I can not use ForegroundService . (because Of Employer's request to not showing any notification) .
When I checked running service in android mobile setting , there are some
apps that their service not killing like Es file explorer , Zapya , ...
How they keep their service running without foreground service .
And What should i do .
Show in blow image , some apps services are running without any notification .

Based on the documentation:
The system distinguishes between foreground and background apps. An
app is considered to be in the foreground if any of the following is
true:
It has a visible activity, whether the activity is started or paused.
It has a foreground service.
Another foreground app is connected to the app, either by binding to one of its services or by making use of one of its content
providers.
Reason Es FileExplorer can do could be (its just my opinion) following:
Es FileExplorer (is quite cheeky when it comes to taking advantage of some loop holes) have several content providers but one provider, FileProveders which is some how manages to have com.android.providers.settings connected to it. I guess this connection makes it foreground. They virtually have all the possible intent-filter registered for almost all the scheme. Anything you try to share or access, could trigger them some or the other way which keeps its process in use (you can just click on the details and you will find LocalCService of app running).
But for your app:
If you can't use FCM, ForegroundService and can't have visibility to user, then only option is to perform task periodically. You can use WorkManager. The only limitation is minimum duration for scheduling is 15 minutes. Refer to my answer for scheduling work with WorkManager and WorkManager vs Service for usage of WorkManager.

Related

Android background Service vs foreground Service

I have built an android app that performs some downloads followed by some time consuming processing. My goal here is to do the downloading and the processing in the background. I have read about background and foreground services, but I am not able to understand them properly and which to use where.
I have built the rest of the app with ionic. Now I have to make the app work in background. I have tried cordova-plugin-background-mode available in ionic but unfortunately its not maintained anymore.
So what should I do to my app in android studio to make it support background processing.
Also is it possible to combine android packages to an ionic project after building it?
Thanks in advance.
First understand about Android services: Three different types of services:
1. Foreground service: is a service that stays alive even when the app
is terminated. Foreground services continue running even when the
user isn't interacting with the app.
List of Apps:
Music player app that plays music in a foreground service
Fitness app that records a user's run in a foreground service
Navigation app, allows users to get turn-by-turn directions
Even you perform your download
Note: To download and the process in the background Google recommend you to use WorkManager.
Let's understand background work:
An app is running in the background when both the following
conditions are satisfied:
None of the app's activities are currently visible to the user.
The app isn't running any foreground services that started while an
activity from the app was visible to the user.
2. Background service: is a service that runs only when the app is running so it’ll get terminated when the app is terminated. It performs an operation that isn't directly noticed by the user.
List of Apps:
Downlead data from server
Continuously share location
Sync data with server also use workmanager
IOT Apps
3. Bound service: is a service that runs only if the component it is bound to is still active. A bound service runs only as long as another application component is bound to it. Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed.
All above apps can be bounded or not

Android 12 - Foreground service launch restrictions

I'm developing an SDK that needs to startForeground service from the background. Because it uses background location and Bluetooth-related works. If the application is killed, the monitoring is performing in the background. That's why I'm using the foreground service. There is a condition that starts the foreground service from the background.
Currently, my SDK using Service to handle this job. But Android 12 on-words it doesn't support to start service from the background.
I'm trying to start the service from the background the below exception throws.
ForegroundServiceStartNotAllowedException: Service.startForeground() not allowed due to mAllowStartForeground false
How can I use WorkManager to fix this issue, all my handling is done by the Service class and how can I pass the Service object to Worker class and start this job inside the Worker class.
Actually, my project is based on beacon technology.
and the beacon signals are used to show different recommendations to the user.
In my current implementation, if the application is killed by the user,
and also accepts the foreground service, the SDK will be run in the background.
and detect the beacon and provide appropriate actions.
My implementation is that, if the application initializes my SDK with the foreground service "OFF"
Then sometime later, when the application is in the background and trying to start the foreground service from the background this exception throws.
The foreground service-related decisions are held by the server-side API. I'm periodically checking whether the server-side value is changed or not, and if the value is changed the changed action is reflected in the SDK.
There is no one in the world that can give you an answer. The idea of all these restrictions is that we as developers need to optimize our applications. So if this is not possible for you it means most likely that you need to optimize the way you do your work. For this to happen you need to provide more info of what exactly events you are receiving, what is exactly your use case, etc.
https://developer.android.com/about/versions/12/foreground-services#cases-fgs-background-starts-allowed
As you can see there is info about exceptions for:
Your app receives a Bluetooth broadcast that requires the BLUETOOTH_CONNECT or BLUETOOTH_SCAN permissions.
But there is nothing in your question saying that your use case might relate to this.
Also, I don't understand how the app might be killed, but you keep working in the background.
Also if you want to constantly do something - why there is an event when you are in the background. Just when the user opens the app - start the service and keep it going.
You can also just "hack" it and ask the user to remove you from battery optimization.
https://developer.android.com/training/monitoring-device-state/doze-standby#support_for_other_use_cases
Earlier we were using Service to run background tasks. But, due to Android 12 - Foreground service launch restrictions, we will not be able to invoke Service for performing background tasks for Android 12+.
So from now on, from targetSdk 31, Service can be invoked only when the application is in the foreground. When the application is closed or when the application went to the background, invoking Service using startForegroundService will cause ForegroundServiceStartNotAllowedException.
So to perform background tasks, we need to use Worker instead of Service. Please refer to this answer to get an idea of how it is implemented. Hope it helps. Also, refer to the below links to get a high-level overview of what changes needs to be done.
Android 12 Behavior Changes
Work Requests
According to the official docs, if your app does one of the following, it should be able to start an FGS:
Your app receives a Bluetooth broadcast that requires the BLUETOOTH_CONNECT or BLUETOOTH_SCAN permissions.
or
Your app receives an event that's related to geofencing or activity recognition transition.
Those two seem like pretty good candidates for your use-case, at least how I understood it.

Android Using a Thread for Background Jobs

I have read many posts state that doze mode killed a running service at a particular moment e.x link or that they want to execute a long running thread.
I can't understand why you should use a service to do a background job that you know that in some point it will stop eventually.
For instance:
You could use a simple Thread:
new Thread(new Runnable).start()
and do some work in it. Using this:
In combination with a wake lock, device wont sleep and thread will keep running.
No doze mode restriction (except network but lets say we do local stuff)
So you can do background work with no restriction whatsoever. Although you should use services for these reasons link.
Is this another way (not better of course but a way nonetheless) of doing a background work? Am I wrong?
There are a lot of ways to do a background job aside of services check this link it may help you pick the best option for your work :
Job Scheduler vs Background Service
And services as #TheWanderer said will continue to work event after the app is closed for a period of time unlike a simple thread that will end immediately when the app is closed.
Read this part in the link that you linked
Services are given higher priority than other Background processes and
hence it’s less likely that Android will terminate it. Although it can
be configured to restart once there is ample resources available
again. You should go through the different processes and their
priority/important level in the documentation on processes and
threads. Assigning them the same priority as foreground activities is
definitely possible in which case it’ll need to have a visible
notification active (generally used for Services playing music).
If you are running a background thread that you start from an Activity, Android does not know that you are doing background work in the OS Process that is hosting your Activity. Android can kill the OS Process hosting your Activity at pretty much any time. If the user presses the HOME button or takes a phone call or opens a notification and goes to another application, Android can kill off the OS Process at any time. When the user returns to your application, Android will create a new OS Process and recreate all the relevant activities, but your background thread is hopelessly lost. This is the reason that Android has services.
If you start a Service to perform your background processing, the Service will also start background threads, but these are controlled. Your Service tells Android what to do if it kills the Service while it is processing an Intent. Your Service can therefore be informed and restart (or continue) the background processing as necessary. You can also run the Service in a different OS Process from the OS Process running your activities. This will prevent Android from killing the Service if the user removes your app from the list of recent tasks.
With newer Android SDKs there are other mechanisms you can use, like JobScheduler.

What exactly does change for my app in the background when it uses a service?

According to the Android developer website https://developer.android.com/guide/components/fundamentals.html
A service is a general-purpose entry point for keeping an app running in the background for all kinds of reasons.
And on several occasions, i read that a service is (also) used as a means to tell the system that the app requires doing some work in the background.
What is the difference in my Application object creating a sticky service and starting it and it creating a POJO that does the same work?
When the app enters the background (home button) how does the existence of the service change how the system treats my app? Will the service (which runs on the main thread) cause the system to schedule my main thread higher or not reduce it a priority while in the background ? Will it do so if there is no service but a POJO doing some work?
Neither will receive any notification of my app entering the background or coming back to front, neither will be connected to any activity (but could provide functionality for activities to connect to them).
So how exactly does the use of a service change how the system treats my app when it is in the background?
Somewhere it was mentioned that if there is a service running the app will be restarted should it be killed for any reason, however, the service will be killed along with its process (we are talking about a service running in the same process as the rest of the app) but this does not have anything to do with "running in the background" as the android guide mentions.
In addition, the Application object could bind to a service, holding it like a POJO. What would be the difference here, regarding how the system treats my app in the background?

Execute code on location changes if app not running

I'm writing a small android app that need to execute some code when the devise change location.
I was wondering if it is possible to execute code on location change even if the app is not running (not background but stopped).
I mean, is there some system services that "wake" (or launch) my app (or a specific activity of my app) when lat/lng changes?
Until now I've create a locationManager, set some criteria, a provider and set the requestLocationUpdates. This is working but if the app is not running I got no update.
You need to create a Service that is notified of the updates. Services run in the "background" even when your app is not running.
This can get complicated since when a user is in your app, if you expect the app to update, then the activity will need to bind to the service.
Here is a tutorial:
http://www.vogella.com/tutorials/AndroidServices/article.html
And the official docs are good too:
http://developer.android.com/reference/android/app/Service.html
Be careful - services can be shut down by Android when memory runs low. Users can also "force stop" your app. Don't assume that it is ALWAYS running, but you can assume it runs most of the time.
And pay attention to the Service Lifecycle - it's different from and Activity:
http://developer.android.com/guide/components/services.html#Lifecycle

Categories

Resources