When is extending the Application class needed? - android

I saw several places and people suggesting extending the Application class in their app.
Personally, I have never needed the necessity to do so.
I was not able to find a clear cut and direct answer by google-ing, so here are some questions :
What is an application class ?
why do we need it ?
Is it a singleton ? or we can have several instances ?
When we use it inside our manifest, is it the same as using the default application that usually eclipse generates ?
When are cases that extending it might be needed ? and when it is an overhead ?
Is it useful for caching purposes ?

It is something I have also thought about when I first started developing with Android and never came up with an answer. However just a quick google myself revealed this website.
Essentially I think it comes down to the fact if you are making a more involved Android application which would involve several Activity classes then things become difficult if you need to persist data that is to be shared between the various Activity classes of your application. Quoting from the above website:
If you take a look at the Application class (see here) in the API reference guide, you get a suggestion on how to manage global application data. The Application class, it says, is the “Base class for those who need to maintain global application state.”
If you've just started Android development this point may not be apparent to begin with however once you've worked with SDK for a while and you come up with an idea that you'd like to develop in a serious way you may hit upon this problem and then the reason for the Application class will become clear.

In the Android documentation there is quite good explanation what the Applications.class is.
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, which will cause that class to be instantiated for you when the process for your application/package is created.
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.
Sometimes you may need it to extend in order to work with external libraries. I did use it for UrbanAirship see here
The Application instance is indeed one for our app and it is created when our application starts and removed when it is closed. It represents general state of the application.

Related

How can I use two android application classes for UI and Android-service?

Currently in my app, I have an Android application class & in there I'm doing some initializations that use in application UI and some features.
Also, I have an Android service, that runs in backgrounds with some events that doesn't need those above initializations in my application class. That cause some delay for my Android service to start when app UI doesn't not have instance.
Therefore, I need to create a separate application class & couple my service with that. Is this solution possible? If yes, what is the better way to achieve it?
Thank you in Advance.
As #CommonsWare said, this is approach is not a solution for my problem. We can have only one application class mention in AndroidManifest.xml
If we need to create two application classes, we should create new application class by extending the application we already have.
As a solution for my problem, I gave up this approach and I moved all UI stuff to Activity level and kept only necessary things in application level.
Thank you.

Is it possible for a custom view to be implemented in another application?

I have the following in my application (com.para.app1):
<com.para.app2.MyKeyboardView
...
which is a custom view. The implementing class (I.e. MyKeyboardView) is defined in another application (com.para.app2) which is already installed on my device.
Although I have used a fully qualified class name in my layout.xml (that's "com.para.app2.MyKeyboardView"), every time I run my app, I face ClassNotFoundException for MyKeyboardView.
Any idea?
Just to let you know about the error, the issue is that your applications are running in their own processes and VM instance.
Now to answer your question, It is possible, but it would be a dumb idea to take the time to do so since it might have an important impact in performance, either way you might be able to accomplish it by making both apps share the same process(which is possible if both apps are signed with the same key only)but I would strongly recommend you to have the class in both applications and avoid all that useless overload on your apps.
Anyway if both apps are using same process you can use Context.createPackageContext() to instantiate a package for the other app as long as both apps are using the same shared user ID, then you can get the ClassLoader from the context and instantiate whatever classes you want.
Regards!
No. You must have all the classes your app uses in your apk. The only way to run code in another apk is via an Intent. Of course you can't use an Intent to make a view.

Is it safe to use static class variables in an android application

I am aware of the technique of extending the Application class to provide global storage. However in my case I am writing a class for a library function, so do not wish to force users of the class down this path. I have a requirement for some static class variables. I have seen passing references in StackOverflow that these might not be safe. However I've tried two different applications using the same class, and even when running both applications side by side on a Galaxy S3 in multi-window mode, the static class variables remain separate.
So, can someone with an in depth knowledge of Android internals confirm if this is safe or not.
If it is not safe, I can wrap the variables in a nested class and add them to a Serializable static HashMap, using the application package name as the key. This will force them to be safe. However if this is not necessary, then I'd rather not do it.
I have seen passing references in StackOverflow that these might not be safe.
They are not "safe" insofar as your process will be terminated from time to time, wiping out your static data members (and your custom Application, for that matter). Hence, static data members are good for a cache and not much else.
Within that scope, they are "safe".
You just need to make sure that this data is either stored somewhere persistent (e.g., file) or otherwise can be regenerated once the process is terminated and later is started up again. This is no different than with Application.
However I've tried two different applications using the same class, and even when running both applications side by side on a Galaxy S3 in multi-window mode, the static class variables remain separate.
Correct. Those are separate processes, with separate copies of your class and objects.
If your goal is to store persistant data across the twists and turns of the application lifecycle, then I would recommend not using static variables to do so. The obvious problem with this approach is that they could easily be garbage collected by the system when the operating system decides to reclaim memory (i.e. when the screen sleeps or a different application starts a memory-intensive task). I'm not sure what kind of data you are looking to "store", but I would recommend saving the state in SharedPreferences or an SQLiteDatabase instead.
I'm a little confused about what you're trying to do. You're trying to create a utility library in Java to be used by other applications? You're trying to create a whole Activity intended for use by other applications?
At any rate, as other posters have mentioned, applications can be killed at almost any time when resources become tight. There's simply no way to guarantee that static global values will remain resident in memory. You must provide a way to back it up on onPause() or onSaveInstanceState().
If you're writing a utility library, I presume that it returns some master object which holds all of its state. Add saveState(Bundle), restoreState(Bundle) methods to that object, and optionally saveToSharedPreferences() and restoreFromSharedPreferences() methods as well.
If it's an Activity you're writing, you're probably already familiar with the ways of saving state.
Me, I'm fond of combining the "singleton pattern" with shared preferences: https://stackoverflow.com/a/13673178/338479
You seem to have a deep misconception of how classes work.
Even if two classes are in the same package in two separate apps (by default) those apps run on separate VMs (i.e., processes). They literally have nothing to do with each other (as it should be, since otherwise you might get cross-app name collisions which is unacceptable).
What you're looking for is not a way to use static variables but a way to do inter-process communication (IPC). Android's Services are ideal for this, though there is a bit of a steep learning curve there.

Android global/common functions

Just started today to learn Android development, and I just can't find any info on how may I define a Helper class, or a collection of functions that will load globally and I'll be able to use them in any Activity that I create.
What I'm planning, is to create (at least for now) 2 functions that will be used almost in every activity, and would be a mess having to define the same functions in every activity.
Which would be the proper way to approach the above?
I want to throw out a quick note that you should not be putting functions in a global application class for this purpose. Generally what happens is that if you have shared functionality, you abstract that and put the code in:
Static methods
Another package
A library implementing the functionality against which you link your app
A content provider
You should explicitly not implement this functionality in the Application class. There are uses for extending the application, but doing so results in code smell and is a common antipattern for beginners. If you want a bunch of functionality which is shared in your app, a library is the perfect solution (even if it's just code you separate into another package). This encourages reuse and allows the code to be more cleanly segmented and tested.
It's common in Java to have either a class or pacakge of the form *.util for this.
(I'm guessing you come from something like a Rails world where this is the norm, since Ruby is much more metaprogramming oriented than Java, you generally use different tricks.)
This would be a static method in Java.
Java Static Methods
In a class Helper,
public static void DoSomething(){
}
Would be accessible from any class.
Example:
Helper.MyFunction();

Please explain me Context class in Android

I'm new to Android. Can someone explain me the concept of Context class/Object. What it is? What it will be used for? Why Context class?
Have you seen the android developer's guide? it will answer your questions:
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.
A Context has a lot of functions, but as a developer, you primarily use it to load and access application resources.
In programming Android applications, you will hardly ever need to use the Context class directly (not possible at all since Context is abstract), but you will need the child classes that derive from it like Activity, Service etc.
You might want to look these up.
You can think of Context, like the end-user-interface that will use that code. When you are in a class you can know based on Context if you have visual screen(Activity), or a running service(Service).
To compare against some other programming example, you can think of Context is equal to Console App, GUI App, or even Applet.
I hope if you read this source code you will have answer for the problems:
http://www.devdaily.com/java/jwarehouse/android/core/java/android/content/Context.java.shtml

Categories

Resources