bindService初步了解

时间:2023-01-05 19:23:44

bindService的使用:

    当需要调Service里面的方法时,可以用bindService()

首先定义一个类继承于Service,然后配置Manifest.xml文件

 public class MyBindService extends Service {
     @Nullable
     @Override
     public IBinder onBind(Intent intent) {
         return new MyBinder();
     }
     public void myfunction(){
         System.out.println("我是服务里的方法");
     }
     @Override
     public void onCreate() {
         super.onCreate();
     }
     public class MyBinder extends Binder{
         public void call(){
             myfunction();
         }
     }
 }

通过onBind()方法返回一个对象,给onServiceConnected(ComponentName name, IBinder service)

方法里面的Service,然后通过强转得到一个MyBinder对象

myBinder = (MyBindService.MyBinder)service;
用myBinder对象调用call方法,从而调到服务里面的myfunction()方法

 public class MainActivity extends AppCompatActivity {

     private Myconn conn;
     private MyBindService.MyBinder myBinder;

     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
     }

     public void click(View v){
         conn = new Myconn();
         bindService(new Intent(this,MyBindService.class),conn,BIND_AUTO_CREATE);
     }

     public void click1(View v){
         myBinder.call();
     }
     public void click2(View v){
         unbindService(conn);
     }

     private class Myconn implements ServiceConnection {
         @Override
         public void onServiceConnected(ComponentName name, IBinder service) {
             myBinder = (MyBindService.MyBinder)service;
         }
         @Override
         public void onServiceDisconnected(ComponentName name) {
         }
     }
 }
onServiceConnected()当绑定成功后调用该方法。
onServiceDisconnected()取消绑定后调用该方法。
 

unBinder()方法不能多次取消绑定。