BroadcastReceiver independent from app process - android

There is a state of my app in which it does nothing but scanning wifi (actually wifiP2pManager.discoverPeers). In that state it should use minimal energy but react quickly on broadcast intents.
1) Am I right that the receiver object is created before registering programmatically and keeps loaded until unregistered as long as the app's process is not killed?
2) How can I prevent the process from being killed without wakelocks which would also harm power consumption?
3) Can CPU be stopped while wifi scanning, i.e. while WifiLock is acquired?
4) How can a WifiLock can be held when a process is killed ->2?
5) Can I register a BroadcastReceiver class which will be created just when there is an intent to handle even when the app's process was killed?
Hope this is understandable. Maybe the following outline helps a bit:
Boot or app start
loop
initiate wifi scan
loop
sleep (stop CPU and release memory if possible)
process scan event (potentially calling services and activities)
until scan complete
forever
Currently I have the feeling that I need a service in parallel to the receiver to hold reference of the receiver and keep this service running all the time, but at least without wakelocks. Is this right? Or is there a better approach?
Thanks

Related

Does an empty foreground service keep an android app alive?

I'm working on an app that keeps communicating with a device by Bluetooth(ble) when it's in both foreground mode and background mode.
I know I should implement ble jobs in a foreground service in Android, but the app is written in flutter and all codes are in dart.
It seems that for now even though there isn't a foreground service, the app keeps alive in background mode.
But I want it to be alive as long as possible.
So I'm thinking about making an empty foreground service...
Will an empty foreground service make an app has some priority in background mode?
And is it ok to do so?
Thanks.
The system can terminate an application in the background at any point. In practice if there is no need for its resources, it runs several minutes maybe more.
When using a foreground service, at some point only the service will run, so there is no real use of "empty service". Closing the application manually will leave only the service running.
Yes, an "empty" Foreground Service will usually prevent the app process from being killed automatically by the system, unless the device is critically low on memory.
How the code in the service class itself looks like does not matter. The important thing is that when a Foreground Service is running in the app process, the whole process will be prevented from being killed. This means that you can have Dart threads in the same process that won't be killed. Activities belonging to the same process that are in the background can still be "destroyed" though, i.e. the onDestroy callback can be called.
Since BLE connections in Android uses the Binder mechanism which are not tied to any of the standard Components (Service, Broadcast Receiver, Activity, ...) that otherwise control how the app process stays alive, having an "empty" Foreground Service is actually a common way to keep BLE connections alive.

Android long time running service

I am working on an Android project and I need the app to work even when the device is locked.
The idea is to open the app that will start the (Intent)Service, the service processes the data all the time. The device can be locked/put away and after some time when the app is opened the service is manually stopped. The service should be running all the time in the background.
I have found information online, but I am not sure what to use and in which way..
I have found that the IntentService can be used. Also the service should run in a new thread. I need to process the data from gps all the time, should I use WakefulBroadcastReceiver?
Thank you.
IntentService is not necessarily what you want to use. It will automatically spawn a new thread just to handle an incoming Intent. Once all incoming Intents have been handled it will stop the Service. To have a long running Service, you would need to derive from Service and when it is started return START_STICKY from the onStartCommand() method, plus spawn your own thread to handle your background work.
If you need to monitor GPS, you'll have to manage that along with keeping the device awake using a WakeLock. Note that in Marshmallow, this gets more complicated because of the new Doze mode where even wakelocks are ignored.
Also, note that the way Android is architected there is still a chance that your application running the background Service may be killed. Android uses a unique process management technique based on memory pressure and user perceived priority to determine how long a process should stick around. I recommend reading up on the Service lifecycle in the documentation.
In android their is no fool proof way to ensure that your service runs forever because the LMK(low memory killer) when the system needs resources (based on a certain memory threshold) , kills the service then if it can restarts it. If you handle the restart properly the service will continue to run.
Services that are given foreground priority are significantly less likely to be killed off, so this might be your best bet. However their will be a notification of your service running the in the background on the menu bar up top. Foreground Service

Foreground sensor service in an embedded device context

Question:
What are best practices for a persistent/always-on sensor data collection service in an embedded setting? Permanently attached power source and no user to aggravate with another running service, so no battery life or usability concerns.
Plan:
A local Service, startForeground(), START_STICKY, probably acquiring a PARTIAL_WAKE_LOCK, starting on BOOT_COMPLETED. This will not be a Play Store application. I will have an activity which can bind to the service to get feedback, set preferences, and manually start/stop the service if so desired. Since this will be running on a dedicated device with no UI and will not be reliant on battery power, which should bypass most of the usual concerns with services, is there anything else I can/should do to ensure the service runs at a high priority with the least likely chance it will be killed? Is there a better option than a service implemented in this way?
Background (optional reading):
I've written a multi-threaded Activity-based app which starts via a broadcast receiver on boot completed, runs through validations, runs a data collection thread, a data transmission thread which connects to a remote service, and executes other tasks which aren't pertinent to this discussion. I need to transition to a Service-based solution. From what I've read, best practices for a service which collects sensor data usually involve periodically starting the service via an AlarmManager. This will not work in my case.
In general, there's no issue with a Service receiving sensor data. But, be sure that you are processing any data on a background thread rather than in the SensorListener callbacks. If you need to keep receiving data even when the screen turns off, you'll need to hold a partial wakelock to prevent the system from going to a lower power state. Battery life is affected with the "foreground" service only because you are leaving the sensor activated at some interval. Otherwise, there's nothing magical about a service being considered foreground, other than it has a very low chance of being killed off by the framework.
You may also need to make sure the accuracy of the sensor doesn't change (via the listener callback) and if it is different than what your algorithms expect, you'll have to re-configure it with the SensorManager. An Activity based solution won't really do what you are talking about as the Activity is only "running" when it is visible to the user.

Service shouldn't stop when the phone is sleeping, or the activity (for starting the service) is not running

I want to run a service to collect the accelerometer sensor information and it shouldn't stop when the phone is sleep or the activity (for starting the service) is not running.
I have to send start and stop commands to the service from the menu activity.
currently I am using a bundled service in the same process of the activity but the problem is that it gets closed as soon as activity is closed (return key pressed).
I am wondering if I use a separate process it will resume even if there is no bundled activity (when activity is closed).
If not, which service model should I choose?
You are probably looking for startService instead of bindService.
http://developer.android.com/reference/android/content/Context.html#startService%28android.content.Intent%29
However, even with startService, there are no guarantees the service will remain running "forever" and "always".
WARNING, the options below will consume a lot of battery.
You can increase the chances the service will not be stopped by changing the priority to startforeground (requires a notification).
While the screen is off, the only way to keep the service "alive all the time" is to use Alarm Manager with an RTC_WAKEUP or ELAPSED_REALTIME_WAKEUP schedules.
Less battery...
Practically speaking, however, without startForeground and just using normal RTC or ELAPSED_REALTIME alarm schedules, your service will run most of the time.
You can create a service in the same process with your application, even if your activities all closed, the app still work because your service still alive until you call stopservice (the system will restart your service automatically when it is killed by system). if your service perform complicated communication with activities , i think you should use remote messenger service. During running of service you can bind to service to send and receive data between service and activities.
For more information of service and communicate to service, you can refer here

BroadcastReceiver vs Service

Well, in android, what is the difference between doing something in broadcastReceiver and calling another service in broadcastReceiver? I think they both run in background,right?
Actually, what I what to do is:
In certain time of everyday, download the user event(eg: 9:00 am eat
breakfast) from database, and set up the AlarmManager to show
notification about the event.
Now I set up a alarm manager to do the above task. And I am puzzled should I directly accomplish this in BroadcastReceiver or call service in BroadcastReceiver to accomplish this.
Thank You.
You should do as LITTLE processing in a BroadcastReceiver as possible because (quoting from the Android Blog)
When handling a broadcast, the application is given a fixed set of
time (currently 10 seconds) in which to do its work. If it doesn't
complete in that time, the application is considered to be
misbehaving, and its process immediately tossed into the background
state to be killed for memory if needed.
You definitelly should call a service from the receiver for this purpose, if your action takes some longer time (connecting to the internet can take some). Broadcast receivers are limited by maximum amount of time, they have to finish.
Process Lifecycle
A process that is currently executing a BroadcastReceiver (that is,
currently running the code in its onReceive(Context, Intent) method)
is considered to be a foreground process and will be kept running by
the system except under cases of extreme memory pressure.
Once you return from onReceive(), the BroadcastReceiver is no longer
active, and its hosting process is only as important as any other
application components that are running in it. This is especially
important because if that process was only hosting the
BroadcastReceiver (a common case for applications that the user has
never or not recently interacted with), then upon returning from
onReceive() the system will consider its process to be empty and
aggressively kill it so that resources are available for other more
important processes.
This means that for longer-running operations you will often use a
Service in conjunction with a BroadcastReceiver to keep the containing
process active for the entire time of your operation.
from: BroadcastReceiver

Categories

Resources