I am creating an application that checks when the app first loads. I am creating a value in the MainActivity class (before the onCreate() method). I need this because I want something to run only on the first app load. When is the Activity class loaded? I know that the onCreate() method runs whenever the app opens and renders, but it seems that the Activity is reloading after extended time with the app closed. Is there a way to store a variable when the app first loads but doesn't reset when onCreate() runs?
Subclass Application and do whatever initialization you are doing inside of the Application's onCreate() method. You also need to specify the name of your Application class in your AndroidManifest's <application> tag. This will run once every time your app process starts.
If you want to run something the very first time the app is launched and never again (even on future launches), you should still use the Application subclass, but now you also need to store something in SharedPreferences (or elsewhere) that you can check for later to make sure you only do this task once.
SharedPreferences.Editor ed=PreferenceManager.getDefaultSharedPreferences(YourActivityName.this).edit();
ed.putString("key","value").commit();
And to get back the value from shared preferences do this:
String storedValue=PreferenceManager.getDefaultSharedPreferences(YourActivityName.this).getString("key","default Value In Case The Variable Hasn'tBeen Created");
Related
In my application I have a filter function on table view which give filtered result in table. I set filtered options(checkboxes) in shared preferences so the next time the user go in filter screen it sees the checkboxes checked so it know what was the table filtered for and what he did check last time for filtering.
when the application launches i set them all to unchecked(requirement), but i dont know when the application is launched or resume. when the application is resumed from memory it again initialized all my data types. how can i check the application is resumed. if i set things in activity onResume - no gain it is called every time i just want to know only when the application is resumed.
What happens now i dont know when the application is resumed from memory, my filter behaves like application launched and set all to unchecked
what i did is, on my first activity made a boolean and put false and stored it in shared preferences, then did it true when start that filtering thing. so it remains true as the application remains in the memory and resume even. when application exits, and the launched again on startup it again turns false
There's no "resumed from memory" state. It is either resumed or created (or restarted). So you should rework your application logic and init your stuff on onCreate() instead of onResume()
I am not able to understand you question properly, but as far as my understanding goes, you are filtering user options through shared preferences. If this is so, you need not unset/set each option programatically. Android remembers and and restores this for you. If you want to access these, just call context.getSharedPreferences() and from sharedPreferences object received call getBoolean (key,defValue).
You can restore your checkboxes on onRestart(), that means your activity was not killed and is resumed after it had been stopped(either manually or by android).
I'm working on an application which has a few Activities. One Activity starts the next one. To share some Values I'm using a custom implementation of Application (I'm talking about android.app.Application) called MyApplication.
As we all know, the Android system kills an app, if it needs more space. But this leads to a problem:
I open my app and use it just like any other app
I close it (Home Button) and use other apps
The system will kill my application because it's wasting memory
When I reopen my App, it wants to open the last activity I used and I get a force close, because the values in MyApplication are null
The strange thing is, that the system destroys my Application, but it seems like it keeps the Activity. I don't really understand why this is so because the Application doesn't seem to have a life cycle.
What I want to have:
When MyApplication (whole Application, not only the activity) gets killed, I want the last activities to be killed too. So when I reopen the App, it starts the main acitvity provided by the manifest.xml.
or
The values in MyApplication are persisted and don't get lost if the Application gets destroyed. (I'm talking about a few objects so i think the shared preferences won't work).
I don't want to use a service to bind my activities to, but is there a similar way to tell the system that my last used activity depends on the application-context?
I hope you understand what my problem is and someone can help me out with this.
The right way to do things would be to save your application state.
Override the onSaveInstanceState(Bundle savedInstanceState) method to save your state and onRestoreInstanceState to retrieve it.
If you need to save large sets of data consider using a SQL database
You should make sure the app closes and restarts the way you want it to in the onPause() , onResume() and onStop() methods. Check out savedInstanceState which can save the state of the app (and restore it, when it's sent as a parameter to onCreate)
In your custom implementation of Application, add a Flag say :
public boolean appContextExist = false;
On your first Activity set the flag to true,
Override onCreate and onResume method on your Activity which need the contexts, add following :
MyApplication myApp = ((MyApplication) getApplicationContext());
if (!myApp.appContextExist) {
// Code to return to start activity here
}
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.
I am using a separate class with only static fields, to store current application data.
It is partly populated from sharedpreferences on application startup. The rest is data like results of some action, used for further browsing these results (multiple activities that use the results).
I can go to the home screen, start other applications etc. and when I return to my own application it just works correctly.
However, since the new Error Reporting feature I get some bug reports all related to a nullreference error. The object that is null is a reference to the static field in the mentioned separate class.
Since I cannot reproduce the bug I am inclined to think this is due to the application getting killed due to low memory, and when it relaunches it calls the oncreate from the activity that the user was currently in. However all the static data in the separate class is not restored and thus it crashes.
I would like to know: Is there a way to force the application to "restart" completely, and not start with the last used activity if it gets killed? Or is that standard behaviour?
Can I do this programmatically? Like when the static fields are null, restart app?
Restarting the activity where the user was is normal behaviour - the idea is to make it look to the user like the app was never closed. There are two things you can look at:
protected void onSaveInstanceState(Bundle outState){
// This gets called by the system when it's about to kill your app
// Put all your data in the outState bundle
}
That bundle is the same one that gets passed to the activity in onCreate(). You can then get any necessary information out of it and restore the values in the static class.
The other way is to simply check the values in the onResume() method of any of your activities. If the values are null or wrong in some way, then you can call start the original activity and finish() the one being started.
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.