How to access a start of Application (not Activity) - android

I need to implement very specific code in the start of the application.
I mean, not in the start of the activity(onCreate() or onStart()) but in the start of the application.
I had one solution which is not good for me, which is to have a base activity called "MyBaseActivity" and then extends from it in all of my activities.
This solution is not good for me, because this solution makes me to be able to do only one specific thing in the onCreate of each activity(the specific code I talked about), which is not what I want.
I want every activity to be able to do different things according to their onCreate() func, and in addition to do the specific code that I talked about above.
Therefor, I need to access the start of the application, or that you have another solution for me.
Thank you !

The Application class, or your subclass of the Application class, is instantiated before any other class when the process for your application/package is created.
You need to extend application class.
public class AppApplication extends Application{
#Override
public void onCreate() {
super.onCreate();
//Do whatever you want
}
}
And this AppApplication class should be included in manifest file.
<application
android:allowBackup="true"
android:name=".AppApplication"
android:icon="#mipmap/ic_launcher"

I need to implement very specific code in the start of the application.
Every time when Android "gets a request" to start any of your app component (Activity, Service, BroadcastReceiver) and your app isn't running yet, it forks the app_process (a.k.a zygote), changes its name to your.package.name defined in AndroidManifest.xml, initializes an Application instance, calls its onCreate() method, then instantiates the component requested and calls its lifecycle methods (Activity's onCreate(), Service's onCreate() or BroadcastReceiver's onReceive()).
There can be only single instance of Application class which lives untill the app process dies. That said, any class instances you create within your extended Application class will also live until the app process is killed by the system.
Example: Understanding the Android Application Class

Related

Android Activity::onCreate called before Application.onCreate

In some cases I can see that Activity.onCreate is called before the Appication object gets created (before Application.onCreate is called). Is that ever possible?
May be you forgot to add your application class in manifest file.
Place your application class in AndroidManifest.xml class under <application> tag.
i.e.,
<application
android:name=".{YourApplicationClassName}"
...
...
In some cases I can see that Activity.onCreate is called before the
Appication object gets created (before Application.onCreate is
called).
This is not what Android document says about the Application class. As per the official android documents,
The Application class, or your subclass of the Application class, is
instantiated before any other class when the process for your
application/package is created.
Also below is specific explanation of onCreate() of an Application class
Called when the application is starting, before any activity, service,
or receiver objects (excluding content providers) have been created.
Hence the onCreate() of Application has to be invoked 1st and then onCreate() of Activity class
So the scenario you have mentioned is not possible as per the flow of instantiation of Application class and Activity class
In the case you are using logging to determine when application is created, check if you are using external logging system, like Timber which is usually instantiated in the end of application onCreate(). So it may appear that nothing before this system is instantiated when it is called.
Try to instantiate logging tool before super.onCreate() in application onCreate().

Detecting activity launching inside application

I'm trying to realize functionality for login launched activities names. I don't want to add checking in every activity. Short time ago i saw that it's possible to realize something like "activity lifecycle manager" inside application and catch callbacks like activityCreated(...) or activityDestroyed(...). But unfortunately i forgot the exact name of that method/interface(i don't even remember what was that :( ) and i didn't manage to find something similar here.
So, can somebody tell me how can i achieve this?
You can extend the Application class and implement the ActivityLifecycleCallbacks interface:
public class MyApplication extends Application implements ActivityLifecycleCallbacks {
// Various activity callbacks here
}
You can read about the callbacks here.
The above class will need to registered in the <application> tag of your manifest file under android:name:"" property as android:name:"MyApplication".

Android: How to know the component type in Application class?

I'm extending the Application class for my additional custom need. And I'm calling a method inside that. As the expected behaviour, it is getting invoked for type of Android components(Activity, Service, Broadcast receiver, etc.,) But I want that too be invoked only on Activity. Is that any other way to overcome this problem ?
public class MyApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
// the below method needs to invoked only for service
// but now called for all application components
myCustomMethod();
}
....
}
But I want that too be invoked only on Activity.
Can't be done. The Application instance will run if one component of your Application is open.
You need to do the customized stuff in another class and open it just when the instance of your desire component is open.
just add your code to onCreate method of your entry-point activity. If you want it to be called once per session - add two int keys to your shared preferences - app_launch_count and method_invoke_count. Increment first on App's onCreate and check the second in your Activity's onCreate if first greater then invoke the method :)
Move myCustomMethod() into the activity. An Application has no way of knowing what triggered the creation of its process.
Or, use registerActivityLifecycleCallbacks() on Application to register an ActivityLifecycleCallbacks object, and put your myCustomMethod() logic in onActivityCreated(). This requires a minSdkVersion of 14 or higher. That will tell you when each activity is created after your process is instantiated — if you only care about the first one, you would have to unregister the callbacks in your onActivityCreated() implementation.

Android Application sub-class constructor not being called

I have a class in my Android application that sub-classes the AndroidApplication object. The documents say:
public void onCreate ()
Since: API Level 1 Called when the
application is starting, before any
other application objects have been
created. Implementations should be as
quick as possible (for example using
lazy initialization of state) since
the time spent in this function
directly impacts the performance of
starting the first activity, service,
or receiver in a process. If you
override this method, be sure to
call super.onCreate().
I placed a breakpoint on my sub-class's constructor and when I run my application, it is never reached. Naturally, when I call the sub-class's getInstance() method from other code it returns NULL since the instance variable is (supposed to be) initialized when the constructor is called.
Can anyone tell me what is wrong? I would assume from the docs that I don't have to create an instance of the AndroidApplication sub-class myself, or do I? Am I supposed to modify my manifest file somehow to add the AndroidApplication sub-class and if so, how?
-- roschler
I'm posting the answer here for others. Yes you need to add the name of your Application object sub-class's name to the Android manifest. For Eclipse users, the easiest way to do this is to open the AndroidManifest.xml file, select the Application tab in the manifest editor, and use the Browse button next to the Name field to find your Android Application object sub-class name and select it. The manifest file will be updated properly to register it. I just did that and it worked.
I had a problem of not having a . before my application class name.
Should be:
android:name=".MyApp"
since the MyApp class is in the package defined in the manifest.

Accessing Activity before it starts

I am using the InstrumentationTestCase class in order to unit test some things within an activity.
I need to be able to check the SharedPreferences's contents and edit them, before this activity is launched.
I cannot use the setUp method to create the Activity and access it's SharedPreferences object to edit it, and then close that activity before finishing the setUp method because it apparently is locking the tests processing.
I also cannot access the SharedPreferences after I have launched the activity inside the test because as soon as the Activity is launched, it will already change the SharedPreferences object and act according to it, before I had the chance to get it's reference.
I apparently cannot access the SharedPreferences before either, because I have no Activity object... and as soon as I do, it is already executing code and being launched...
So, my question is, is there any way to access the SharedPreferences (and any other Activity information) of this Activity before I have the Activity actually created through an Intent?
I cannot change it to an ActivityInstrumentationTestCase2 because my test uses a second activity in it's process, so I can't just change to this class and use it's setUp() method to access the SharedPreferences.
I found the best simpler way to do this through the instrumentation only, without having to edit the application's architecture or any of the access attributes.
I achieved it through this:
Instrumentation instrumentation = getInstrumentation();
instrumentation.getTargetContext().getSharedPreferences(..);
This way I can access the SharedPreferences before any Activity is launched by the instrumentation.
Thanks for all the help, hints and other alternatives anyway.
Well... To tell you frankly.. I am not able to visualize your scenario. But is checking for info in application is doable ?
Create a class which extends android.app.Application and specify class name in Manifests child application element.
Sample Code:
import android.app.Application;
public class MyApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
//try and access activity info here.
}
}
When your application is launched first class method to execture is onCreate of your application and has all the lifecyle events of that of any activity..
You must define extended application class in manifest by:
<application
android:name=".MyApplication"
android:label="#string/application_name">
I hope this ca give you some overview.
I haven't tried it, but if you set the mode to MODE_WORLD_READABLE and possibly MODE_WORLD_WRITEABLE instead of MODE_PRIVATE, I would think you could access the shared preferences from another application before the activity under test starts.
You could probably also use a different activity or service within the apk, or another apk that establishes a shared user ID and has the same certificate, to do the access without changing the access mode.

Categories

Resources