Android--Service②-->接口重构来服务调用服务内部的方法

本文介绍如何通过接口重构提高Android Service的封装性,详细讲解了创建接口、服务中实现IBinder子类以及在活动中接收服务返回的IBinder对象的步骤,强调了隐藏内部实现、只暴露接口的优势。
摘要由CSDN通过智能技术生成


前言

上篇博客中我们解决了怎么启动,关闭服务,怎么调用服务内部的方法,这篇博客我们就来讨论一下怎么用接口来让服务内部的实现更加的隐蔽,值暴露接口


提示:以下是本篇文章正文内容,下面案例可供参考

一、使用步骤

1.创建接口

public interface ICommunication {
   
    void callServiceMethod();
}

2.在服务中定义一个实现了接口的IBinder的子类,并在onBind中返回

    private class InnerBinder extends Binder implements ICommunication {
   
        @Override
        public void callServiceMethod() {
   
            sayHello();
        }
    }
    /*
    调用bindService时使用
     */
    @Override
    public IBinder onBind(Intent intent) {
   
        return new InnerBinder();
    }

    @Override
    public void onCreate() {
   
        super.onCreate();
        Log.i(TAG, "onCreate");
    }

3.在活动中定义一个接口去接受服务返回的IBinder对象

private ICommunication binder;
    private final ServiceConnection serviceConnection = new ServiceConnection() {
   

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
   
            binder= (ICommunication) service;
            Log.i("TAG", "onServiceConnected");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
   
            Log.i("TAG", "onServiceDisconnected");
            binder = null;
        }
    };

二、使用接口的优势

1.隐藏内部实现的细节,暴露接口

三、完整代码

xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值