精华内容
参与话题
问答
  • bindService

    2019-10-07 18:14:17
    如果服务和访问者之间需要方法调用和传递参数,调用bindservice()和unbindService()方法启动和关闭服务。  绑定:如果service没被创建,那么调用一次onCreate(),然后调用onBind(), 多次绑定时,不会多次调用on...

      如果服务和访问者之间需要方法调用和传递参数,调用bindservice()和unbindService()方法启动和关闭服务。

      绑定:如果service没被创建,那么调用一次onCreate(),然后调用onBind(),
    多次绑定时,不会多次调用onBind()
      解除绑定:调用unbindService(),然后onDestory().不可以多次调用unbindService()方法解除绑定。

      原理:

      客户端调用bindService()启动服务-----》服务端向客服端返回一个Ibinder对象----》客户端透过binder对象调用服务端的方法

      一个实例:

      服务端的代码

    import android.app.Service;

    import android.content.Intent;

    import android.os.Binder;

    import android.os.IBinder;

    public class StudentService extends Service {

     private String[] names = {"张帆","拉法基","老子有把杀猪刀"};

     private Binder binder = new StudentBinder();

     

     public String query(int no){

      if(no>0&&no<4){

       return names[no-1];

      }else {

       return null;

      }

     }

     public IBinder onBind(Intent arg0) {

      return binder;

     }

     

     private class StudentBinder extends Binder implements IStudent{

      public String queryStudent(int no) {

       return query(no);

      }

     }

    }

      StudentBinder是私有的,所以定义一个接口让客户端透过binder对象调用服务端的方法, Binder实现了 IBinder接口,所以继承Binder即可。

    接口:

      public interface IStudent {
                    public String queryStudent(int no);
    }

    客服端即activity

     

    import android.os.Bundle;
    import android.os.IBinder;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.app.Activity;
    import android.content.ComponentName;
    import android.content.Intent;
    import android.content.ServiceConnection;

    public class MainActivity extends Activity {
     private EditText studentno;
     private ServiceConnection conn = new StudentServiceConnection();
     private IStudent iStudent;
     private TextView resultView;
     protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
      
      resultView  = (TextView)this.findViewById(R.id.resultView);
      studentno = (EditText)this.findViewById(R.id.studentno);
      Button button = (Button)this.findViewById(R.id.button);
      button.setOnClickListener(new ButtonClickListener());
      Intent service = new Intent(this,StudentService.class);
      bindService(service, conn, BIND_AUTO_CREATE);// 客户端调用bindService()启动服务
     }


     private class StudentServiceConnection implements ServiceConnection{

      public void onServiceConnected(ComponentName arg0, IBinder arg1) {
           iStudent =(IStudent)arg1;
      }

      @Override
      public void onServiceDisconnected(ComponentName arg0) {
       iStudent = null;
      }
      
     }
     
     protected void onDestroy() {
      unbindService(conn);//解除跟服务的绑定
      super.onDestroy();
     }
     private final class ButtonClickListener implements View.OnClickListener{

      public void onClick(View v) {
       String no =studentno.getText().toString();
       String name = iStudent.queryStudent(Integer.valueOf(no));
       resultView.setText(name);
       
      }
      
     }

    }

    转载于:https://www.cnblogs.com/zyandroid/archive/2013/06/13/3134165.html

    展开全文
  • BindService

    2015-11-13 11:39:49
    示例:后台播放音乐和天气类软件的前台Service。首先Service和Activity都是运行在主线程...启动方式有startService和bindService两种。以bindService的方式启动Service时可以与Activity进行交互,所以只写这种用法。//

    Service是程序后台运行的体现,需要在Androidmanifest文件中注册。示例:后台播放音乐和天气类软件的前台Service。

    首先Service和Activity都是运行在主线程里的,另外Service与线程一点关系都没有。

    启动方式有startService和bindService两种。以bindService的方式启动Service时可以与Activity进行交互,所以只写这种用法。

    //MainActivity.java
    public class MainActivity extends Activity implements OnClickListener{
    
        Button btn1,btn2,btn3,btn4;
        Intent intent1;
        MyService service;
        /*--*/
        ServiceConnection conn = new ServiceConnection() {
    
            @Override/*Activity与Service异常解除关联时执行此方法*/
            public void onServiceDisconnected(ComponentName arg0) {
                // TODO Auto-generated method stub          
            }
    
            @Override/*Activity与Service关联时执行此方法*/
            public void onServiceConnected(ComponentName arg0, IBinder binder) {
                // TODO Auto-generated method stub
                /*下面语句的作用就是当Activity与Service关联时获取该Service对象(总不能NEW一个Service对象用吧)*/
                service=((MyService.MyBinder)binder).getService();
                System.out.println("Conn--->onServiceConnected()");     
            }
        };
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            btn1=(Button) findViewById(R.id.button1);
            btn2=(Button) findViewById(R.id.button2);
            btn3=(Button) findViewById(R.id.button3);
            btn4=(Button) findViewById(R.id.button4);
            btn1.setOnClickListener(this);
            btn2.setOnClickListener(this);
            btn3.setOnClickListener(this);
            btn4.setOnClickListener(this);
    
        }
        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            switch(arg0.getId())
            {
            case R.id.button1:
            /*用intent关联Activity与Service并通过bindService启动服务*/
                intent1 = new Intent(MainActivity.this,MyService.class);
                bindService(intent1,conn,Service.BIND_AUTO_CREATE);
                break;
            case R.id.button2:
                service.Paly();
                break;
            case R.id.button3:
                service.Stop();
                break;
            case R.id.button4:
            /*解除绑定*/
                unbindService(conn);
                break;
            }
        }
    
    }
    //MyService.java
    public class MyService extends Service{
        /*在MyService中写一个MyBinder内部类我感觉是介于ServiceConnection中方法的参数*/
        public class MyBinder extends Binder{
            public MyService getService(){
                return MyService.this;
            }
    
        }
        public void Paly(){
            System.out.println("Service--->Paly()");
    
        }
        public void Stop(){
            System.out.println("Service--->Stop()");
    
        }
    
        @Override
        public IBinder onBind(Intent arg0) {
            // TODO Auto-generated method stub
            System.out.println("Service--->onBind()");
            return new MyBinder();
        }
    
        @Override
        public void unbindService(ServiceConnection conn) {
            // TODO Auto-generated method stub
            System.out.println("Service--->unbindService()");
            super.unbindService(conn);
        }
    
        @Override
        public void onCreate() {
            // TODO Auto-generated method stub
            super.onCreate();
            System.out.println("Service--->onCreate()");
        }
    
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            // TODO Auto-generated method stub
            System.out.println("Service--->onStartCommand()");
            return super.onStartCommand(intent, flags, startId);
        }
    
        @Override
        public void onDestroy() {
            // TODO Auto-generated method stub
            super.onDestroy();
            System.out.println("Service--->onStartCommand()");
        }
    }
    展开全文
  • bindservice流程

    2017-07-09 18:14:02
    bindservice流程

    bindservice流程

    • android.app.ContextImpl#bindService

      @Override
      public boolean bindService(Intent service, ServiceConnection conn,
              int flags) {
          warnIfCallingFromSystemProcess();
          return bindServiceCommon(service, conn, flags, mMainThread.getHandler(),
                  Process.myUserHandle());
      }
      
      private boolean bindServiceCommon(Intent service, ServiceConnection conn, int flags, Handler
              handler, UserHandle user) {
          IServiceConnection sd;
          if (conn == null) {
              throw new IllegalArgumentException("connection is null");
          }
          if (mPackageInfo != null) {
              sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(), handler, flags);
          } else {
              throw new RuntimeException("Not supported in system context");
          }
          validateServiceIntent(service);
          try {
              IBinder token = getActivityToken();
              if (token == null && (flags&BIND_AUTO_CREATE) == 0 && mPackageInfo != null
                      && mPackageInfo.getApplicationInfo().targetSdkVersion
                      < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                  flags |= BIND_WAIVE_PRIORITY;
              }
              service.prepareToLeaveProcess(this);
              // 1. 这里是调用了服务端的bindService
              int res = ActivityManagerNative.getDefault().bindService(
                  mMainThread.getApplicationThread(), getActivityToken(), service,
                  service.resolveTypeIfNeeded(getContentResolver()),
                  sd, flags, getOpPackageName(), user.getIdentifier());
              if (res < 0) {
                  throw new SecurityException(
                          "Not allowed to bind to service " + service);
              }
              return res != 0;
          } catch (RemoteException e) {
              throw e.rethrowFromSystemServer();
          }
      }
      
    • ActivityManagerProxy代理的真正的是ActivityManagerNative子类ActivityManagerService

    • android.app.ActivityManagerProxy#bindService

      public int bindService(IApplicationThread caller, IBinder token,
              Intent service, String resolvedType, IServiceConnection connection,
              int flags,  String callingPackage, int userId) throws RemoteException {
          Parcel data = Parcel.obtain();
          Parcel reply = Parcel.obtain();
          data.writeInterfaceToken(IActivityManager.descriptor);
          data.writeStrongBinder(caller != null ? caller.asBinder() : null);
          data.writeStrongBinder(token);
          service.writeToParcel(data, 0);
          data.writeString(resolvedType);
          data.writeStrongBinder(connection.asBinder());
          data.writeInt(flags);
          data.writeString(callingPackage);
          data.writeInt(userId);
          // 2. 代理调接口跟服务端通信,这里走到服务端
          mRemote.transact(BIND_SERVICE_TRANSACTION, data, reply, 0);
          reply.readException();
          int res = reply.readInt();
          data.recycle();
          reply.recycle();
          return res;
      }
      
    • public abstract class ActivityManagerNative extends Binder implements IActivityManager

      @Override
      public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
              throws RemoteException {
          // 4. 子类调用了父类的onTransact
          case BIND_SERVICE_TRANSACTION: {
              data.enforceInterface(IActivityManager.descriptor);
              IBinder b = data.readStrongBinder();
              IApplicationThread app = ApplicationThreadNative.asInterface(b);
              IBinder token = data.readStrongBinder();
              Intent service = Intent.CREATOR.createFromParcel(data);
              String resolvedType = data.readString();
              b = data.readStrongBinder();
              int fl = data.readInt();
              String callingPackage = data.readString();
              int userId = data.readInt();
              IServiceConnection conn = IServiceConnection.Stub.asInterface(b);
              // 5. 这里调用了子类中的bindService不是代理类中的
              int res = bindService(app, token, service, resolvedType, conn, fl,
                      callingPackage, userId);
              reply.writeNoException();
              reply.writeInt(res);
              return true;
          }
      }
      
    • com.android.server.am.ActivityManagerService extends ActivityManagerNative

      @Override
      public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
              throws RemoteException {
          try {
              // 3. 这里会调用父类的onTransact方法
              return super.onTransact(code, data, reply, flags);
          } catch (RuntimeException e) {
              // The activity manager only throws security exceptions, so let's
              // log all others.
              if (!(e instanceof SecurityException)) {
                  Slog.wtf(TAG, "Activity Manager Crash", e);
              }
              throw e;
          }
      }
      
      public int bindService(IApplicationThread caller, IBinder token, Intent service,
          String resolvedType, IServiceConnection connection, int flags, String callingPackage,
          int userId) throws TransactionTooLargeException {
          enforceNotIsolatedCaller("bindService");
      
          // 6. 执行绑定服务的操作
          synchronized(this) {
              return mServices.bindServiceLocked(caller, token, service,
                      resolvedType, connection, flags, callingPackage, userId);
          }
      }
      

    总结:

    • 1.ContextImpl#bindService
    • 2.ActivityManagerNative.getDefault().bindService
    • 3.ActivityManagerProxy#bindService —> mRemote.transact
    • 4.ActivityManagerService.onTransact
    • 5.ActivityManagerNative.onTransact
    • 6.调用子类的bindService即ActivityManagerService.bindService
    展开全文
  • bindService过程

    2019-03-27 02:33:27
    发起方的ServiceConnection对象作为bindService参数 ContextWrapper.java 复制代码 public boolean bindService(Intent service, ServiceConnection conn, int flags) { return mBase.bindService(ser...

    发起绑定

    发起方的ServiceConnection对象作为bindService参数

    ContextWrapper.java
    复制代码
        public boolean bindService(Intent service, ServiceConnection conn,
                int flags) {
            return mBase.bindService(service, conn, flags);
        }
    复制代码
    ContextImpl.java
    复制代码
        public boolean bindService(Intent service, ServiceConnection conn,
                int flags) {
            warnIfCallingFromSystemProcess();
            return bindServiceCommon(service, conn, flags, Process.myUserHandle());
        }
    
    private boolean bindServiceCommon(Intent service, ServiceConnection conn, int flags,
                UserHandle user) {
            IServiceConnection sd;
            if (conn == null) {
                throw new IllegalArgumentException("connection is null");
            }
            if (mPackageInfo != null) {
                sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(),
                        mMainThread.getHandler(), flags);
            } else {
                throw new RuntimeException("Not supported in system context");
            }
            validateServiceIntent(service);
            try {
                IBinder token = getActivityToken();
                if (token == null && (flags&BIND_AUTO_CREATE) == 0 && mPackageInfo != null
                        && mPackageInfo.getApplicationInfo().targetSdkVersion
                        < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                    flags |= BIND_WAIVE_PRIORITY;
                }
                service.prepareToLeaveProcess();
                int res = ActivityManagerNative.getDefault().bindService(
                    mMainThread.getApplicationThread(), getActivityToken(), service,
                    service.resolveTypeIfNeeded(getContentResolver()),
                    sd, flags, getOpPackageName(), user.getIdentifier());
                if (res < 0) {
                    throw new SecurityException(
                            "Not allowed to bind to service " + service);
                }
                return res != 0;
            } catch (RemoteException e) {
                throw new RuntimeException("Failure from system", e);
            }
        }
    复制代码
    ActivityManagerNative.java
    复制代码
        public int bindService(IApplicationThread caller, IBinder token,
                Intent service, String resolvedType, IServiceConnection connection,
                int flags,  String callingPackage, int userId) throws RemoteException {
            Parcel data = Parcel.obtain();
            Parcel reply = Parcel.obtain();
            data.writeInterfaceToken(IActivityManager.descriptor);
            data.writeStrongBinder(caller != null ? caller.asBinder() : null);
            data.writeStrongBinder(token);
            service.writeToParcel(data, 0);
            data.writeString(resolvedType);
            data.writeStrongBinder(connection.asBinder());
            data.writeInt(flags);
            data.writeString(callingPackage);
            data.writeInt(userId);
            mRemote.transact(BIND_SERVICE_TRANSACTION, data, reply, 0);
            reply.readException();
            int res = reply.readInt();
            data.recycle();
            reply.recycle();
            return res;
        }
    复制代码

    mRemote为IActivityManager类型。

    ActivityManagerService.java
    复制代码
        public int bindService(IApplicationThread caller, IBinder token, Intent service,
                String resolvedType, IServiceConnection connection, int flags, String callingPackage,
                int userId) throws TransactionTooLargeException {
            enforceNotIsolatedCaller("bindService");
            synchronized(this) {
                return mServices.bindServiceLocked(caller, token, service,
                        resolvedType, connection, flags, callingPackage, userId);
            }
        }
    复制代码
    ActiveServices.java
    复制代码
    int bindServiceLocked(IApplicationThread caller, IBinder token, Intent service,
                String resolvedType, IServiceConnection connection, int flags,
                String callingPackage, int userId) throws TransactionTooLargeException {
        if ((flags&Context.BIND_AUTO_CREATE) != 0) {
                    s.lastActivity = SystemClock.uptimeMillis();
                    if (bringUpServiceLocked(s, service.getFlags(), callerFg, false) != null) {
                        return 0;
                    }
                }
    }
    
    private final String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg,
                boolean whileRestarting) throws TransactionTooLargeException {
                // Not running -- get it started, and enqueue this service record
            // to be executed when the app comes up.
             if (app != null && app.thread != null) {
                    try {
                        app.addPackage(r.appInfo.packageName, r.appInfo.versionCode, mAm.mProcessStats);
                        realStartServiceLocked(r, app, execInFg);
                        return null;
                    } catch (TransactionTooLargeException e) {
            ...
            if (app == null) {
                if ((app=mAm.startProcessLocked(procName, r.appInfo, true, intentFlags,
                        "service", r.name, false, isolated, false)) == null) {
                    String msg = "Unable to launch app "
                            + r.appInfo.packageName + "/"
                            + r.appInfo.uid + " for service "
                            + r.intent.getIntent() + ": process is bad";
                    Slog.w(TAG, msg);
                    bringDownServiceLocked(r);
                    return msg;
                }
                if (isolated) {
                    r.isolatedProc = app;
                }
            }
    }
    
     private final void realStartServiceLocked(ServiceRecord r,
                ProcessRecord app, boolean execInFg) throws RemoteException {
        app.thread.scheduleCreateService(r, r.serviceInfo,
            mAm.compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo),app.repProcState);
                }//进入service的onCreate
        ...
        requestServiceBindingsLocked(r, execInFg);//绑定
    复制代码
    ApplicationThreadNative.java
    复制代码
        public final void scheduleCreateService(IBinder token, ServiceInfo info,
                CompatibilityInfo compatInfo, int processState) throws RemoteException {
            Parcel data = Parcel.obtain();
            data.writeInterfaceToken(IApplicationThread.descriptor);
            data.writeStrongBinder(token);
            info.writeToParcel(data, 0);
            compatInfo.writeToParcel(data, 0);
            data.writeInt(processState);
            try {
                mRemote.transact(SCHEDULE_CREATE_SERVICE_TRANSACTION, data, null,
                        IBinder.FLAG_ONEWAY);
            } catch (TransactionTooLargeException e) {
                Log.e("CREATE_SERVICE", "Binder failure starting service; service=" + info);
                throw e;
            }
            data.recycle();
        }
    复制代码

    创建Application对象并进入service的onCreate方法

    ActivityThread.java
    复制代码
            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);
            }
        
         private void handleCreateService(CreateServiceData data) {
         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, mInstrumentation);
                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, SERVICE_DONE_EXECUTING_ANON, 0, 0);
                } catch (RemoteException e) {
                    // nothing to do.
                }
            } 
         }
    复制代码

    服务进程创建完成后,调用requestServiceBindingsLocked(r, execInFg);绑定。

    ActiveServices.java
    复制代码
        private final void requestServiceBindingsLocked(ServiceRecord r, boolean execInFg)
                throws TransactionTooLargeException {
            for (int i=r.bindings.size()-1; i>=0; i--) {
                IntentBindRecord ibr = r.bindings.valueAt(i);
                if (!requestServiceBindingLocked(r, ibr, execInFg, false)) {
                    break;
                }
            }
        }
    
        private final boolean requestServiceBindingLocked(ServiceRecord r, IntentBindRecord i,
                boolean execInFg, boolean rebind) throws TransactionTooLargeException {
                    bumpServiceExecutingLocked(r, execInFg, "bind");
                    r.app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
                    r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind,
                            r.app.repProcState);
        }
    复制代码
    ApplicationThreadNative.java
    复制代码
        public final void scheduleBindService(IBinder token, Intent intent, boolean rebind,
                int processState) throws RemoteException {
            Parcel data = Parcel.obtain();
            data.writeInterfaceToken(IApplicationThread.descriptor);
            data.writeStrongBinder(token);
            intent.writeToParcel(data, 0);
            data.writeInt(rebind ? 1 : 0);
            data.writeInt(processState);
            mRemote.transact(SCHEDULE_BIND_SERVICE_TRANSACTION, data, null,
                    IBinder.FLAG_ONEWAY);
            data.recycle();
        }
    复制代码

    进入Service的onBind

    ActivityThread.java
    复制代码
            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);
            }
        
            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) {
                            IBinder binder = s.onBind(data.intent);//进入Service的onBind
                            ActivityManagerNative.getDefault().publishService(
                                    data.token, data.intent, binder);//通过onServiceConnected回调将binder对象返回给Service
                        } else {
                            s.onRebind(data.intent);
                            ActivityManagerNative.getDefault().serviceDoneExecuting(
                                    data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
                        }
                       
            }
        }
    复制代码

    回调ServiceConnection的onServiceConnected

    ActivityManagerNative.java
    复制代码
        public void publishService(IBinder token,
                Intent intent, IBinder service) throws RemoteException {
            Parcel data = Parcel.obtain();
            Parcel reply = Parcel.obtain();
            data.writeInterfaceToken(IActivityManager.descriptor);
            data.writeStrongBinder(token);
            intent.writeToParcel(data, 0);
            data.writeStrongBinder(service);
            mRemote.transact(PUBLISH_SERVICE_TRANSACTION, data, reply, 0);
            reply.readException();
            data.recycle();
            reply.recycle();
        }
    复制代码

    mRemote为IActivityManager类型

    ActivityManagerService.java
    复制代码
        public void publishService(IBinder token, Intent intent, IBinder service) {
            // Refuse possible leaked file descriptors
            if (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.java
    复制代码
        void publishServiceLocked(ServiceRecord r, Intent intent, IBinder service) {
            final long origId = Binder.clearCallingIdentity();
            try {
                if (r != null) {
                    Intent.FilterComparison filter
                            = new Intent.FilterComparison(intent);
                    IntentBindRecord b = r.bindings.get(filter);
                    if (b != null && !b.received) {
                        b.binder = service;
                        b.requested = true;
                        b.received = true;
                        for (int conni=r.connections.size()-1; conni>=0; conni--) {
                            ArrayList<ConnectionRecord> clist = r.connections.valueAt(conni);
                            for (int i=0; i<clist.size(); i++) {
                                ConnectionRecord c = clist.get(i);
                                if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Publishing to: " + c);
                                try {
                                    c.conn.connected(r.name, service);
                                } catch (Exception e) {
                                    Slog.w(TAG, "Failure sending service " + r.name +
                                          " to connection " + c.conn.asBinder() +
                                          " (in " + c.binding.client.processName + ")", e);
                                }
                            }
                        }
                    }
    
                    serviceDoneExecutingLocked(r, mDestroyingServices.contains(r), false);
                }
            } finally {
                Binder.restoreCallingIdentity(origId);
            }
        }
    复制代码
    LoadedApk.java
    复制代码
            private static class InnerConnection extends IServiceConnection.Stub {
                final WeakReference<LoadedApk.ServiceDispatcher> mDispatcher;
    
                InnerConnection(LoadedApk.ServiceDispatcher sd) {
                    mDispatcher = new WeakReference<LoadedApk.ServiceDispatcher>(sd);
                }
    
                public void connected(ComponentName name, IBinder service) throws RemoteException {
                    LoadedApk.ServiceDispatcher sd = mDispatcher.get();
                    if (sd != null) {
                        sd.connected(name, service);
                    }
                }
            }
    
     static final class ServiceDispatcher {
             ServiceDispatcher(ServiceConnection conn,
                    Context context, Handler activityThread, int flags) {
                mIServiceConnection = new InnerConnection(this);
                mConnection = conn;
                mContext = context;
                mActivityThread = activityThread;
                mLocation = new ServiceConnectionLeaked(null);
                mLocation.fillInStackTrace();
                mFlags = flags;
            }
     
             public void connected(ComponentName name, IBinder service) {
                if (mActivityThread != null) {
                    mActivityThread.post(new RunConnection(name, service, 0));//新建RunConnection任务,在该任务中回调onServiceConnected
                } else {
                    doConnected(name, service);
                }
            }
     }
     
             private final class RunConnection implements Runnable {
                RunConnection(ComponentName name, IBinder service, int command) {
                    mName = name;
                    mService = service;
                    mCommand = command;
                }
    
                public void run() {
                    if (mCommand == 0) {
                        doConnected(mName, mService);
                    } else if (mCommand == 1) {
                        doDeath(mName, mService);
                    }
                }
    
                final ComponentName mName;
                final IBinder mService;
                final int mCommand;
            }
     
             public void doConnected(ComponentName name, IBinder service) {
                // If there was an old service, it is not disconnected.
                if (old != null) {
                    mConnection.onServiceDisconnected(name);
                }
                // If there is a new service, it is now connected.
                if (service != null) {
                    mConnection.onServiceConnected(name, service);//回调ServiceConnection的onServiceConnected
                }
            }
    复制代码

    至此。onBind方法返回Ibinder对象就通过发起方的ServiceConnection的onServiceConnected返回了。

    转载于:https://juejin.im/post/5c998aabe51d452a12197f09

    展开全文
  • BindService总结

    千次阅读 2013-08-25 12:56:28
    BindService介绍。
  • bindService流程

    2020-03-11 23:02:46
    bindService(i, object : ServiceConnection { override fun onServiceDisconnected(p0: ComponentName?) { } override fun onServiceConnected(p0: Compon...
  • Android bindservice失败解决方法 现象: this.bindService(bindIntent, conn, Context.BIND_AUTO_CREATE); 相同的代码以前使用一直很正常,但最近在项目中使用却一直绑定失败,bindservice返回false。 原因: 使用...
  • android studio BindService

    千次阅读 2020-10-12 10:01:49
    public class BindServiceActivity extends AppCompatActivity implements View.OnClickListener { private static final String TAG = "BindServiceActivity"; private Button mBtBindService; private Button ...
  • bindService源码分析

    2020-03-28 02:28:47
    bindService AIDL中使用了 bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE)进行服务绑定,这里对这个方法进行源码分析。 调用了ContextWrapper中的 @Override public boolean bindService...
  • s type hierarchy to find <code>BindService</code>. This is brittle because other code gen tools could have placed <code>BindService</code> in a different location. <p>What about adding an attribute ...
  • Android中有两种主要方式使用Service,通过调用Context的startService方法或调用Context的bindService方法,本文只探讨纯bindService的使用,不涉及任何startService方法调用的情况。如果想了解startService相关的...
  • BindService详解

    千次阅读 2016-04-27 16:19:16
    Service启动得两种方式分别为startService()、bindService(),但是他们的使用场景是不一样的。。。
  • BindService标准写法

    2019-05-09 14:59:03
    BindService标准写法 在使用bindservice时,经常会忽略掉死亡回调的作用,下面提供一个标准的bindService的使用流程,仅供参考 import android.app.Activity; import android.content.ComponentName; import ...
  • bindservice返回值问题

    2019-03-21 10:04:14
    在极端的情况下bindservice返回值为true但是可能运行的是onServiceDisconnected方法,所以不能按照bindservice的返回值来判断是否连接成功。 通过源码也可以看出bindservice在连接过程中可能会走到...
  • bindService的使用

    2020-05-01 00:44:04
    bindService与starService之间的区别: 在程序通过startService()方法启动的服务,会长期在后台运行,并且启动服务的组件与服务之间没有关系,即使启动服务的组件被销毁,服务还是会运行。 但是当一个组件使用...
  • 安卓BindService笔记

    2019-07-23 20:22:00
    最近学习到了安卓的service,记录一下自己对BindService的理解,学习教程以及部分代码来自菜鸟教程的android教程:菜鸟教程安卓端BindService链接 2 正文 先贴一下布局代码和MainActivity.java代码,在分别...

空空如也

1 2 3 4 5 ... 20
收藏数 3,936
精华内容 1,574
关键字:

bindservice