FrameWork源碼解析(11)-插件化框架VirtualApk之Service管理

主目錄見(jiàn):Android高級(jí)進(jìn)階知識(shí)(這是總目錄索引)
框架地址:VirtualApk
在線(xiàn)源碼查看:AndroidXRef

關(guān)于滴滴插件化框架VirtualApk我們已經(jīng)講了有幾篇了:
1)插件化框架VirtualApk之初始化
2)插件化框架VirtualApk之插件加載
3)插件化框架VirtualApk之Activity啟動(dòng)
這篇我們緊接著前面開(kāi)始講,我們知道啟動(dòng)服務(wù)有兩種方式startService和bindService兩種方式,我們前面已經(jīng)講過(guò)startService的流程分析和bindService方式的從framework分析AIDL生成文件,而且我們知道,Service的生命周期是我們可以手動(dòng)控制的,我們可以不像Activity生命周期的控制一樣交給系統(tǒng)管理,我們可以更簡(jiǎn)單地控制Service的生命周期。

Service生命周期

我們看到Service的生命周期是比較簡(jiǎn)單的,而且圖中已經(jīng)說(shuō)明了startService的時(shí)候,會(huì)調(diào)用onCreate(),onSstartCommand()方法,然后停止服務(wù)的時(shí)候我們可以調(diào)用stopService()或者stopSelf()方法;如果是bindService的時(shí)候,則會(huì)調(diào)用onCreate(),onBind()方法返回binder對(duì)象,然后會(huì)回調(diào)ServiceConnection對(duì)象,解除綁定的時(shí)候可以調(diào)用unBindService()來(lái)回調(diào)onUnbind()方法。和上一篇一樣,我們這里就貼一下startService的啟動(dòng)過(guò)程概圖:

startService流程圖

我們看到和Activity啟動(dòng)不一樣的是,這里并不是通過(guò)Instrumentation來(lái)進(jìn)行管理創(chuàng)建過(guò)程的,而是直接通過(guò)ActivityManagerProxyAMS通訊進(jìn)行創(chuàng)建的。

一.Service管理過(guò)程分析

插件化框架VirtualApk在Service的管理上采用了一種稱(chēng)為代理分發(fā)的方式。首先會(huì)在AndroidManifest.xml中注冊(cè)兩種代理Service,這樣要啟動(dòng)插件Service的時(shí)候,我們都會(huì)啟動(dòng)這個(gè)代理Srevice,然后在onStartCommand()方法中進(jìn)行分發(fā)執(zhí)行插件的onStartCommand()方法。所以我們先來(lái)看看這兩個(gè)代理Service的注冊(cè)情況:

  <!-- Local Service running in main process -->
        <service android:name="com.didi.virtualapk.delegate.LocalService" />

        <!-- Daemon Service running in child process -->
        <service android:name="com.didi.virtualapk.delegate.RemoteService" android:process=":daemon">
            <intent-filter>
                <action android:name="${applicationId}.intent.ACTION_DAEMON_SERVICE" />
            </intent-filter>
        </service>

我們看到這里注冊(cè)了兩個(gè)代理服務(wù),一個(gè)是在主進(jìn)程中的,一個(gè)是在非主進(jìn)程中的,根據(jù)插件服務(wù)在的進(jìn)程進(jìn)行分別地啟動(dòng)。而且在前面的初始化我們已經(jīng)看到,一個(gè)是hook 了Instrumentation類(lèi)還有一個(gè)是hook了IActivityManager,我們來(lái)看看:

   private void hookSystemServices() {
        try {
            Singleton<IActivityManager> defaultSingleton = (Singleton<IActivityManager>) ReflectUtil.getField(ActivityManagerNative.class, null, "gDefault");
            IActivityManager activityManagerProxy = ActivityManagerProxy.newInstance(this, defaultSingleton.get());

            // Hook IActivityManager from ActivityManagerNative
            ReflectUtil.setField(defaultSingleton.getClass().getSuperclass(), defaultSingleton, "mInstance", activityManagerProxy);

            if (defaultSingleton.get() == activityManagerProxy) {
                this.mActivityManager = activityManagerProxy;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

 private void hookAMSForO() {
        try {
            Singleton<IActivityManager> defaultSingleton = (Singleton<IActivityManager>) ReflectUtil.getField(ActivityManager.class, null, "IActivityManagerSingleton");
            IActivityManager activityManagerProxy = ActivityManagerProxy.newInstance(this, defaultSingleton.get());
            ReflectUtil.setField(defaultSingleton.getClass().getSuperclass(), defaultSingleton, "mInstance", activityManagerProxy);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

我們看到根據(jù)不同android版本分別采用了不同的方式,但是最終都是通過(guò)動(dòng)態(tài)代理的方式將ActivityManagerProxy代理成我們自己的ActivityManagerProxy對(duì)象。這樣在調(diào)用AMS的時(shí)候,我們會(huì)走到自己的ActivityManagerProxy對(duì)象的invoke()方法來(lái)。我們來(lái)看看invoke()方法:

  @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if ("startService".equals(method.getName())) {
            try {
                return startService(proxy, method, args);
            } catch (Throwable e) {
                Log.e(TAG, "Start service error", e);
            }
        } else if ("stopService".equals(method.getName())) {
            try {
                return stopService(proxy, method, args);
            } catch (Throwable e) {
                Log.e(TAG, "Stop Service error", e);
            }
        } else if ("stopServiceToken".equals(method.getName())) {
            try {
                return stopServiceToken(proxy, method, args);
            } catch (Throwable e) {
                Log.e(TAG, "Stop service token error", e);
            }
        } else if ("bindService".equals(method.getName())) {
            try {
                return bindService(proxy, method, args);
            } catch (Throwable e) {
                e.printStackTrace();
            }
        } else if ("unbindService".equals(method.getName())) {
            try {
                return unbindService(proxy, method, args);
            } catch (Throwable e) {
                e.printStackTrace();
            }
        } else if ("getIntentSender".equals(method.getName())) {
            try {
                getIntentSender(method, args);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if ("overridePendingTransition".equals(method.getName())){
            try {
                overridePendingTransition(method, args);
            } catch (Exception e){
                e.printStackTrace();
            }
        }

        try {
            // sometimes system binder has problems.
            return method.invoke(this.mActivityManager, args);
        } catch (Throwable th) {
            Throwable c = th.getCause();
            if (c != null && c instanceof DeadObjectException) {
                // retry connect to system binder
                IBinder ams = ServiceManager.getService(Context.ACTIVITY_SERVICE);
                if (ams != null) {
                    IActivityManager am = ActivityManagerNative.asInterface(ams);
                    mActivityManager = am;
                }
            }

            Throwable cause = th;
            do {
                if (cause instanceof RemoteException) {
                    throw cause;
                }
            } while ((cause = cause.getCause()) != null);

            throw c != null ? c : th;
        }
    }

這個(gè)方法很簡(jiǎn)單,我們看到關(guān)于Service的所有操作都被攔截了,我們這里一個(gè)一個(gè)方法來(lái)講,首先我們看看startService()方法。

1.startService

  private Object startService(Object proxy, Method method, Object[] args) throws Throwable {
        IApplicationThread appThread = (IApplicationThread) args[0];
        Intent target = (Intent) args[1];
        ResolveInfo resolveInfo = this.mPluginManager.resolveService(target, 0);
        if (null == resolveInfo || null == resolveInfo.serviceInfo) {
            // is host service
            return method.invoke(this.mActivityManager, args);
        }

        return startDelegateServiceForTarget(target, resolveInfo.serviceInfo, null, RemoteService.EXTRA_COMMAND_START_SERVICE);
    }

我們看到這里的resolveService()方法跟Activity啟動(dòng)管理里面的resolveActivity()方法類(lèi)似,是根據(jù)intent的信息然后查找出來(lái)匹配的ServiceResolveInfo信息來(lái),然后判斷ResolveInfo如果為空則說(shuō)明是宿主程序中的服務(wù),否則會(huì)調(diào)用startDelegateServiceForTarget()方法進(jìn)行處理:

  private ComponentName startDelegateServiceForTarget(Intent target, ServiceInfo serviceInfo, Bundle extras, int command) {
        Intent wrapperIntent = wrapperTargetIntent(target, serviceInfo, extras, command);
        return mPluginManager.getHostContext().startService(wrapperIntent);
    }

我們看到這里會(huì)先調(diào)用wrapperTargetIntent()進(jìn)行將要啟動(dòng)插件的服務(wù)替換成前面提前注冊(cè)好的服務(wù),然后啟動(dòng)。我們看看這里的替換代碼:

 private Intent wrapperTargetIntent(Intent target, ServiceInfo serviceInfo, Bundle extras, int command) {
        // fill in service with ComponentName
        target.setComponent(new ComponentName(serviceInfo.packageName, serviceInfo.name));
        String pluginLocation = mPluginManager.getLoadedPlugin(target.getComponent()).getLocation();

        // start delegate service to run plugin service inside
        boolean local = PluginUtil.isLocalService(serviceInfo);
        Class<? extends Service> delegate = local ? LocalService.class : RemoteService.class;
        Intent intent = new Intent();
        intent.setClass(mPluginManager.getHostContext(), delegate);
        intent.putExtra(RemoteService.EXTRA_TARGET, target);
        intent.putExtra(RemoteService.EXTRA_COMMAND, command);
        intent.putExtra(RemoteService.EXTRA_PLUGIN_LOCATION, pluginLocation);
        if (extras != null) {
            intent.putExtras(extras);
        }

        return intent;
    }

我們看到這里的首先設(shè)置intent的Component為插件中服務(wù)的Component,然后獲取插件的位置,而且判斷是不是要啟動(dòng)的插件服務(wù)是在獨(dú)立的進(jìn)程中,接著就設(shè)置intent的class等等一些信息。最后將提前注冊(cè)好的Service啟動(dòng)。到這里我們的LocalServiceRemoteService就已經(jīng)啟動(dòng)了,這里的RemoteService是繼承LocalService的,多了一步創(chuàng)建Application的操作。我們看前面的Service的生命周期可以知道,啟動(dòng)Service的過(guò)程中,會(huì)回調(diào)onStartCommand()方法,所以我們?cè)谶@里面做相應(yīng)的操作即可,首先我們來(lái)看啟動(dòng)服務(wù)的回調(diào):

    case EXTRA_COMMAND_START_SERVICE: {
                ActivityThread mainThread = (ActivityThread)ReflectUtil.getActivityThread(getBaseContext());
                IApplicationThread appThread = mainThread.getApplicationThread();
                Service service;

                if (this.mPluginManager.getComponentsHandler().isServiceAvailable(component)) {
                    service = this.mPluginManager.getComponentsHandler().getService(component);
                } else {
                    try {
                        service = (Service) plugin.getClassLoader().loadClass(component.getClassName()).newInstance();

                        Application app = plugin.getApplication();
                        IBinder token = appThread.asBinder();
                        Method attach = service.getClass().getMethod("attach", Context.class, ActivityThread.class, String.class, IBinder.class, Application.class, Object.class);
                        IActivityManager am = mPluginManager.getActivityManager();

                        attach.invoke(service, plugin.getPluginContext(), mainThread, component.getClassName(), token, app, am);
                        service.onCreate();
                        this.mPluginManager.getComponentsHandler().rememberService(component, service);
                    } catch (Throwable t) {
                        return START_STICKY;
                    }
                }

                service.onStartCommand(target, 0, this.mPluginManager.getComponentsHandler().getServiceCounter(service).getAndIncrement());
                break;
            }

這個(gè)方法就是啟動(dòng)Service的方法,首先會(huì)調(diào)用isServiceAvailable()方法判斷服務(wù)是否已經(jīng)創(chuàng)建好緩存在mServices中了,如果有則不用重新創(chuàng)建直接獲取到Service然后調(diào)用它的onStartCommand方法,否則就重新反射創(chuàng)建Service,調(diào)用attach()方法,然后手動(dòng)調(diào)用Service的onCreate()方法,并將創(chuàng)建好的Service添加到緩存中。如果這塊代碼有點(diǎn)不懂的話(huà)那么可以認(rèn)真看framework層的代碼。

2.stopService

      case EXTRA_COMMAND_STOP_SERVICE: {
                Service service = this.mPluginManager.getComponentsHandler().forgetService(component);
                if (null != service) {
                    try {
                        service.onDestroy();
                    } catch (Exception e) {
                        Log.e(TAG, "Unable to stop service " + service + ": " + e.toString());
                    }
                } else {
                    Log.i(TAG, component + " not found");
                }
                break;
            }

我們看到停止服務(wù)比較簡(jiǎn)單,即時(shí)移除緩存中的Service,然后執(zhí)行他的onDestroy()方法即可。

3.bindService

  private Object bindService(Object proxy, Method method, Object[] args) throws Throwable {
        Intent target = (Intent) args[2];
        ResolveInfo resolveInfo = this.mPluginManager.resolveService(target, 0);
        if (null == resolveInfo || null == resolveInfo.serviceInfo) {
            // is host service
            return method.invoke(this.mActivityManager, args);
        }

        Bundle bundle = new Bundle();
        PluginUtil.putBinder(bundle, "sc", (IBinder) args[4]);
        startDelegateServiceForTarget(target, resolveInfo.serviceInfo, bundle, RemoteService.EXTRA_COMMAND_BIND_SERVICE);
        mPluginManager.getComponentsHandler().remberIServiceConnection((IBinder) args[4], target);
        return 1;
    }

我們看到綁定服務(wù)這里將IBinder存入了一個(gè)Bundle中,這個(gè)IBinder就是我們前面分析源碼時(shí)候提及的IServiceConnection類(lèi),然后通過(guò)startDelegateServiceForTarget()啟動(dòng)代理的Service,同樣地,最終會(huì)來(lái)到LocalServiceonStartCommand()方法中。

   case EXTRA_COMMAND_BIND_SERVICE: {
                ActivityThread mainThread = (ActivityThread)ReflectUtil.getActivityThread(getBaseContext());
                IApplicationThread appThread = mainThread.getApplicationThread();
                Service service = null;

                if (this.mPluginManager.getComponentsHandler().isServiceAvailable(component)) {
                    service = this.mPluginManager.getComponentsHandler().getService(component);
                } else {
                    try {
                        service = (Service) plugin.getClassLoader().loadClass(component.getClassName()).newInstance();

                        Application app = plugin.getApplication();
                        IBinder token = appThread.asBinder();
                        Method attach = service.getClass().getMethod("attach", Context.class, ActivityThread.class, String.class, IBinder.class, Application.class, Object.class);
                        IActivityManager am = mPluginManager.getActivityManager();

                        attach.invoke(service, plugin.getPluginContext(), mainThread, component.getClassName(), token, app, am);
                        service.onCreate();
                        this.mPluginManager.getComponentsHandler().rememberService(component, service);
                    } catch (Throwable t) {
                        t.printStackTrace();
                    }
                }
                try {
                    IBinder binder = service.onBind(target);
                    IBinder serviceConnection = PluginUtil.getBinder(intent.getExtras(), "sc");
                    IServiceConnection iServiceConnection = IServiceConnection.Stub.asInterface(serviceConnection);
                    if (Build.VERSION.SDK_INT >= 26) {
                        ReflectUtil.invokeNoException(IServiceConnection.class, iServiceConnection, "connected",
                                new Class[]{ComponentName.class, IBinder.class, boolean.class},
                                new Object[]{component, binder, false});
                    } else {
                        iServiceConnection.connected(component, binder);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            }

這里的代碼也并不復(fù)雜,主要做了幾件事,首先也是判斷緩存中有沒(méi)有創(chuàng)建好的Service,如果沒(méi)有則創(chuàng)建調(diào)用他的attach()方法和onCreate()方法,這里還有一個(gè)不同的地方是調(diào)用Service的onBind()方法,然后會(huì)調(diào)ServiceConnectionconnected()方法。

4.unbindService

  case EXTRA_COMMAND_UNBIND_SERVICE: {
                Service service = this.mPluginManager.getComponentsHandler().forgetService(component);
                if (null != service) {
                    try {
                        service.onUnbind(target);
                        service.onDestroy();
                    } catch (Exception e) {
                        Log.e(TAG, "Unable to unbind service " + service + ": " + e.toString());
                    }
                } else {
                    Log.i(TAG, component + " not found");
                }
                break;
            }

這個(gè)跟stopService差不多,就是多了一個(gè)在onDestroy前面調(diào)用了onUnbind()方法,這樣的話(huà),Service的整個(gè)啟動(dòng),停止,綁定,解綁等都已經(jīng)完成了。

還有在invoke()方法里面有一個(gè)stopServiceToken方法,這個(gè)方法的調(diào)用主要是在IntentService中的stopSelf()方法中會(huì)調(diào)用到,最終會(huì)調(diào)用mActivityManager.stopServiceToken方法,同樣的中轉(zhuǎn)到STOP操作即可.

總結(jié):到這里Service的管理我們也已經(jīng)講完了,整理來(lái)說(shuō)代碼邏輯不難,細(xì)節(jié)倒是非常多的,如果想要更深入了解,建議還是要認(rèn)真看一下FrameWork的源碼,希望大家能有所收獲。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容