I have to run some background tasks whenever an application is activated / or starts running. Suppose u r running the application and then suddenly the device got off or any how u got out of the application without stopping it properly, then when you will again start the application, obviously it will start running from the previous state before getting out of the application. When it starts again or activated, i want my background tasks to be done.Is there any function which is called every time an application starts which i can use to initialize those background tasks? If not then how can i accomplish my purpose? Need help on this , Thanks in advance .... !!!
Whenever an application returns from being in the background, at very least it will run the the onResume() function:
#Override
public void onResume(){
//You have to call super.onResume(), otherwise an exception is thrown
super.onResume();
// and then do whatever you want here.
}
Yes, the main activity class's OnCreate method is called whenever an application is started.
From the documentation -
Called when the activity is starting. This is where most initialization should go: calling setContentView(int) to inflate the activity's UI, using findViewById(int) to programmatically interact with widgets in the UI, calling managedQuery(android.net.Uri, String[], String, String[], String) to retrieve cursors for data being displayed, etc.
This question might be helpful. From the accepted answer -
OnCreate is called regardless of you start the app or you resume the app.
Well - there's no such facility available in the Android SDK for you to determine whether or not your application is running - this is primarily because of the way applications are handled by Android.
For example - what would you mean by saying the application is not running? would that mean the UI s not visible, or the process related to the application is not running? Btw, I hope that you know that:
Application's lifetime != Application process' lifetime.
As for running background tasks, you can either make use of AsyncTask or the Service classes.
And if you're concerned about only the Application's visible lifetime, the you'll have to rely on making use of the onPause and onResume methods, to check on flags which you can turn on/off to capture the state of the app.
Related
If I, for example, need to keep some very important data which the user can edit within my app, should I need to save them every time user changes such data or is it ok if I would save it within onPause(), onStop() or onDestroy() methods?
Can somehow application end without any of those methods calling? (For instance when battery runs out)
This certainly can't be done in onDestroy().
According to the documentation:
There are situations where the system will simply kill the activity's
hosting process without calling this method (or any others) in it, so
it should not be used to do things that are intended to remain around
after the process goes away.
So yes, the application can end without calling any of the lifecycle methods.
In that scenario when the phone is shutting down, you can use the ACTION_SHUTDOWN Intent.
More info here. For all other cases onPause should do the work. Even in the link provided, there is a statement that onPause will be called if the app is in FG.
Apps will not normally need to handle this, since the foreground
activity will be paused as well.
However, if it is not so expensive operation, I would go with saving data after edit.
As per the documentation of Android activity life cycle, onPause is called when an activity is going into the background, but has not (yet) been killed.
Hence, in most Android documentation, and sample codes you will find onPause is used for saving any persistent state the activity is editing, to present a "edit in place" model to the user and making sure nothing is lost if there are not enough resources.
So in your use case, all you need to do is implement onPause for your Activity and write a code to Save the activity state (EditText content or any other ongoing user interactions). Android system will save the activity state which you can always get back in onCreate of your Activity when android launch your activity next time.
in this case please verify your phone activity via debug interface , some of phones are terminate your application this is force quit.
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.
I have an activity in which I do server sync with a back end server using a subclass of asyctask.
Given it is a network task and might take couple of seconds. I am afraid of the following scenario to take place.
The activity starts, and whenever the asynctask should start to run, it does so.
The onPrexecute() is called, executed, and over. Than the doInBackground() is called, and is done so, however, just when the method is being executed, the user presses the home button and swipes the app from the RECENT APPS. (this ofcourse causes the app to terminate and all the onDestroy methods get called of the alive activities..(Correct me if I'm wrong on this one)).
In my onPostExecute() method, I am inserting the data to DB and updating the VIEWs.
But since the app is 'terminated' the onPostExecute() method never runs.
my questions are :
When the user presses the home button and gets out of the app and swipes the app, is doInBackground halted at that moment ? that is, it is cut in the middle and does not continue what it does ?
What happens to the data that I was going to get from the server and put inside the DB ? Is it advisable to do put the data in the db inside the doInBackground ?
AsyncTask is a background task it will continue to run even if the app is closed and onDestroy() is called. The problem would be when the task enters onPostExecute() and tries to update any views associated with the activity it is bound to, as that activity no longer exists. If you're concerned about this, one thing I've done is to keep a reference to that AsyncTask in the calling activity, and then call the method myAsyncTaskReference.cancel(true) to cancel it in the onDestroy() of the calling activity.
Yes, I would put the DB operations in the doInBackground() method, as that runs in the background on a separate thread, and doesn't require a reference to the app activity.
Have you considered using a service for this type of thing instead? I would strongly recommend an IntentService, which is a subclass of service which is specifically designed to perform a single task in the background (similar to AsyncTask), and then kill itself once completed. It's quite easy to implement and usually only involves overriding one method - onHandleIntent() - which is called when the service starts.
It can handle all your DB operations and it has no reference to an activity and so the problem you're worried about in #1 would never occur. If you need to update a view, you can have your IntentService generate a broadcast once it's completed, and your Activity can register for that broadcast and update it's views accordingly when it receives it. And if your activity is no longer around once the broadcast is sent then it doesn't matter and nothing will fail.
When user presses 'Home', your Activtiy will pause but doInBackground will NOT, but may or may not terminate by system when system feels like it. Activity's onPause will be called. Your Asynctask doInBackGround will NOT halt. It will continue to run until the system kills your App process.
Yes, Db operations can take long. Its advisable to put in doInBackground because it runs on another Thread. onpre/onpostexcute runs on the main thread. If you are worried that System may terminate half way of your db operations, you shouse set Transcation, and only when you are done, you called commit.
Check out this post, I have tested it.
no, it doesn't stop.
It is relly better to put it to datastorage of some kind and then work with it
It is always better to use service for such goals. AsyncTasks just don't fit here. Ask your service to do the work, and then you may start or quit activities as you wish to.
If swiping app from recent stack, it is equivalent to close the app hence it will kill all tasks related to the process so async task will also get killed by the android system. ( even intent service is also get killed)
It is device dependent also. Manufacturers customised removing app from recents behaviour
In Windows Phone, there is Application.LoadCompleted Event for detecting the finish of starting an application.
Note the finish means that users are able to interact with the app.
Is there similar API on Android? Any other approaches to achieve this?
after onResume() gets called it means the user can start interacting with your app. Consult this document for more information
You can override onCreate method of main Activity.
It depends what you mean by 'finished starting'. Activities, including the main activity, can be created and destroyed - and therefore onCreate() called - multiple times, for example (in the default behaviour) when the device orientation changes. onResume will be called even more often, for example every time the activity comes to the foreground. Then there's onStart(). See the Android developer docs to see when in the lifecycle each is invoked. It's true that the first time onResume() is called on the main activity will be when the app is fully started, but you won't know it's the first time without storing state somewhere outside any activity, for example on a singleton, or by subclassing the Application class, which is not something especially encouraged, as far as I can tell.
In the Android Application class you can register/unregister ActivityLifecycleCallbacks, which allow you to monitor Activity lifecycle events in your application all in one place (if you so desire).
Where is the proper place to call unregisterActivityLifecycleCallbacks? I'm registering in onCreate, and was thinking that onTerminate would be the proper place just from the name of the method but the docs say for onTerminate():
This method is for use in emulated process environments. It will never
be called on a production Android device, where processes are removed
by simply killing them; no user code (including this callback) is
executed when doing so.
I don't see any other methods in the Application class where a 'shutdown' type callback is made. Do you even need to unregister?
Simon was right about this. registerActivityLifecycleCallbacks doesn't require a matching call to unregisterActivityLifecycleCallbacks. As described in this SO question you can't detected when your application is being killed. So there is no "logical" place to unregister your callback. And even if there was, your Application instance is killed after the last Activity action takes place, and the killing of your Application kills the mActivityLifecycleCallbacks list which holds the reference to your callback anyway.
TL;DR - Don't worry about calling unregisterActivityLifecycleCallbacks, it's only there if you want to stop tracking Activity actions during your Application's normal lifecycle.