I am creating an application which requires login. I created the main and the login activity.
In the main activity onCreate
method I added the following
What about ensuring the collection of native memory with such global structures?
Activities have an onPause/onDestroy()
method that's called upon destruction, but the Application class has no equivalents. What mechanism are recommended to ensure that global structures (especially those containing references to native memory) are garbage collected appropriately when the application is either killed or the task stack is put in the background?
you can use Intents , Sqlite , or Shared Preferences . When it comes to the media storage, like documents , photos , and videos, you may create the new files instead.
Just a note ..
add:
android:name=".Globals"
or whatever you named your subclass to the existing <application>
tag. I kept trying to add another <application>
tag to the manifest and would get an exception.
I couldn't find how to specify the application tag either, but after a lot of Googling, it became obvious from the manifest file docs: use android:name, in addition to the default icon and label in the application stanza.
android:name The fully qualified name of an Application subclass implemented for the application. When the application process is started, this class is instantiated before any of the application's components.
The subclass is optional; most applications won't need one. In the absence of a subclass, Android uses an instance of the base Application class.
DO N'T Use another <application>
tag in manifest file.Just do one change in existing <application>
tag , add this line android:name=".ApplicationName"
where, ApplicationName
will be name of your subclass(use to store global) that, you is about to create.
so, finally your ONE AND ONLY <application>
tag in manifest file should look like this :-
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/Theme.AppCompat.NoActionBar"
android:name=".ApplicationName"
>
Like there was discussed above OS could kill the APPLICATION without any notification (there is no onDestroy event) so there is no way to save these global variables.
SharedPreferences could be a solution EXCEPT you have COMPLEX STRUCTURED variables (in my case I had integer array to store the IDs that the user has already handled). The problem with the SharedPreferences is that it is hard to store and retrieve these structures each time the values needed.
In my case I had a background SERVICE so I could move this variables to there and because the service has onDestroy event, I could save those values easily.