Bug

多组件绑定同一个service,出现问题:只有第一个服务绑定的时候会调用onBind()方法

原因

要指定多组件绑定service,输入的时候bindservice会认为intent是一样的,就会默认使用第一次调用的onbind传回的IBinder,这样的话,会发现服务绑定的内存地址也是同一个。其实就是它一直用的第一个服务绑定的地址。

 //main button点击事件 
 public void bindClick(View view){
   
        Log.v("chendandan","bindClick()");
        if(myConn==null){
   
            myConn=new MyConn();
        }
        Intent intent=new Intent(MainActivity.this,MyService.class);
        bindService(intent,myConn,BIND_AUTO_CREATE);
    }

解决办法

给intent指定一个type,区分多次intent的类型即可:

 //main button点击事件 :绑定服务1
 public void bindClick(View view){
   
        Log.v("chendandan","bindClick()");
        if(myConn==null){
   
            myConn=new MyConn();
        }
        Intent intent=new Intent(MainActivity.this,MyService.class);
         //指定type
        intent.setType("main");
        bindService(intent,myConn,BIND_AUTO_CREATE);
    }
//child buttion点击事件:绑定服务2
public void bindClick(View view){
   
        Log.v("chendandan","bindClick()");
        if(myConn==null){
   
            myConn=new MyConn();
        }
        Intent intent=new Intent(MainActivity2.this,MyService.class);
        //指定type
        intent.setType("child");
        bindService(intent,myConn,BIND_AUTO_CREATE);
    }

运行结果:

如果文章对你有帮助,不要忘了给我点个赞吼( ̄▽ ̄)~
欢迎关注我的微信公众号:松鼠技术站