美文网首页
Context被创建的次数

Context被创建的次数

作者: BlackNeko | 来源:发表于2017-10-27 17:20 被阅读43次

    很多书里面都说 Context 对象个数 = 四大组件个数 + 1,这个1代表的是application,但其实这里的个数说法是不对的。

    context 个数应该是 四大组件个数 + 进程数。

    有几个进程,application就会被创建几次

    Application

    public class Application extends android.app.Application {
    
        @Override
        protected void attachBaseContext(Context base) {
            super.attachBaseContext(base);
            Log.i("DaqServices_TAG", "attachBaseContext: ");
        }
    
        @Override
        public void onCreate() {
            super.onCreate();
            Log.i("DaqServices_TAG", "oncreat");
        }
    }
    

    Service

    public class DaqServices extends Service {
        private final String TAG = "DaqServices_TAG";
    
    
        @Override
        public void onCreate() {
            super.onCreate();
            Log.i(TAG, "onCreate() executed");
        }
    
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            Log.i(TAG, "onStartCommand() executed");
            return START_NOT_STICKY;
        }
    
        @Override
        public void onDestroy() {
            super.onDestroy();
            Log.i(TAG, "onDestroy() executed");
        }
    
        @Override
        public void onTaskRemoved(Intent intent) {
            super.onTaskRemoved(intent);
            Log.i(TAG, "onTaskremoved");
    
        }
    
        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
    }
    

    AndroidManifest 配置

     <service
                android:name="com.pxworks.projectx.service.DaqServices"
                android:process=":peppelu"
                android:stopWithTask="false" />
    

    日志

    10-27 17:05:53.614 32026-32026/com.pxworks.projectx I/DaqServices_TAG: attachBaseContext: 
    10-27 17:05:53.617 32026-32026/com.pxworks.projectx I/DaqServices_TAG: oncreat
    10-27 17:05:53.839 32044-32044/com.pxworks.projectx:peppelu I/DaqServices_TAG: attachBaseContext: 
    10-27 17:05:53.840 32044-32044/com.pxworks.projectx:peppelu I/DaqServices_TAG: oncreat
    10-27 17:05:53.841 32044-32044/com.pxworks.projectx:peppelu I/DaqServices_TAG: onCreate() executed
    10-27 17:05:53.841 32044-32044/com.pxworks.projectx:peppelu I/DaqServices_TAG: onStartCommand() executed
    

    Application被创建了两次

    相关文章

      网友评论

          本文标题:Context被创建的次数

          本文链接:https://www.haomeiwen.com/subject/chldpxtx.html