Android中 服务里的方法抽取成接口

1 写个类继承Service 重写 onBind方法 返回一个IBinder 对象(传递到连接成功时用)

2 服务中 写一个内部类 继承IBinder 并且实现一个接口(用于抽取方法)继承IBinder 是可以在1步骤中返回这个内部类的对象,内部类的对象可以调用服务中的其它方法。在实现接口的方法中 调用服务的方法。

3 写一个类 实现ServiceConnection服务连接,重写 连接成功 和连接失败的方法 ,连接成功时会传入一个IBinder 对象,就是上面那个内部类对象,这样就通过这个对象调用服务中的方法了。实现接口只是为了 限制访问服务中的相关方法的调用。把传入的对象 强制转换成接口对象


定义一个接口,里面定义方法,此方法实现的时候 调用服务中指定的方法
    public interface GetService{
        void getService();
    }

在继承服务中的类中 定义一个内部类 继承Binder 并且实现接口.内部类可以调用服务中的方法,所以用内部类实现接口中的方法,用此方法调用服务中的方法即可
public class MyService extends Service{
        public Ibinder onBind(Intent intent){
            //返回一个IBinder对象,给连接成功时用的 用来调用服务中的方法
            return new MidMan();
        }

      //内部类继承Binder 实现接口
        class MidMan extends Binder implements GetService{
            public void getService(){
                doServices();
            }
   }

        //定义并实现我们要用的服务中的方法
        public void doServices(){
            System.out.println("The Service Method!");

        }

        //服务中的其它方法,不给用
        public void doOtherServices(){
            System.out.println("inner use!");
        }

}


在Activity中
        private Intent int;
        private MyServiceConn conn
        GetService gs;
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            int = new Intent(this,MyService.class);
            conn = new MyServiceConn();

            //绑定服务
            bindService(int,conn,BIND_AUTO_CREATE);
        }

  //连接服务成功,调用此方法
     class MyServiceConn implements ServiceConnection{

                public void onServiceConnected(Component name,IBinder service){
                 //service 就是 上面onBind()返回的对象,强转是为了只让用接口里的方法
                  gs = (GetService) service;

              }

           public void onServiceDisconnected(Component name){

             }

     }
      //使用服务中指定的方法
        public void click(View view){
            gs.GetServices();//GetServices()调用我们想要的 doServices();

        }

    



原文地址:https://www.cnblogs.com/exayong/p/5929818.html