Android Activity in background - android

I have a question in android.
If my activity class interact with external library. This library which I'm working on it has to do some processes when the application go into background or when it returns to foreground.
Is there any way to know when the application enters the background.
NOTE: I don't want to do anything in the activity. I don't want to send callback to the library when onPause is invoked.
Thanks

If I understood your problem, you could use Application.registerActivityLifecycleCallbacks and implement your own Application.ActivityLifecycleCallbacks.
Something like:
class myActivityLifecycleHandler implements ActivityLifecycleCallbacks{
// Methods implementation here
}
yourActivity.getApplication().registerActivityLifecycleCallbacks(new myActivityLifecycleHandler())

You may write in some file when application coming to background.
Then your library may time for time checks this file.

Application.registerActivityLifecycleCallbacks is indeed the correct api that you want to use. Unfortunately it is indeed API14+, so you have the following option:
use this library to implement the activitylifecycle callback. You will have to extend your activities in the application you are working on, but something must be done to then no matter what as you need less than API14 support.
With this library implemented, you can create an int count in the callback. This count can be incremented and decremented every onStart() and onStop() callback for each activity.
The count will go from 0 -> 1 on app open, and 1 -> 0 on app close/background. When these conditions are met you can do calls to your library.
Remember that when you background your app the OS can kill it off any time. If you have any amount of networking or anything long, start a service to handle it all as quickly as possible.

override onPause method of activity, onPause is called when activity is going to backgroud

Related

Android - Application onCreate method - does it ALWAYS get called first?

I am preparing new version of one of my apps, and I made such huge changes in my app, that I need to do some data conversion exactly after update of app as absolutely first thing (before doing anything else). I figured out, that best place to do it would be in my class (which extends Application) in onCreate() method. I tested it few times, and it seems to work ok, but then I read documentation:
Base class for those who need to maintain global application state.
You can provide your own implementation by specifying its name in
your AndroidManifest.xml's tag, [b]which will cause
that class to be instantiated for you when the process for your
application/package is created[/b].
It looks like I am right, but I am not quite sure. Can you confirm/disprove it?
The Application constructor will be called first. Then the Application::onCreate() method will be called. The only exception I know of is if the Application contains a ContentProvider, it can receive calls before the Application does.
This is from here: http://developer.android.com/reference/android/app/Application.html#onCreate()
public void onCreate ()
Added in API level 1 Called when the application is starting, before
any activity, service, or receiver objects (excluding content
providers) have been created. Implementations should be as quick as
possible (for example using lazy initialization of state) since the
time spent in this function directly impacts the performance of
starting the first activity, service, or receiver in a process. If you
override this method, be sure to call super.onCreate().
Yes, that is right. You should do all your initial app configuration in the onCreate() method of the Application.
Besides if you use sqllite you can make migration in onUpgrade method of the SQLiteOpenHelper.
http://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html
I have not tested it, and maybe there are some more relevant options out there, but for the upgrade the following looks promising: SQLiteOpenHelper.onUpgrade( SQLiteDatabase db, int oldVersion, int newVersion ).
So you can hang your update routines on that. The method you override should fire only when the database upgrade is needed.
Yes. The application onCreate method is the first method that is called when the process is started. you can put your code there without any problems.
here the documentation http://developer.android.com/reference/android/app/Application.html#onCreate()
Called when the application is starting, before any activity, service, or receiver objects (excluding content providers) have been created. Implementations should be as quick as possible since the time spent in this function directly impacts the performance of starting the first activity...
be careful to make all the changes very quickly and be sure that you call the "upgrade" method only once.
Consider also the possibility to put this method in an AsyncTask, if its possible.
No it dosent..say you have activity A(launcher activity) and B...when you launch your app ...A loads starting from onCreate()...and say u started activity B, then it launches B and its onCreate method is executed..but now if you navigate back to A..it will call th onResume activity and not the onCreate..

How to handle the background to foreground thing in android for all activities

Actually I am connecting with my application server each and every time when my application is coming from background to foreground for checking the session validity no matter on which activity user is currently on.
So What I did I have created one boolean type preference and setting up it true in to onCreate() method of activity and checking it on onResume() if it is true that means the application is coming from onCreate() which indicate the first time launch of activity so I am not running the set of code for validation and at the same time I am setting up that preference as false .
So if the application is coming from background to foreground the code will execute and check the validation of session.
But I feel it very messy when I am adding activities to my application each and every activity i need to take care of all these stuff not feeling it as a standard way of doing the same. Is there any function provided in Android which can help me out and fulfill my requirement ?
If not what should I do in the code level so I need not to worry about all these thing while adding the activities in my application means suggest some good way to achieving the same.
Consider creating a BaseActivity that will handle all the initialization and checking stuff that all activities should do. Now let all your activities extend the BaseActivity, instead of directly extending Activity.
This way if you'll need to add a new activity, the only thing you'll have to do will be to extend BaseActivity.

How to know when an application finished?

I need to know when an application finishes to stop all the local services that it starts.
How can I do it?
You could try using onDestroy() (not recommended, though) to know when Android is cleaning your app from the memory. or can also use onStop() to know when the Activity is being sent in the background.
Do implement these two methods in the first activity of the Activity stack.
Lets see if it helps, since I also haven't tried it so far.
One idea is to use BoundService despite the fact that it's your app own service. By definition Bound Service stops when the las connection is dropped.
Another idea would be to define count in Application object (you can override global Application object). You can increment the count in each onResume and in decrement in each onPause.
You could use try / finally on the main function and do the service clean up in the final block
You could use object finalizer to issue shutdown commands. You wont know exactly when it happens since the Garbage collector will run at its own pace, but you do know it will happen eventually.
I am now solving the same problem, I have an Idea and will implement it:
1.static variable called (String currentShownActivity).
2. in every Activity (onResume() ) I fill the variable with activity name). So when I navigate between the activities the currentShownActivity variable changed and carry the current activity name.
3. on every onPause(), set flag that indcate the activity onPause() called (i.e boolean IsPauseCalled)
4.in onStop () check IsPauseCalled, and the activity name.
if the activity onPause called and the name in currentShownActivity not changed (that mean we leave the activity to "no activity") and that mean [home] key pressed.
the integration way to know the the application is not running Check onDestroy of the main activity.

Application pause/resume state

My question is can i get to know when the entire application gets paused/resumed start/stop etc.
For example if i have 5 activities in my application. Whenever any activity gets paused/resumed android notify the activity by calling the onPause/onResume methods.
So there are two possible scenarios when my activity gets paused.
1. My activity-2 gets paused because my activity-3 gets invoked.
2. My activity-2 gets paused because of some outside activity like incoming call.
Here I am interested only tracking when my activity gets paused by outside activities not my own application activities.
So is there any android provided solution for this or do I have to write my customized solution.
Thanks
Dalvin
There is no solution provided by the API because it is not needed in most cases.
What you can do is to create an abstract activity and make all your activities inheriting from this abstract one.
In this abstract activity, by overriding onCreate, onResume, onPause, onDestroy, you can manage to count how many of your own activities are "alive", and then determine the state of your application.
This could work but it's not really the Android phylosophy
You can know the starting of the whole application on application.oncreate() but there is no indicator for the whole application pause. Most of the cases never needs it anyway.
So further read in the activity lifecycle and the application class.
Still you can do this option in your program by overriding the onPause in each class and save a value to the sharedPrefrences then check on this value all over the application
If I understand your question, you want your app to be able to distinguish between exiting the current activity within the context of your program or by an external event like a phone call. I have used the following method in the past to do this (although it may not be the best, it definitely works):
(1) Set up a value in SharedPreferences (the built in file for storing a program's data). Call it something like "exitStatus" which is set to 1 for an exit within the program code and 0 for an exit based on external events.
(2) Now, within each of your activities, set the value of exitStatus to 0 in onResume (which is called no matter how you enter). If your program exits due to an external event within that activity, this value will persist when the program is reloaded.
(3) At the end of your activity, at all points where you are going to transfer to another activity, first set exitStatus to 1. Then, when you arrive at the other activity, it will know that you arrived there from within your program.
(4) Thus, just to be clear, each of your activities can check exitStatus at the outset to see whether you are entering from within your program context (= 1) or after a non-local exit of some kind (= 0).
That's all there is to it. I use this method to be sure that load data for my app is present as it may be lost if a user turns off their device so that the app tries to pick up in the middle of things when they later reboot, etc.
Instead of making base activity and override onPause/onResume you can use
registerActivityLifecycleCallbacks(Application.ActivityLifecycleCallbacks callback)
where you can handle these states for application activities in one place.

How to run callback on application launch?

I know Android's Activity model is a bit different from what I usually consider to be an "app".
I want to do something (in this case, check some notifications on a server and show them if available) when my app is "launched". What is a good way to accomplish this?
I likely don't want to do it in an activity's OnCreate, since each activity can be created any number of times - the code would get called more often than necessary.
The app also has multiple entry points - would I have to duplicate the check in each activity?
What I'm thinking of doing is setting up this code inside the Application object, along with a flag that tracks whether it's already been called - and just call it from each Activity's onCreate().
Is there a better or more "proper" way to do this?
The right, Android-approved way to do this is:
Create your own android.app.Application class
Override the onCreate method
In the AndroidManifest.xml, change the android:name attribute of the application element to the name of your class
Now, whenever your app is "started" (any one of your activites is started for the first time and no other instances are alive) onCreate will be called.
You may also find the onTerminate method useful.
Can you just check if the bundle passed to onCreate() is null?
It's not null "If the activity is being re-initialized after previously being shut down..."
There's probably no harm in putting it in onCreate; the Activity is really only destroyed when the OS needs the RAM for something else, not when the user goes to another app.
EDIT: You can also have a Service that runs when the device gets booted up, too. This might be a better option if you also want to check when the app starts, since you'll only have to call context.startService from the Activity to run the check. Just be sure to stop it when it's done if you don't need it to be persistent.

Categories

Resources