ANDROID: access variable in paused activity - android

Let's say we have an Android app that consists of a MainActivity, and also a bound intent service (or any other background service that continues to run while MainActivity is paused).
Lets say we have some variables belonging to MainActivity, MainAcitivity.variable1, and MainActivity.variable2.
Is it safe/normal to update these variables from the background service while MainActivity is paused? I know that it works without errors, but it seems strange to me that it is possible to interact with a class/thread that is "asleep." If you send multiple updates while Main is paused, do they all end up in a buffer that gets dealt with when Main is resumed? or do the updates happen immediately?
What technical subject to these questions have to do with?
Thankyou!!

You shouldn't get used to this. simply because your Service will not be able to see your Activity's variable when the app is closed.
A very good solution is to cache the changes made by the Service in local storage, and use BroadcastReciever to update the Activity if it is running. In addition to that, the Activity should get data from the storage in the onResume() method and update the UI accordingly.

Related

Update Activity data from service when its paused

Lets say I have an activity that has a data object. It updates its gui component based on that object. Now lets say that it is paused ( OnPause is called) but not stopped or destoryed
Meanwhile , a push notification is received ( intentservice is started) and I need to update that object with the push notification object so I gui is updated when the app is resumed.
I thought about sending a broadcast to the activity so it can update its dataobject But I read somewhere that when activity is paused then broadcasts are not received.
What should I do in this case?
The hard but correct way to do this is to build your own custom ContentProvider for your app and update all data received from web services and push notifications to this ContentProvider. When the Activity comes back into the foreground, it updates itself with the new data provided by the ContentProvider.
It is hard because making a custom ContentProvider is a lot of work. It is the correct way because it is in conformance with the behavior of mobile applications and with the Android architecture: say a user activates a web-service or some computation-intensive task, and then dismisses the app; or say a push notification arrives and requires the app's data to be updated and displayed. In both cases, the app's Activitys may no longer be in the foreground, but a Service can be used to perform some non-UI operation. Now at the end of that operation, the Service makes changes to the data through the ContentProvider, and when the user activates the app again, the Activitys get their new data from the ContentProvider.
To quote the official tutorial:
Content providers are the standard interface that connects data in one
process with code running in another process.
As a developer, you should always assume that the user may invoke an app at any time and dismiss it at any time. Irrespective of whether an Activity is in the foreground or not, the app's data needs to be correctly updated and maintained.
Google's own apps use custom ContentProviders. The Gmail app in particular makes use of its ContentProvider to get new emails when network connectivity is available and display emails offline. The Facebook, WhatsApp & Twitter Android apps also make use of ContentProviders.
You pretty much treat it as if the Activity was destroyed. You can't really assume that it won't happen once onPause is called.
If the object represents something that's persistent, then simply update the persistent portion of the object and retrieve it when the Activity resumes. If it represents a state of a Service for example, then bind to the service and update. If it's a database, then update the database then refresh the Activity onResume.
If it's a temporary object that's only valid through the life of an Activity, then you need to make something persistent that the Activity can check when it resumes. Something simple like a boolean variable in the "sharepreferences". In onResume, check for the object, if it exists, then retrieve object, then clear the object.
I thought about sending a broadcast to the activity so it can update
its dataobject But I read somewhere that when activity is paused then
broadcasts are not received.
What should I do in this case?
I think the resource of that information is incorrect, if you declare a receiver in onCreate and remove it at onDestroy you wont have any problems. What I mean is, first parse the push notification with your service and then send localBroadcast to the activity. It is as simple as you thought. then update your GUI at onRecieve method of your reciever.
You should bind to the Service when the Activity starts. Then in onResume you can request updates that may have occurred while the activity was paused.
You may consider passing data to the activity through a callback to update variables in the activity while it is paused, but then you will need to update the UI in onResume.
Also consider that when your Activity is paused, it may get destroyed and re-created. You don't seem concerned with that scenario based on your question, but I thought it important to explain it. to handle any changes for this scenario, you would need to persist the data for the change. If you are persisting the data, then you don't need to bind to the Service you simply need to check the persistent data store in onResume.
EDIT:
In your comment you mention an IntentService which you cannot "bind" to. You have several options in this case (basically listed in order of preference). First, you can create a Service when your activity is created, then have the IntentService forward intents to that service. Second, you can have a Static variable in your Activity to allow the IntentService to access a shared data store. As mentioned previously, you can also persist the data (put in SharedPreferences, a file or a database. Last, you can use the Application class to store references to the data so that while your app is active, you can pass data.

want to make the service independently run

So basically what i am trying to do is i want a service that runs in background and updates the LatLong to the server. This operation needs to happen all the time even if the application is running or not.
Now when the application is launched i want the service to calculate the distance between the latlong and update the UI in addition to the work that it was already doing i.e. updating the latlong to the server. i want the service to do the additional work for multiple activities. lets say i launch the application and i am on Activity A, onclick of a button on Activity A the service starts updating the UI and when we click gain it stops updating. Now i am on Activity B and on click i want the service to do some work in addition to the updation of LatLong and update the UI.
What would be the best approach to achieve this.??
EDIT
The problem i am facing is not getting the service update the UI but making the activity communicate with the service when it has already started.
i can pass on some data when i am starting the service but how to communicate with the service when it has already started. How to tell the service that see you are already running and doing some operations now you have to perform some more operation on top of the previous operation.
I can make some static method in the service and call them when i need to perform the extra operation but i dont wanna do that.. i want to better approach.
Here is the basically services runs on the same main thread process as ui. When you want make it run continuously you have run it in your tread. In this way you avoid service being get stopped as application go in background or killed. (Please take look at Service.START_STICKY flag, this is what you need as i guess).
And more coming your second problem of activity getting updated with service information or data that is being collected for this you need look at " How Bind the service". (In activity check for service connection and Binding to a activity, Unbindibg is also there have look at it also). Activity has all the call backs for it you need to implement binder.
EDIT
Service to update ui has to have send and receive intent mechanism. You can broadcast and intent from the services check your activity is running or not. If running broadcast intent and have receiver in activity to listen it.
You can do it by interface mechanism too

Is there a design pattern for Android that defines how multiple Activites should access a single Service?

I am developing an Android data entry app that saves the entered data to a file. A Service (let's call it FileIOService) is launched using the filename, and loads and saves data that is passed to it from each Activity that the user accesses.
I am trying to make the whole app as robust as possible, and at the moment I feel I need to pay particular attention to the interaction between each Activity and the Service. Here are the issues I can see:
If the Service is killed by the system, it needs to restart and open the file that it had open: I can handle this by using START_REDELIVER_INTENT.
If an Activity is destroyed, for instance by an orientation change, it needs to reconnect to the Service.
The thing is, once the Activity launches the Service, there's a while before the Service finishes opening the file and becomes ready for I/O requests. To address this, in my Activity, I have both:
an inner class subclassing ServiceConnection, with its onServiceConnected() method completed
a private reference to an anonymous inner subclass of BroadcastReceiver, with its handleMessage() method completed. This gets called when the Service sends out a broadcast to indicate it's finished opening its file.
Both of these methods then call a setUpActivity() method that pulls data from the Service. This is where it starts to get ugly. Because onServiceConnected() may run before the file is ready for I/O, and handleMessage() might be called while the Service is not bound to the Activity, I have to make both handleMessage() and onServiceConnected() set boolean flags that can later be checked in setUpActivity(), like this:
if ((fileLoaded && serviceConnected))
{
//access the file data
}
As I said, this feels ugly and awkward, and relies on setting extra boolean variables.
There's another problem - if my Activity launches an external Activity, like the Camera app, upon returning to my app the Service and Activity may both have been destroyed (especially with an orientation change) and the app crashes.
My feeling is that I may be missing some overall pattern that would define how each Activity should relate to the Service, and vice versa, while remaining robust and able to cope with unexpected terminations/restarts.
Let's ignore the fact that I am skeptical that this is a valid use case for a service (a service whose existence is simply to read and write files?).
If the Service is killed by the system, it needs to restart and open the file that it had open: I can handle this by using START_REDELIVER_INTENT.
The service is not "killed by the system". The process is killed by the system. This will eradicate your activities as well as your service.
The one possible exception to this is if the user manually stops the service (and only the service) from Settings, in which case I have no clue what the expected behavior would be. This should be fairly uncommon nowadays, particularly for an app that the user had just been using. Users will be more inclined to use a task manager, such as swiping your app off the recent-tasks list, which will get rid of the entire process, not just the service.
If an Activity is destroyed, for instance by an orientation change, it needs to reconnect to the Service.
Not necessarily:
Bind using the Application context (getApplicationContext()) instead of from the Activity directly
Use a retained fragment to maintain the binding across the configuration change
My feeling is that I may be missing some overall pattern that would define how each Activity should relate to the Service, and vice versa, while remaining robust and able to cope with unexpected terminations/restarts.
This is one of the many reasons why I try to avoid the binding pattern altogether. Use a service for processing commands, sent via startService(), with results (if any) delivered by LocalBroadcastManager, or Otto, or greenrobot's EventBus, or a "real" broadcast Intent, or maybe a Messenger. Particularly when the service is an IntentService, the service nicely cleans up after itself when there is no more work to be done.

android continuos polling ... how?

I have an application that needs updating constantly. I would like to create a job (Service, thread ...?) that execute the polling over all the activities. I need to update some data even if i'm not on the activity that needs to.
I would not create a service because actually I don't need to update tha application along it is closed.
What do you suggest?
Thanks
a.
I think you are confusing an Activity with the data that it presents to the user. You do not mess with other activities that are not currently on screen.
If I understand correctly, you want to update some data that is shared among your activities whenever any activity is currently visible.
You could create a Service which in turn uses a separate thread to do its polling. Then in each of your activities that you want the polling to be run you call startService in the onResume method of the activity and stopService in the onPause method of the activity.
Also make sure you use returnSTART_STICKY at the end of your service's onStartCommand method.

Activity as a listener and memory leaks

I have the following framework for my application:
1. a Network thread that runs in the background (a queue) for issuing request and get async responses. The thread is started and stopped in the Application Object so it's leaving through out the whole application.
2. a DataManager which is also a member of Application and has different DataManagers for the data types i retrieve from the network. the data manager itself is the listener for the responses from the network so it's safe until the application itself dies.
3. this is the problematic part. Some of my Adapters and part of my Activities are DataListeners for my DataManagers, that means that the data manager keeps a reference to them.
When a phone call or some other phone event occurs i've noticed that the activity is usually in paused and not destroyed and so receives my events, which is ok. the problem starts when landscape\portrait is changed. since i keep a referenced to the activity in an Application bound object, the activity can't be destroyed on one hand, BUT the event is still getting to the listener, only the wrong one...
Basically i can fix that issue by removing the listener in onDestroy and retaining configuration boolean to tell me that request was allready issues and i just need to put a listener and try to retrieve the data from the data manager.
However :-) i was wondering how android handles this cases usually, if for example this was a Service running. or if the Service is a local Service that used Bound and passed on the Activity as a Listener to the network Event, the same things happen, untill the listener is not removed the Activity is leaked and lives on, but without it, no way to get callbacks from the network...
an Intent requires serilaztion and deserilazation of data which can be heavy (Bitmaps for example?)
And anywa, asuming i send an intent on each respose i get, how do i get the intent to the Activity (i know of getIntent, but if i get another one , not related, do i get it as an 'event' ?)
From what I gather it's customary on Android to remove yourself from listener lists when the activity is destroyed. It's kinda error-prone, but I think it's the generally accepted way to do it.
You could imagine your service accepts only one listener, which may or may not fit your case, and when the activity restarts its registering with the DataManager would overwrite the old activity which would in turn be garbage collected. The drawback is, you don't free the activity memory if it is destroyed but the service lives on, so it's probably better to just remove the activity from listeners.
Android development is rather different from other platforms (e.g. BlackBerry). I'm not able to give you a quick silver bullet solution, however here are my thoughts on this:
Some of my Adapters and part of my
Activities are DataListeners for my
DataManagers, that means that the data
manager keeps a reference to them.
OS kills Activities according to their lifecycle. So you should avoid keeping a handle to an Activity in another object which is supposed to live after the Activity is destroyed by OS. Otherwise you'll get memory leak.
Also keep in mind Application sublass instance does not always live for the whole application session (a session from a user perspective). If your app goes in the background, for example, due to an incoming phone call, then your entire process can be killed. See details here. As soon as you Application sublass contains some state which is not persisted if process is killed you may mistakenly expect your handles to point to some non-null entities. However after going to foreground (and process restore) those may just be nulls because a new instance of Application sublass has been created by OS.
Ok, so let me describe the problem and the solution i found in more details.
The problem:
I have a Service\Network Thread that needs to notify Activities that sent requests through it that either request or Error has arrived in an Async way. Using Listener Pattern requires me to set listener before or when i send a request like so:
mNetService.setRequest(request, this);
where this is Activity that implements my listener Interface.
But doing it this way requires me to remove the listener from the service in onDestroy and returning the listener, if i ever sent a request back in onCreate\onResume, but the response can also arrive exactly when the activity is not listening (landscape\portrait event) which requires me to keep the Error\Response in the service until some1 picks it up and resets it.
The solution i found:
using Broadcasts and BroadcastReciever.
this is only part of the solution but it let you have a listener to broadcasts (that can be specific for a certain class type meaning Activity) and action.
Since all of my Activities inherit a base Activity class i've made they all have a BroadcaseReciever inner class that listens on certain action in it's filter.
is i enable the listening in the C'tor of my Activity the listener will be registered in onResume and deregister in onPause.
If the listener gets onRecieved event it will call a method in the Activity (which i can override in my specific activty) and pass it the Intent i got which can contain all the data from the response.
The only missing part is what happens if the Activity dies for a second and only then the broadcast arrives ? ah, that's a problem, so android intorduces Sticky Broadcasts that stays there untill you remove them with removeStickyBroadcast(Intent), so when is ent broadcast from my service i send Sticky broadcast, when the Activity gets my Broadcast it removes it so it wont stay around and mislead the activity about new response that arrived.
The only problem with it is if i send a request, don't wait for the response and goes to the next Activity right away, in this case when i'll go back to that Activity it will think it got the response. Didn't find a proper solution to that just yet. But it's better then my previous solution.

Categories

Resources