BindeService
生活随笔
收集整理的這篇文章主要介紹了
BindeService
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?App 綁定service
fun bindService() {val i = Intent("com.example.iffyservice.Iffyservice")i.setPackage("com.example.iffyservice")if (bindService(i, this, Service.BIND_AUTO_CREATE)) {println("綁定成功")} else {println("綁定失敗")}} ContextImpl @Overridepublic boolean bindService(Intent service, ServiceConnection conn, int flags) {warnIfCallingFromSystemProcess();return bindServiceCommon(service, conn, flags, null, mMainThread.getHandler(), null,getUser());}private boolean bindServiceCommon(Intent service, ServiceConnection conn, int flags,String instanceName, Handler handler, Executor executor, UserHandle user) {//調用AMS的bindIsolatedServiceint res = ActivityManager.getService().bindIsolatedService(mMainThread.getApplicationThread(), getActivityToken(), service,service.resolveTypeIfNeeded(getContentResolver()),sd, flags, instanceName, getOpPackageName(), user.getIdentifier());}???? ActivityManagerService bindIsolatedService
public int bindIsolatedService(IApplicationThread caller, IBinder token, Intent service,String resolvedType, IServiceConnection connection, int flags, String instanceName,String callingPackage, int userId) throws TransactionTooLargeException {enforceNotIsolatedCaller("bindService");//調用ActiveServices的bindServiceLockedsynchronized(this) {return mServices.bindServiceLocked(caller, token, service,resolvedType, connection, flags, instanceName, callingPackage, userId);}}ActiveServices 啟動service
int bindServiceLocked(IApplicationThread caller, IBinder token, Intent service,String resolvedType, final IServiceConnection connection, int flags,String instanceName, String callingPackage, final int userId)throws TransactionTooLargeException {//BIND_AUTO_CREATE時候 創建serviceif ((flags&Context.BIND_AUTO_CREATE) != 0) {s.lastActivity = SystemClock.uptimeMillis();if (bringUpServiceLocked(s, service.getFlags(), callerFg, false,permissionsReviewRequired) != null) {return 0;}}}private String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg,boolean whileRestarting, boolean permissionsReviewRequired)throws TransactionTooLargeException {if (!isolated) {app = mAm.getProcessRecordLocked(procName, r.appInfo.uid, false);if (DEBUG_MU) Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid+ " app=" + app);if (app != null && app.thread != null) {try {app.addPackage(r.appInfo.packageName, r.appInfo.longVersionCode, mAm.mProcessStats);//啟動ServicerealStartServiceLocked(r, app, execInFg);return null;} catch (TransactionTooLargeException e) {throw e;} catch (RemoteException e) {Slog.w(TAG, "Exception when starting service " + r.shortInstanceName, e);}// If a dead object exception was thrown -- fall through to// restart the application.}} }private final void realStartServiceLocked(ServiceRecord r,ProcessRecord app, boolean execInFg) throws RemoteException {//ActivityThread startServiceapp.thread.scheduleCreateService(r, r.serviceInfo,mAm.compatibilityInfoForPackage(r.serviceInfo.applicationInfo),app.getReportedProcState());}ActivityThread
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;//Handler create ServicesendMessage(H.CREATE_SERVICE, s);}case CREATE_SERVICE:Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, ("serviceCreate: " + String.valueOf(msg.obj)));handleCreateService((CreateServiceData)msg.obj);Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);break;private void handleCreateService(CreateServiceData data) {//工廠用于創建下面這些東西 //public class AppComponentFactory* @see #instantiateApplication* @see #instantiateActivity* @see #instantiateClassLoader* @see #instantiateService* @see #instantiateReceiver* @see #instantiateProvider*/service = packageInfo.getAppFactory().instantiateService(cl, data.info.name, data.intent); }ActiveServices
int bindServiceLocked(IApplicationThread caller, IBinder token, Intent service,String resolvedType, final IServiceConnection connection, int flags,String instanceName, String callingPackage, final int userId)throws TransactionTooLargeException {//service已經存在就直接回調app的onServiceConnectedif (s.app != null && b.intent.received) {// Service is already running, so we can immediately// publish the connection.try {c.conn.connected(s.name, b.intent.binder, false);} catch (Exception e) {Slog.w(TAG, "Failure sending service " + s.shortInstanceName+ " to connection " + c.conn.asBinder()+ " (in " + c.binding.client.processName + ")", e);}// If this is the first app connected back to this binding,// and the service had previously asked to be told when// rebound, then do so.if (b.intent.apps.size() == 1 && b.intent.doRebind) {requestServiceBindingLocked(s, b.intent, callerFg, true);}} else if (!b.intent.requested) {//Service沒有bind的話就去bindrequestServiceBindingLocked(s, b.intent, callerFg, false);}}private final boolean requestServiceBindingLocked(ServiceRecord r, IntentBindRecord i,boolean execInFg, boolean rebind) throws TransactionTooLargeException {//thread 是 IApplicationThread zygote fork出來的r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind,r.app.getReportedProcState()); } ActivityThread.ApplicationThread public final void scheduleBindService(IBinder token, Intent intent,boolean rebind, int processState) {updateProcessState(processState, false);BindServiceData s = new BindServiceData();s.token = token;s.intent = intent;s.rebind = rebind;if (DEBUG_SERVICE)Slog.v(TAG, "scheduleBindService token=" + token + " intent=" + intent + " uid="+ Binder.getCallingUid() + " pid=" + Binder.getCallingPid());sendMessage(H.BIND_SERVICE, s);}public void handleMessage(Message msg) {case BIND_SERVICE:Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceBind");handleBindService((BindServiceData)msg.obj);Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);break;}private void handleBindService(BindServiceData data) {Service s = mServices.get(data.token);if (DEBUG_SERVICE)Slog.v(TAG, "handleBindService s=" + s + " rebind=" + data.rebind);if (s != null) {try {data.intent.setExtrasClassLoader(s.getClassLoader());data.intent.prepareToEnterProcess();try {if (!data.rebind) {IBinder binder = s.onBind(data.intent);//調用AMS publishServiceActivityManager.getService().publishService(data.token, data.intent, binder);}} catch (RemoteException ex) {throw ex.rethrowFromSystemServer();}} }}?
??? ActivityManagerService 發布Service
ActivityManagerService 發布Servicepublic void publishService(IBinder token, Intent intent, IBinder service) {// Refuse possible leaked file descriptorsif (intent != null && intent.hasFileDescriptors() == true) {throw new IllegalArgumentException("File descriptors passed in Intent");}synchronized(this) {if (!(token instanceof ServiceRecord)) {throw new IllegalArgumentException("Invalid service token");}mServices.publishServiceLocked((ServiceRecord)token, intent, service);}} ActiveServices ActiveServices void publishServiceLocked(ServiceRecord r, Intent intent, IBinder service) {for (int conni = connections.size() - 1; conni >= 0; conni--) {ArrayList<ConnectionRecord> clist = connections.valueAt(conni);for (int i=0; i<clist.size(); i++) {ConnectionRecord c = clist.get(i);c.conn.connected(r.name, service, false);}} }會調用client app的OnServiceconnected?
override fun onServiceConnected(name: ComponentName?, service: IBinder?) {mIMyAidlInterface =IMyAidlInterface.Stub.asInterface(service) }?
總結
以上是生活随笔為你收集整理的BindeService的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: c语言 方程改main的值_c语言mai
- 下一篇: .NET不用代码生成器自己写一个生成Co