<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??碼云GVP開源項目 12k star Uniapp+ElementUI 功能強大 支持多語言、二開方便! 廣告
                #### 9.3.1 Service的啟動過程 Service的啟動過程從ContextWrapper的startActivity開始,如下所示。 public ComponentName startService(Intent service) { return mBase.startService(service); } 上面代碼的mBase的類型是ContextImpl,在9.2節中我們知道,Activity被創建時會通過attach方法將一個ContextImpl對象關聯起來,這個ContextImpl對象就是上述代碼中的mBase。從ContextWrapper的實現可以看出,其大部分操作都是通過mBase來實現的,在設計模式中這是一種典型的橋接模式。下面繼續看ContextImpl的startActivity的實現,如下所示。 public ComponentName startService(Intent service) { warnIfCallingFromSystemProcess(); return startServiceCommon(service, mUser); } private ComponentName startServiceCommon(Intent service, UserHandle user) { try { validateServiceIntent(service); service.prepareToLeaveProcess(); ComponentName cn = ActivityManagerNative.getDefault().startService( mMainThread.getApplicationThread(), service, service.resolveTypeIfNeeded(getContentResolver()), user.get- Identifier()); if (cn ! = null) { if (cn.getPackageName().equals("! ")) { throw new SecurityException( "Not allowed to start service " + service + " without permission " + cn.getClassName()); } else if (cn.getPackageName().equals("! ! ")) { throw new SecurityException( "Unable to start service " + service + ": " + cn.getClassName()); } } return cn; } catch (RemoteException e) { return null; } } 在ContextImpl中,startService方法會調用startServiceCommon方法,而startService-Common方法又會通過ActivityManagerNative.getDefault()這個對象來啟動一個服務。對于ActivityManagerNative.getDefault()這個對象,我們應該有點印象,在9.2節中進行了詳細的分析,它實際上就是AMS(ActivityManagerService),這里就不再重復說明了。需要注意的是,在上述代碼中通過AMS來啟動服務的行為是一個遠程過程調用。AMS的startService方法的實現如下所示。 public ComponentName startService(IApplicationThread caller, Intent service, String resolvedType, int userId) { enforceNotIsolatedCaller("startService"); // Refuse possible leaked file descriptors if (service ! = null && service.hasFileDescriptors() == true) { throw new IllegalArgumentException("File descriptors passed in Intent"); } if (DEBUG_SERVICE) Slog.v(TAG, "startService: " + service + " type=" + resolvedType); synchronized(this) { final int callingPid = Binder.getCallingPid(); final int callingUid = Binder.getCallingUid(); final long origId = Binder.clearCallingIdentity(); ComponentName res = mServices.startServiceLocked(caller, service, resolvedType, callingPid, callingUid, userId); Binder.restoreCallingIdentity(origId); return res; } } 在上面的代碼中,AMS會通過mServices這個對象來完成Service后續的啟動過程,mServices對象的類型是ActiveServices, ActiveServices是一個輔助AMS進行Service管理的類,包括Service的啟動、綁定和停止等。在ActiveServices的startServiceLocked方法的尾部會調用startServiceInnerLocked方法,startServiceInnerLocked的實現如下所示。 ComponentName startServiceInnerLocked(ServiceMap smap, Intent service, ServiceRecord r, boolean callerFg, boolean addToStarting) { ProcessStats.ServiceState stracker = r.getTracker(); if (stracker ! = null) { stracker.setStarted(true, mAm.mProcessStats.getMemFactorLocked(), r.lastActivity); } r.callStart = false; synchronized (r.stats.getBatteryStats()) { r.stats.startRunningLocked(); } String error = bringUpServiceLocked(r, service.getFlags(), callerFg, false); if (error ! = null) { return new ComponentName("! ! ", error); } if (r.startRequested && addToStarting) { boolean first = smap.mStartingBackground.size() == 0; smap.mStartingBackground.add(r); r.startingBgTimeout = SystemClock.uptimeMillis() + BG_START_TIMEOUT; if (DEBUG_DELAYED_SERVICE) { RuntimeException here = new RuntimeException("here"); here.fillInStackTrace(); Slog.v(TAG, "Starting background (first=" + first + "): " + r, here); } else if (DEBUG_DELAYED_STARTS) { Slog.v(TAG, "Starting background (first=" + first + "): " + r); } if (first) { smap.rescheduleDelayedStarts(); } } else if (callerFg) { smap.ensureNotStartingBackground(r); } return r.name; } 在上述代碼中,ServiceRecord描述的是一個Service記錄,ServiceRecord一直貫穿著整個Service的啟動過程。startServiceInnerLocked方法并沒有完成具體的啟動工作,而是把后續的工作交給了bringUpServiceLocked方法來處理,在bringUpServiceLocked方法中又調用了realStartServiceLocked方法。從名字上來看,這個方法應該是真正地啟動一個Service,它的實現如下所示。 private final void realStartServiceLocked(ServiceRecord r, ProcessRecord app, boolean execInFg) throws RemoteException { ... boolean created = false; try { String nameTerm; int lastPeriod = r.shortName.lastIndexOf('.'); nameTerm = lastPeriod >= 0 ? r.shortName.substring(lastPeriod) : r.shortName; if (LOG_SERVICE_START_STOP) { EventLogTags.writeAmCreateService( r.userId, System.identityHashCode(r), nameTerm, r.app. uid, r.app.pid); } synchronized (r.stats.getBatteryStats()) { r.stats.startLaunchedLocked(); } mAm.ensurePackageDexOpt(r.serviceInfo.packageName); app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE); app.thread.scheduleCreateService(r, r.serviceInfo, mAm.compatibilityInfoForPackageLocked(r.serviceInfo. applicationInfo), app.repProcState); r.postNotification(); created = true; } catch (DeadObjectException e) { Slog.w(TAG, "Application dead when creating service " + r); mAm.appDiedLocked(app); } finally { if (! created) { app.services.remove(r); r.app = null; scheduleServiceRestartLocked(r, false); return; } } requestServiceBindingsLocked(r, execInFg); updateServiceClientActivitiesLocked(app, null, true); // If the service is in the started state, and there are no // pending arguments, then fake up one so its onStartCommand() will // be called. if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) { r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.make- NextStartId(), null, null)); } sendServiceArgsLocked(r, execInFg, true); ... } 在realStartServiceLocked方法中,首先通過app.thread的scheduleCreateService方法來創建Service對象并調用其onCreate,接著再通過sendServiceArgsLocked方法來調用Service的其他方法,比如onStartCommand,這兩個過程均是進程間通信。app.thread對象是IApplicationThread類型,它實際上是一個Binder,它的具體實現是ApplicationThread和ApplicationThreadNative,在9.2節已經對這個問題做了說明。由于ApplicationThread繼承了ApplicationThreadNative,因此只需要看ApplicationThread對Service啟動過程的處理即可,這對應著它的scheduleCreateService方法,如下所示。 public final void scheduleCreateService(IBinder token, ServiceInfo info, CompatibilityInfo compatInfo, int processState) { updateProcessState(processState, false); CreateServiceData s = new CreateServiceData(); s.token = token; s.info = info; s.compatInfo = compatInfo; sendMessage(H.CREATE_SERVICE, s); } 很顯然,這個過程和Activity的啟動過程是類似的,都是通過發送消息給Handler H來完成的。H會接收這個CREATE_SERVICE消息并通過ActivityThread的handleCreateService方法來完成Service的最終啟動,handleCreateService的源碼如下所示。 private void handleCreateService(CreateServiceData data) { // If we are getting ready to gc after going to the background, well // we are back active so skip it. unscheduleGcIdler(); LoadedApk packageInfo = getPackageInfoNoCheck( data.info.applicationInfo, data.compatInfo); Service service = null; try { java.lang.ClassLoader cl = packageInfo.getClassLoader(); service = (Service) cl.loadClass(data.info.name).newInstance(); } catch (Exception e) { if (! mInstrumentation.onException(service, e)) { throw new RuntimeException( "Unable to instantiate service " + data.info.name + ": " + e.toString(), e); } } try { if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name); ContextImpl context = ContextImpl.createAppContext(this, packageInfo); context.setOuterContext(service); Application app = packageInfo.makeApplication(false, mInstrumen- tation); service.attach(context, this, data.info.name, data.token, app, ActivityManagerNative.getDefault()); service.onCreate(); mServices.put(data.token, service); try { ActivityManagerNative.getDefault().serviceDoneExecuting( data.token, 0, 0, 0); } catch (RemoteException e) { // nothing to do. } } catch (Exception e) { if (! mInstrumentation.onException(service, e)) { throw new RuntimeException( "Unable to create service " + data.info.name + ": " + e.toString(), e); } } } handleCreateService主要完成了如下幾件事。 首先通過類加載器創建Service的實例。 然后創建Application對象并調用其onCreate,當然Application的創建過程只會有一次。 接著創建ConTextImpl對象并通過Service的attach方法建立二者之間的關系,這個過程和Activity實際上是類似的,畢竟Service和Activity都是一個Context。 最后調用Service的onCreate方法并將Service對象存儲到ActivityThread中的一個列表中。這個列表的定義如下所示。 final ArrayMap<IBinder, Service> mServices = new ArrayMap<IBinder, Service>() 由于Service的onCreate方法被執行了,這也意味著Service已經啟動了。除此之外,ActivityThread中還會通過handleServiceArgs方法調用Service的onStartCommand方法,如下所示。 private void handleServiceArgs(ServiceArgsData data) { Service s = mServices.get(data.token); if (s ! = null) { try { if (data.args ! = null) { data.args.setExtrasClassLoader(s.getClassLoader()); data.args.prepareToEnterProcess(); } int res; if (! data.taskRemoved) { res = s.onStartCommand(data.args, data.flags, data.startId); } else { s.onTaskRemoved(data.args); res = Service.START_TASK_REMOVED_COMPLETE; } QueuedWork.waitToFinish(); try { ActivityManagerNative.getDefault().serviceDoneExecuting( data.token, 1, data.startId, res); } catch (RemoteException e) { // nothing to do. } ensureJitEnabled(); } catch (Exception e) { if (! mInstrumentation.onException(s, e)) { throw new RuntimeException( "Unable to start service " + s + " with " + data.args + ": " + e.toString(), e); } } } } 到這里,Service的啟動過程已經分析完了,下面分析Service的綁定過程。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看