How to access a start of Application (not Activity)

馋奶兔 提交于 2019-12-12 04:54:35

问题


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



来源:https://stackoverflow.com/questions/46135828/how-to-access-a-start-of-application-not-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!