How to access a start of Application (not Activity

2019-08-18 14:50发布

问题:

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 !

回答1:

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"


回答2:

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