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..
Related
In the sample app fetch method is called in onCreate(). Is it really a good place to do this? The application can be used (moves from foreground to background and vice-versa, opens new activities and going back to main activity) for weeks and onCreate() from the main Activity won't be called again. I don't think it is good solution where my app won't update my configs for such a long time.
Update:
It is very bad idea to fetch config values only in onCreate() method, some kind of check should be done in onStart(). Here is also some useful information: https://firebase.googleblog.com/2017/01/firebase-remote-config-loading.html
The link you shared shows example for demo purpose. Ideally you should do initialization in onCreate() and call for data in onStart() when onResume() gets called, the activity is visible and user can interact with your app.
As said by #Doug Stevenson in comment that there is no obligation, but you should follow what is given in docs for best practice.
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
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.
The life cycle of an activity is documented in many places but I couldn't find the thing I need. This is my activity, it have a constructor and the onCreate method. In my project I have also a logging in this methods and every time when I go from portrait to landscape I see that both methods are executed. Why my the constructor is called ? isn't the activity in the stack and the instance of my activity is in the memory so when the configuration change is happen, then only the oncreate and on retainistancestate should happen (of course the onResume). Why the constructor is called every time, who is calling ? Is it every time when something get changed from the configuration both methods are guaranteed to be called (one after another, in this same sequence).
public TestActivity()
{
super(R.menu.main_menu, tag);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
I was playing with my sample app but I want to know more details, can someone clarify me the scenario when the constructor is included ?, I founded a a lot of documentation about life-cycle but none explains the details when the constructor is included
Edit1:
I read in some places that there is stack in witch the activities are putted in so the next time they go up and running faster, but what when the configuration get changed ? Is it must to to call the constructor and the oncreate methods ?
On rotation your activity will be restarted complete. You can prevent that with android:configChanges="keyboardHidden| orientation" in your manifest.
As #rekire answered, the activity is restarted on screen rotation. Here restart means that the framework creates another instance of the activity, that's why the constructor of your activity class is called and then the onCreate(). The new activity instance replaces the old one which will be finally recycled by GC, if its reference isn't held by others.
If you want to avoid activity restart on screen rotation, please read this question.
I've drawn an UML diagram to describe the Android activity life cycle.
Hence there are no reason having constructor to invoke activity unless you have constructor with params(onCreate invoke it for us anyway...). However basically it seems like a java thing onCreate probably calling activties's default constructor which is
public ActivityName(){} // This might get call because onCreate somewhere under the hood invoking Activity :)
Try same thing with constructor with param like
public ActivityName(String s){}// This wouldn't be call unless you explicitly call it.
Hope this will help,
I would wait for more expert answer though :)
Edit : So when you rotate your phone which calls onCreate as it will get created again and onCreate probably calls default constructor to invoke instance of your activity :)... I forgot to mention this earlier.
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.