android broadcasts and wake locks synchronization - android

I have a service A, which is started by WakefulBroadcastReciever from AlarmManager. Service A follows a standard pattern - performs a computation, then sends local broadcast to inform the system about the results, then calls WakefulBroadcastReceiver.completeWakefulIntent().
Depending of the results of the computation,i.e. content of the local broadcast, other local services may need to perform some computation immediately. However, am I guaranteed that the other services will receive the local broadcast at all before the device goes back to sleep?
If not, I guess another solution would be to use explicit callbacks.
Is there a standard pattern for this?
Thanks!

Local Broadcast manager has a sync mode. Beware ! The onReceive runs in the thread it is called from - not the main (UI) thread.

Related

Is it correct to call WebServices inside onReceive of BroadcastReceiver?

I've a BroadcastReciever on a separate class, i register that receiver on one of the activities, and this broadcast receiver trigger when there is an Internet connectivity. Inside onReceive() of the receiver, i execute a method for getting token from the server.
But when i gone through the documentation i found that; "When it runs on the main thread you should never perform long-running operations in it (there is a timeout of 10 seconds that the system allows before considering the receiver to be blocked and a candidate to be killed)."
Please help me with the correct way of doing it.
IMO , it is perfectly fine to call a WebService inside the onReceive method of a broadcast receiver. I have done it in many of my applications and till now I have never faced any problem.
Infact in majority of applications, which require frequent updates from server the BroadcastReceiver component is used as the onReceive method runs in the Worker thread/task.
To be on the safe side you can set your WebService timeout to less than 10 secs.Another implementation can be that you can create a background/worker thread, send it a token from the onReceive of your BroadcastReceiver and inside that thread you can call your WebService.
No, The Android System may be kills the your BroadcastReceiver, in case of in-sufficient memory. Because user never or not recently interact with the process of Application.
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.
That means A Process holds only BroadcastReceiver, then it may be considered as low priority under cases of extreme memory pressure.
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.
Intent intent = new Intent(mContext, MyService.class)
intent.setData(Uri.parse(your_url));
mContext.startService(intent);

new to android - understanding the use of the service

I have been going through this very short tutorialand I am confused as to what is the function of the service. I am also confused as to what is the function of the broadcast receiver.
I tried to do some research and here is what i understand:
- services run in the background, but... i don't understand why we need something
to run in the background to make the phone wake up at a certain time.
I "think" the broadcast receiver acts as some kind of catcher's mit, in that
when the pending intent is launched at a specific time, it catches it then
launches the service... how close am I to the truth ?
As i think that services are used for long running tasks and especially in those cases that run when your main activity is not running.
For this functionality we can use threads this make us to say that a thread is created inside our activity and it can't be active outside of the our main activity,
that is the drawback that's why we have services .
Document URL
Services can be used to run long running tasks independent of your screen flow. For example, consider your application require to communicate with a server via socket throughout its running duration, you can start a service to handle this. Imagine that against starting the socket and making connection at the start of every activity, and clean up when that activity stops.
Services by default run in the main thread. But you can start separate threads in a service context, just like you do in an Activity. If your background task can overlap across multiple activities, then it is better to start it in a Service context because every Thread/AsyncTask created retains the context that it is running. In that case your Activity will be retained even if user navigates to another activity because a thread started from that Activity is already running. If Activity is retained, it might prevent all its views, images getting garbage collected.
What Services can't do is to directly alter UI components. For that it needs to communicate with the currently running Activity context. In short, if your non UI task does overlap the life time of a particular Activity, it is better to shift that task to a Service.
What is the function of the service ?
A service is a component which runs in the background without direct interaction with the user.
As the service has no user interface, it is not bound to the lifecycle of an activity.
Services are used for repetitive and potentially long running operations, i.e., Internet downloads, checking for new data, data processing, updating content providers and the like.
TO READ: Service
What is the function of the broadcast receiver ?
Broadcast receivers are the second kind of component. Like services, they only exist in the background and don't interact with you directly. But unlike services, they can't stay running or perform long tasks: they exist to respond to events. And unlike activities and services, more than one broadcast receiver can be started in one go.
Each broadcast receiver can react straight away, for example by creating a notification, or it can start a service or an activity to take further action. As soon as the broadcast receiver has handled the event, it is stopped and will not run again until another similar event is broadcast.
TO READ: BroadcastReceiver
I don't understand why we need something to run in the background to
make the phone wake up at a certain time ?
We don't want that the application should necessarily be in the foreground to wake the phone up.
Moreover we want notifications in the background.
We started the service. Now even if we close the application, you can get the phone wake up notification. This is so useful.
Services are great to interact with a user through notifications (a way of alerting a user about an event that he needs to be informed about or even take some action on getting that information). Many a time, applications will need to run processes for a long time without any intervention from the user, or very rare interventions. These background processes need to keep running even when the phone is being used for other activities / tasks.
To accommodate for such a requirement, android has introduced the "Service" component.
It runs in the background until it stops itself. This means that a service could be keeping your phone awake (using a wake lock), running down the battery, or using lots of network data, without anything showing on the screen.
I "think" the broadcast receiver acts as some kind of catcher's mit,
in that when the pending intent is launched at a specific time, it
catches it then launches the service... how close am I to the truth ?
Correct, they are meant to respond to an intent (usually one sent by a service or a system event), do something, and be done. When an intent is broadcast via sendBroadcast, it will be sent to all receivers that have matching intent filters.
Service - is a component of android, which runs in the background with out any UI. By default service will run in Main thread only.
Thread - is not android component, but still one can use thread to do some background task. Using thread in place of service is discouraged

service implementation pattern

ok I have this application which needs to send periodic updates to a web-service, I have done a fair amount of research and I've come up with two service implementation patterns.
Implement a service with a thread, the periodic update time may vary therefore, I will put the thread to sleep with the required time-interval, then call the web-service again. I also need to update an activity, therefore will be using a broadcast receiver or a messenger.
Use a Service with a schedule timer/alarm manager, wake the system and use intent services coupled with a broadcast receiver.
Which would be the best approach?
I think I would go with the #2 option :
Create an IntentService to do the update.
Register a BroadcastReceiver with IntentFilter(s) and start the IntentService from it.
Use AlarmManager to Broadcast the registered action at the required time intervals.
I prefer this method because :
It is a very flexible pattern : You can start the service anytime by registering the same receiver for different actions like network connection changes, system boot changes etc.,
It keeps the logic loosely coupled from other parts of the app.
There is no hassle of managing threads. You get it for free by using IntentService
It is more android-ish way of solving this problem.
The main difference would be that a background service can be shut down by the user and then you won't get any more updates. If you register events with the AlarmManager, then you control when/if these events take place. If the user shuts down your app and goes into a task manager and shuts down any running services related to your app, the AlarmManager is still going to wake up and send a message that your BroadcastReceiver will receive.

Alarm manager, using wakelocks to ensure all code runs

I'm looking at using the Alarm Manager, and read this in the developer docs, which I don't really understand.
"If your alarm receiver called Context.startService(),
it is possible that the phone will sleep before the
requested service is launched. To prevent this, your
BroadcastReceiver and Service will need to implement a
separate wake lock policy to ensure that the phone
continues running until the service becomes available."
http://developer.android.com/reference/android/app/AlarmManager.html
I am specifically asking for which situations it could possible that the phone will sleep before the service is launched (as this is the part I don't comprehend)? Is it dependent on how fast the phone can execute statements? ie. it calls startService() which opens another thread and so the original thread could complete its work before the service has been made available?
Thanks
If you're starting the service from a BroadcastReceiver, you're only guaranteed that the device will not sleep during the receiver's onReceive(). According to this question, startService() is asynchronous, which means it will not block onReceive() from finishing while the service is being started. So if you need to make sure that the service starts, you have to implement your own WakeLock.

Android Service

Please explain an Android Service. How does it differ from an Activity? Does it depend on an application state such as running in the foreground/background?
From the Android Developer's SDK reference for Service:
A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use.
It is very important to note
that services, like other application objects, run in the main thread of their hosting process. This means that, if your service is going to do any CPU intensive (such as MP3 playback) or blocking (such as networking) operations, it should spawn its own thread in which to do that work.
This is in contrast to an activity which is best understood as something a user directly sees and interacts with (a UI.)
A service, as mentioned above, can be used for longer-running operations that will continue even if you have no foreground activity, but they can, and eventually will be killed by Android's lifecycle if left in the "background" state. If you need your service to continue running as a single instance without being killed and restarted, I would recommend placing startForeground(int id, Notification notification) in your Service's onCreate method and stopForeground(boolean removeNotification) in your Service's onDestroy method.
For example, I have an app that uses a foreground Service to record accelerometer data all night while the android device is next to the user's body. Though it is not required to be active, I also have an Activity that broadcast an Intent to a BroadcastReceiver inside the Service which tells the Service that it should also broadcast an Intent with accelerometer data as extras to a BroadcastReceiver inside the Activity.
Code:
SleepActivity
SleepAccelerometerService
Good luck and let me know if you need any more information!
a Service is a context similar to Activity but has no GUI.
Important: A service doesn't run in a new thread!
Read about Service and also check out How to always run a service in the background?

Categories

Resources