How to take action everytime user starts/stops app regardless of the activity they're on - iphone

I'm in the process of porting an app originally developed on iOS to Android. I'm trying to accomplish the following:
every time the app is started, call the start() method on a Manager class
every time the user leaves the app, call the stop() method on the same Manager class
every time the user comes back to the app (resuming from idle), call the start() method on the Manager class
The so-called Manager class handshakes with a server on the Internet and needs to do a variety of book-keeping activities every time the user the user enters and leaves the app.
Whereas iOS enables you to subclass the UIAppDelegate class and have code that runs when the app starts, ends, or resumes from idle, it seems Android doesn't have an equivalent approach. Instead, these are the options with Android:
1) Activity class: methods for every time an Activity (view) is created, stopped, or resumed
2) Application class: onStart and onDestroy for every time the app is started or killed
3) Service mechanism to create a background task that can be used to perform long-living operations in the background while the app is active or even while its not active
None of the above align real well with what I'm used to in iOS. Option 1 would require every Activity in the app's view hierarchy to have code that runs when the app starts/stops/resumes. Of the 3, I sense option 3 is more relevant. I'm just not entirely clear how I could start/stop a service in Android as the user starts/stops/resumes an app without regard to the specific activity they're on at the time.
I would appreciate input from Android developers or developers that work on both iOS and Android.

The so-called Manager class handshakes with a server on the Internet and needs to do a variety of book-keeping activities every time the user the user enters and leaves the app.
This might be a valid design pattern on iOS -- I have no idea. It is not a valid design pattern on Android. You don't "leave the app" on Android any more than you "leave the app" in a Web app. "Leave" is determined mostly as "you didn't come back in a while" in both Android and Web apps.
2) Application class: onStart and onDestroy for every time the app is started or killed
Note that the method is onTerminate(), not onDestroy(), and it actually never gets called. The Application object is created when the process is and lives until the process is terminated outright.
Its just not entirely clear how I could start/stop a service in Android as the user starts/stops/resumes an app without regard to the specific activity they're on at the time.
You might elect to use a service for doing the "handshaking" -- in fact, that's probably likely.
However, there is nothing built in for "leave the app". I would strongly encourage you to simply get rid of the concept entirely.
If not, you're welcome to rig up a service that is notified on each onPause() and onResume(), does the bookkeeping to see if there are any live activities, and if there hasn't been for X period of time, does your "leave the app" logic, then shuts down. You'd also trigger the "leave the app" logic in onDestroy(), if the service is shutting down at OS request vs. your own shutdown request. This is not 100% guaranteed to work -- users can force-stop your service and the OS can kill the process with impunity.

If you want to avoid duplicating code in all your Activities, why not have 1 subclass of Activity with the common code, and have the other Activities subclass that?
You can track activity lifetimes using a variety of mechanisms, including setting/clearing SharedPreferences in onPause/onResume, or use a singleton with reference counting.
Hope this helps,
Phil Lello

Related

How to make LAUNCHER activity be started instead of activity on top of activity stack after process is killed by OS?

Hi I have looked for this question and can’t find it, so here goes...
My application starts with a sign in activity which logs the user in. Upon successful authentication, the initial launcher activity is replaced by a ‘content’ activity.
Everything works fine until I place the app in the background via the home button and start up some memory consuming applications.
Upon returning to my app, Android tries to recreate the activity on the top of the activity stack, however what I’d like is to have the signin activity be restarted instead.
The reason being that the user needs to be reauthenticated again due to inactivity in communicating with the server.
Is there a way of specifying this behavior in the Manifest.xml file or programmatically?
I’m aware of save/restore activity state, but in this case I want the app to restart with the signin activity, thus bypassing needless restore. (Since the user will have to be signed in again due to inactivity)
Thanks for the help!
UPDATE:The issue arises solely when my application process is killed by Android to reclaim memory to be used by other apps that are being loaded. The only aspect of my app that still exists at that point is the activity stack and its top entry is my MainActivity. This is because the activity stack is NOT inside the app process.
So Android is attempting to be nice to the user and it tries to restore the state of my MainActivity. However my ability to authenticate against my server is gone at that point because the user’s credentials have been wiped from memory together with anything that used memory.
Therefore instead of attempting to restore my MainActivity under these conditions, I’d like my app to start at the activity which is designated as the LAUNCHER activity in the Manifest.xml file. This activity implements the signin process which gets credentials from the user and sets up various singletons whih are not tied to any specific activity. NOTE: I don’t want to persist credentials or cookies for various reasons, so that is not an option.

iOS chat-app: How do I notify the user that the app will not function anymore if the user leaves the app?

I'm developing a chat-app for iOS that must use an existing server API. The way it works is pretty straightforward: the app checks every given interval whether there are new messages on the server and displays them, plus, it sends the server new messages that the user typed.
When the user starts 'multi-tasking' or presses the home button, my app will go to the background and therefore will not be able to check the server for new messages. The server will automatically assume that the user stopped the chat when a certain timeout has been reached.
Often, the user isn't aware of the fact that when the app is put to the background, it is unable to maintain the connection to the server and will stop the chat. I'm looking for a method that will notify the user of this behavior as soon as the app is put to the background.
My current idea is to notify the user when applicationWillResignActive and/or applicationDidEnterBackground is fired, but I wouldn't know in what way. Can it be done in a way that complies with Apple's guidelines?
I'm aware of the fact that the best solution would be a different overall design of the software (e.g., using push notifications and no server-side chat termination by timeouts), but in this case I can't change that.
I would continue running in the background and set an expiration handler block (called by the os when you app is REALLY killed) and there schedule a UILocalNotification
use
- (UIBackgroundTaskIdentifier)beginBackgroundTaskWithExpirationHandler:(void (^)(void))handler

Keep infomed for Device location will Application in Backgroud

I'am developing an application that keep a WebService informed for device location each 5minute (for exemple) :
So when the application leave the foreground execution and enter background I have to lunch a timer who
1 - Update the device location
2 - Send the location to a web service
How can I perform this action ? Or do you know any code exemple that I can follow to achieve this design ?
Thank you for your help !
Doesn't look like anyone gave you a solid answer, so allow me.
There is no iOS approved way of running a 5 minute (or any minute) timer in the background (unless your app is VOIP or music). What you CAN do is register your app as requiring location services in the background (edit the info.plist and add a key Required Background Modes and then add a value App registers for location updates. What this means is your locationManager:didUpdateToLocation:fromLocation: method and corresponding region monitoring/SLC methods will fire on location change, but Timers will not work at all.
The reason why is that timers require a run loop (a thread executing code) to be running and must piggy-back on that thread, but when the app is in the background even when executing code from the LocationManager, the run loop that executes the code almost always finishes before your timer would go off.
Hope this helps!
you cannot do this (on iOS).
(unless your app requests permissions that are meant for Navigation apps)
Hello #Aladdin Gallas,
I have developed a simple application that supports background location updates for iOS and Android in Xamarin.
The app pushes a new location every 2 seconds (you can change it to 5 minutes if you want to).
There is a feature I haven't been able to add; it is to keep the service up when the user closes the app (for iPhone). Other than that, as long as the app is open, even if the phone is locked, the service keeps running.
You can take a look at the application as a reference if it helps.
GitHub Repo

Could iOS Kill an App in the Background?

While the device is powered on, is it possible for iOS to automatically terminate my app (calling applicationWillTerminate:) while it's in the background?
I'm also curious what happens in two other cases, three in total:
Device is powered on
Device is powered off
Device loses battery
I'm asking because I want to know how often applicationWillTerminate: is likely to get called. I want to know this because that's where I'm registering for remote notifications. And if there's a failure sending the device token to the server, I want to know how likely it is that that method will get called again (i.e., retry sending the device token to the server).
If your application supports multitasking (the default for anything linked against iOS 4.0+), this method will almost never be called. The documentation says it may be called in cases where the application is running in the background and the system wants to terminate. However, in my experience, I've only ever seen this actually called when running a music app that's actively playing music in the background and the system is jettisoning everything. In cases where I have background tasks running (not music, but short-term background tasks), I've seen the app terminated without this method being called.
I wouldn't ever rely on this being called and try and do all the clean-up you need to do in your delegate methods for transitioning into the background and your background task completion blocks (which do get executed for at least a few seconds before the app gets jettisoned).
Not only can iOS terminate your app automatically, but the user can kill it manually. In fact, the only time the user can kill your app is when it's in the background. Furthermore, when your app is "in the background" it's more likely to be suspended than actually running, so don't count on doing a lot of processing when you're not the foreground app.
As for how likely it is that you'll get -applicationWillTerminate:, that'll depend on the user and how they're using their device. You should handle it appropriately when you get it, and go about your business otherwise.
When memory is running low, iOS can shut down your app, calling applicationWillTerminate.
The docs say this about the method:
... However, this method may be called in situations where the application is running in the background (not suspended) and the system needs to terminate it for some reason.
Check out iOS Developer Library : iOS App Programming Guide : App Termination.

How to run a ~30sec process in the background every hour (iphone app)

I have an iphone app that has a 30second process that does some network IO. Basically, while the app is in the background, i want this process to run every hour (actually once a day, but if it fails i want it to re-run in an hours time).
With the background features of ios 4, is this possible? If so, how? What are the limitations that i'll come up against?
Thanks so much!
Take a look at Apple's documentation about running code in the background.
http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/BackgroundExecution/BackgroundExecution.html
There are few different ways of approaching backgrounded tasks. The only apps that can have fully backgrounded processes are "audio", "voip" and "location" apps, and this needs to be declared in the Info.plist.
If your app is not of this type, you'll probably find it difficult to do what you want easily. There are methods which allow you to keep your app alive in the background for a finite period of time (also at that link), but eventually your app will be shut down.
Local Notifications will only prompt the user to open the app - do you really want to have an alert pop-up on the phone every 30 seconds?
I was making some kind of similar research, have a look at this SO answer in case you didn't manage to find it before. Applications like DataMan or Data Usage must have some sort of periodic code execution in the background, so I'm not 100% convinced that what you're asking for is impossible..
I believe that Using Local notifications will help....
check following....
http://developer.apple.com/library/ios/#documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/IPhoneOSClientImp/IPhoneOSClientImp.html#//apple_ref/doc/uid/TP40008194-CH103-SW1
An application can create and schedule a local notification, and the operating system then delivers it at the schedule date and time. If it delivers it when the application is not active in the foreground, it displays an alert, badges the application icon, or plays a sound—whatever is specified in the UILocalNotification object. If the application is running in the foreground, there is no alert, badging, or sound; instead, the application:didReceiveLocalNotification: method is called if the delegate implements it.
The delegate can inspect the properties of the notification and, if the notification includes custom data in its userInfo dictionary, it can access that data and process it accordingly. On the other hand, if the local notification only badges the application icon, and the user in response launches the application, the application:didFinishLaunchingWithOptions: method is invoked, but no UILocalNotification object is included in the options dictionary.