I don't precisely understand what the Context of app is, what it provides.
The description given in the Android API is:
"Interface to global information about an application environment. This is an abstract class whose implementation is provided by the Android system. It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc."
What is global information?
What doe we mean by application environment?
What do we mean by up-calling for app-level operations such as launching activities?
The Application is a class that lives alongside all your Activities. Think of it as the basement (or the attic). It is created before any other thing that your manifest contains (Activities, Services, etc) and is the last thing cleaned up if your app is GCed by Android.
So you can use it to store persistent variables and data members that various Activities need to have access to.
To use it, create a new class that extends Application (MyApp.java) and reference it in the application node of the manifest (android:name=".MyApp").
Then you can get a reference to it in onCreate of any Activity like
super.onCreate(b);
MyApp myApp = (MyApp)getApplicationContext();
Make sure not to confuse the Activity or Service Context with the Application Context. they're frequently interchangeable but if you're not careful you'll wind up raising exceptions related to your UI Thread.
Related
From Firebase docs they say:
Multiple processes
Crash Reporting creates a separate background process to upload crash
info. If your app extends the Android Application class, you must
ensure it is multi-process safe. Otherwise, it may cause concurrency
issues. When an app extends an Application object, this object gets
instantiated for each process in a multi-process app. Two important
things to watch for are:
If the implementation of this object accesses any out-of-process state
(a database, the file system, shared preferences, etc), or performs
other actions not safe for a multi-process environment, concurrency
issues might arise. This is because multiple instances of the
Application object may run simultaneously. Many third-party libraries
keep out-of-process state (e.g. in a local database) and are subject
to the same concurrency issues if they are initialized from the
Application object. If your app fits the description above and you
plan to use Crash Reporting in your app, we strongly encourage you to
consider moving the Application logic to Content Providers, or to
Android Activities. Any Application logic that is not safe for a
multi-process environment can have unintended effects on your app.
How can I check from my Application class if theres another instance inside the Application onCreate to avoid crashes with Fabric or others?
Generally speaking, you don't "check to see" if there is another Application object from another process. You simply assume that there is always exactly one Application object created for every process in your app, and ensure for yourself that it will be safe to run in conjunction with other Applications objects in other processes. Just don't access any shared read/write resources from Application and you will be fine.
If you must initialize something from only the main process, a more reliable way of doing this is to create a ContentProvider (declare in your manifest and create an object for it like any other component), and use its onCreate(). ContentProviders are only created and initialized from the main process - never from other processes. This way you can be sure that your init will not be duplicated in any other process.
Or if you don't want to deal with this at all, just wait until Crash Reporting comes out of beta to full release, as it will not use an extra process at that time in the future. We (Google) can't say exactly when that will be, but we're not wasting any time in getting the full release published.
I am working on a solution or code that can be embedded inside of an Android APK to track how many times the app has been launched and how long the app has ran for. I know one way to do this is using the ActivityLifecycleMethods in API 14 and in lower versions of Android having code placed in all Activity Lifecycle events or by providing a base Activity class.
1) Is there a way to hook the ActivityLifecycleMethods without the developer having to make any changes to their code outside of dropping additional code into their App?
I believe this answer is no because even with an Enum Singleton it is not loaded until it is referenced. Also the Enum Singleton will go away once the activity is changed since a different class loader is used when activities change.
If I wanted to keep the Enum Singleton around would it be possible to store a reference to the applicationContext and thus it wouldn't be removed when the Activity changes? Is that what google means by
"There is normally no need to subclass Application. In most situation, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), the function to retrieve it can be given a Context which internally uses Context.getApplicationContext() when first constructing the singleton." on http://developer.android.com/reference/android/app/Application.html
2) I am not a fan of this solution for older API versions. It seems very likely developers could forget to modify their Activity Lifecycle methods or forget to inherit from the created BaseActivity. Are there any other unique solutions for these older platforms? Is there any other approaches that can be done to determine when an activity isn't running? Could any of the following work:
a) User a class loader to ensure the base activity with the proper metrics are always used
b) Implement some type of heart beat. Will a timer stop working if the app is paused or killed? Is there some other way? Could the ActivityManager be used?
You have many Analytic Agents like Flurry to do that.
When ever you want to track an event, you will add it to flurry and inturn it syncs with server after specific time.
You may use the same logic.
Better create a library file with following features:
Start Application
End Application and report time to db.
Track a specific event count and update to db.
Sync the data to server you like to.
Call appropriate events from your app.
I have been told recently that extending the Application Class in order to use it as a Singleton was a bad practice but without any explanation.
So what are the potentials problem behind the use of this class ? I have seen it used in many projects.
Also, if using the Application Class is a bad idea, what are the alternatives to store application level variables ?
Using a Singleton approach is not really a bad idea, but it may be troublesome in the cases when being used in a multi-threaded environment where one thread sets a value to a variable and the other thread may over-write that value without any notice.
However, in order to keep application level instances/variables, it is suggested to extend Application class and define it in your AndroidManifest.xml as the default one. Since the application's context is created only once (till the application is running and stays in the memory) when you launch that application, so you may define some variables inside that class to make them availabe anywhere in your application's code using public methods.
Moreover, you may use your application class as Singleton too, since its guaranteed to be created only once when launched.
The problem with using a Singleton class, as well as extending the Application class, is that if the application process is killed - which is very likely to happen when the app is left too long in background - the object will lose all your data.
However, using Application class may be a good option in cases when your app is in foreground or does not stay to much in background (although not 100% risk free).
As an alternative, you could save the data into SharedPreferences, or if your object is more complex, save it in a database.
Another option would be to combine both the use of Application, plus SharedPreferences for example. First try to retrieve the variable from Application instance, if the variable is null, then retrieve it from SharedPreferences.
In my Android application, I overload the Application class, and I updated the tag in my manifest. This application also creates an Android Service.
I have put some logs in the onCreate of my Application class, and I see it being called twice.
The first time is when my application gets launched (this is expected) and then, it's usually right after the Service is being created.
the log also shows that a second instance of the Application is being created.
(I print the "this" value and they are different).
I thought the Application would be created as a singleton.
Is that happening because I create a Service?
Yes, if you used android:process then you have it running in a separate process, so when the service starts a new process is started for it and thus a new Application object for that process needs to be created.
But there is a more fundamental problem - it is just not right for an Application object to start one of its services. It is important that you don't confuse Application with how you may think of an "application" in another OS. The Application object does not drive the app. It is just a global of state for the app in that process. In fact, the Application object is completely superfluous -- you never need one to write an Android application. Generally I actually recommend that people don't use it. It is more likely to cause trouble than anything else.
Another way to put this: what really defines an application is its collection of activity, service, receiver, and provider tags. Those are what are "launched." All an Application is, is something that is created as part of initializing an application's process. It has no lifecycle of its own, it is just there to serve the other real components in the app.
So just ignore Application when designing your app; it will reduce confusion. (In its place, I prefer to use global singletons for such state.)
Also as a general rule, I recommend not using android:process. There are certainly some uses for it, but the vast majority of the time it is not needed and just makes an application use more RAM, less efficient, and harder to write (since you can't take advantage of globals in a single process). It should be obvious to you if you reach a place where there is actually a good reason to use android:process.
A Service should not really be thought of as an Activity, and you're bound to have problems later on if you think this way. Services and Activities can belong to the same application, if you defined them that way in your AndroidManifest.xml, but they behave differently and have different lifecycles. If you want your Service in a different process, then you set android:process="string" in the <service> section to give it a name different from your application name. You won't have access to global variables when it's in a separate process, and you should communicate to your service through Intents. If your service is more complex, you might want to look at making it remotely callable through AIDL. If you want a singleton activity, then set that Activity's launchMode to either singleInstance or singleTask. singleInstance means it will be the first and only instance of this Activity in it's task stack and no new instances will be created for any new Intents. Since it's the only instance of this Activity, it will always be at the top of the task stack, and always in a position to handle new Intents directed at this Activity. If the Activity is declared as singleTask it will also be a singleton but may have other Activities in the same task stack, and may even have Activities at the top of the task stack above it. This is an important distinction to note. Remember this: singleton Activities that are NOT at the top of the task stack cannot handle new Intents, and the Intent will be dropped. If you want your Activity to always be able to handle all new Intents destined for it, then you most likely want to use singleInstance
The problem is that a Service is a component too, with its own lifecycle, just it hasn't got an user interface.
You should check the developer application fundamentals for the alternatives.
I just had this issue and after reading all this, nothing helped. Here is what helped me.
Add the attribute MainLauncher = true to your MainActivity.cs class.
I have an application that is driven by a configuration XML: various
app properties are loaded at the app start-time by parsing the XML and
initializing static variables of some class. The data read from this
XML drives different Activities of the application. Presently, I have
called the "parsing and the properties-initialization" from the
onCreate() of my Main Activity.
I have a few questions as regards this case/approach:
Should I invoke the app initialization method from the Application
Object or is the current approach correct? What advantages/
disadvantages do/would we get/have if I choose to invoke it from the
Application object?
Do we really need a static class to store app properties? Or can we have all the properties as a static Collection variable in the application object?
Parsing a XML(~200 nodes) at app load time might take some time(not
sure how long tho); How can I avoid the dreaded ANRs? I am using a
Pull Parser.
Please help me find answers to these questions.
Thank you.
It depends on what you're initializing. Application's onCreate() should be used when you're doing things that need to be done before any part of your app works correctly and only needs to be done once, whereas Activity/Service/etc's onCreate() should be used for things that are needed for that component alone and needs to be done multiple times.
The main concern I have for putting all your initialization into a component is that it will make extending your application more difficult later on. Suppose you want to make some Activity in your application accessible by outside intents - now you've got to either move the initialization code to Application or you have to duplicate initialization code in the non-launcher Activity.
It sounds like you should check out SharedPreferences, especially PreferenceManager.getDefaultSharedPreferences(). The preferences will be stored between sessions and it gives you easy access to simple properties from any Context.
Threading. I find AsyncTask to be the easiest way to accomplish this task; there's a good write-up on it at Google. Alternatively, you could fire up a Service to do this in the background while having a foreground Activity inform the user that you're booting up the app.
The Application object is used for sharing non-persistent state across the application. I don't think you'll need to use an Application class at all. You can do your initialisation in the onCreate() method of the Activity that is called first. To quote the documentation:
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.
You don't need to create your own class to store application properties. This is done for you by SharedPreferences.
You should also have a look at the setDefaultValues() method in the PreferenceManager
class as this will set preferences from the data in an XML file. What's nice about this method is that use the readAgain parameter so that the XML is only parsed once - the first time you start up your application - rather than every time.