Reputation: 135
Is there a way to do some stuff before onCreate()
of the MainActivity is called?
We want to do some initializing stuff like logging...
Upvotes: 10
Views: 14617
Reputation: 229
You can create another Activity and set that as launcher. And do your stuff in that activity. And on completion of your task, start main activity.
Upvotes: 0
Reputation: 12929
You can add a static initialization block to your Activity. It will be run exactly once per process, the first time this Activity is invoked and before any other Activity method is run.
If your initialization code is not related to this Activity but to the whole app, the best approach is usually to create a lazily initialized singleton class, or in some cases it may be acceptable to add the initialization code to Application.onCreate()
by overriding this method after subclassing Application
.
Upvotes: 1
Reputation: 6472
Two options;
1 . If your logging is not related to the activity about to start, rather, you'd need 'some' initialisation before the first activity starts then subclass android.app.Application
. The onCreate
method here is pretty much the first thing to run when your application starts.
For example, in our app this is where we create our DI injector's or decide whether the app needs a database created ("Preparing for first use") type tasks.
This seems like a good fit for application wide logging subsystem initialisation...
2 . Failing that (and if you want to log precisely just before an Activity's onCreate
method is called) then this is a classic use-case for Aspects. We use AspectJ for similar reasons alongside database transaction management. Refer to this blog entry on how to weave the code you require in the Android build system.
Upvotes: 7
Reputation: 5440
First you create an activity for loging purpose.And set this as your launcher activity.Then start your main activity from this activity after login completes.
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
This should be added to the manifest to mark an actvity as launcher activity
Upvotes: 4
Reputation: 22527
If you refer to Activity life cycle, I doubt it is possible.
But you can create a service or another activity which are launched prior it.
Do your logging in the background and pass the information your main activity!
Upvotes: 3