文章目录
前言
在上篇博客中我们解决了怎么启动,关闭服务,怎么调用服务内部的方法,这篇博客我们就来讨论一下怎么用接口来让服务内部的实现更加的隐蔽,值暴露接口
提示:以下是本篇文章正文内容,下面案例可供参考
一、使用步骤
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"