AIDL使用继承关系自定义类及调用数据异常问题记录

本文主要是介绍AIDL使用继承关系自定义类及调用数据异常问题记录,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

AIDL使用与注意事项

  • 基本使用
    • 1.aidl的定义,我这里定义了aidl 使用的三种场景
    • 2.service 的构建
    • 3.构建实体类
      • 实体类基类
      • 实体类子类
      • 继承关系引发的参数失效或为null 问题
    • 4.那么如何正确的使用继承呢
    • 5.服务的绑定与数据通信
    • 6. 新建接口IDeviceListener.Stub 服务端收到为null 问题
    • 7.服务的注册
    • 项目目录图
    • 自定义类服务端和客户端不统一问题

基本使用

1.aidl的定义,我这里定义了aidl 使用的三种场景

新建aidl

package com.example.aidltestmoclinet;import com.example.aidltestmoclinet.PersonR;
import java.lang.String;
interface IMyAidlInterface {/*** Demonstrates some basic types that you can use as parameters* and return values in AIDL.*/void basicTypes(int anInt, long aLong,  String aString);void testAi(in PersonR persernR,int anInt,String aString);void setDeviceListener(in IDeviceListener iDeviceListener);
}

分别是:
1.普通数据类型(aidl 支持基本数据类型)
2.自定义数据类型 (这里注意了,aidl 不支持继承关系的数据类型)
3.自定义数据类型的接口
补充下:自定义类型前的关键字,in 表示只能输入,即客户端到服务端,out 输出,outin既能输入也能输出

2.service 的构建

public class ClientService extends Service {private static final String TAG = "ClientService";@Overridepublic void onCreate() {super.onCreate ();Log.d (TAG, "onCreate: ");}@Nullable@Overridepublic IBinder onBind(Intent intent) {return new StubBinder() ;}public class StubBinder extends IMyAidlInterface.Stub{private IDeviceListener deviceListener;@Overridepublic void basicTypes(int anInt, long aLong, String aString) throws RemoteException {Log.d (TAG, "basicTypes: ");}@Overridepublic void testAi(PersonR persernR,int anInt, String aString) throws RemoteException {Log.d (TAG, "testAi: " +anInt +"--aString" + aString +"--persernR"+ persernR.toString ());}@Overridepublic void setDeviceListener(IDeviceListener iDeviceListener) throws RemoteException {this.deviceListener=iDeviceListener;Log.d (TAG, "setDeviceListener: " +iDeviceListener);if (iDeviceListener!=null) {PerB perB=new PerB (1,"xiaoming",2);PersonR persernR=new PersonR (1,"xiaoming");PersonR dge=createBaseDeviceInfo (perB) ;iDeviceListener.onDeviceConnect (dge,0,"kjggjjjj");}}public PersonR createBaseDeviceInfo(PersonR persernR) {PersonR bean = null;if (persernR == null) {return bean;}if (persernR instanceof PerB) {bean = new PersonR ();bean.setAge (persernR.getAge ());bean.setName (persernR.getName ());} else {bean = persernR;}return bean;}}
}

通过onBind 返回一个Binder 类型的类,就是我们构建的aidl 接口 ,这里看到返回值是IBinder,iBinder 是aidl 的标准接口,通过我们自定的aidl 类.Stub获取到Binder ,Binder 本身实现了IBinder。
IDeviceListener 的实现

package com.example.aidltestmoclinet;import com.example.aidltestmoclinet.PersonR;
import java.lang.String;
// Declare any non-default types here with import statements
/*** 设备状态监听* 所有蓝牙外设通用接口*/
interface IDeviceListener{/*** failedReason* FAILED_BT_DISABLE = 0* FAILED_NO_START_BONDING = 1*/void onDiscovery(in List<PersonR> devieInfos,in int failedReason);void onDeviceConnect(in PersonR device,in int failedReason,in String message);
}

这里一定要注意 import 包的导入,不然找不到类,自定义类型还需要构建一个相同名字的点aidl类。PersonR.aidl类
在这里插入图片描述

package com.example.aidltestmoclinet;// Declare any non-default types here with import statementsparcelable PersonR;//

所有的自定义类型必须实现parcelable 接口,注意上边的包名地址要和实体类一样。

3.构建实体类

实体类基类

class PersonR implements Parcelable {int age;String name;public PersonR(int age, String name) {this.age = age;this.name = name;}public PersonR() {}protected PersonR(Parcel in) {age = in.readInt ();name = in.readString ();}public static final Creator<PersonR> CREATOR = new Creator<PersonR> () {@Overridepublic PersonR createFromParcel(Parcel in) {return new PersonR (in);}@Overridepublic PersonR[] newArray(int size) {return new PersonR[size];}};public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}@Overridepublic int describeContents() {return 0;}@Overridepublic void writeToParcel(Parcel dest, int flags) {dest.writeInt (age);dest.writeString (name);}@Overridepublic String toString() {return "PersonR{" +"age=" + age +", name='" + name + '\'' +'}';}
}

实体类子类

public class PerB extends PersonR implements Parcelable {public PerB(int age, String name, int sxy) {super (age, name);this.sxy = sxy;}protected PerB(Parcel in) {super (in);sxy = in.readInt ();}public static final Creator<PerB> CREATOR = new Creator<PerB> () {@Overridepublic PerB createFromParcel(Parcel in) {return new PerB (in);}@Overridepublic PerB[] newArray(int size) {return new PerB[size];}};public int getSxy() {return sxy;}public void setSxy(int sxy) {this.sxy = sxy;}int sxy;@Overridepublic int describeContents() {return 0;}@Overridepublic void writeToParcel(Parcel dest, int flags) {super.writeToParcel (dest,flags);dest.writeInt (sxy);}
}

这里无论子类还是父类,都必须实现Parcelable 接口,如果不实现,aidl 就无法序列化实体类,导致无法将序列化后的自定义类保存到内存中,那么在你的客户端,将无法反序列化生成对应的自定义对像,所以这个是必须的。但是在实际中,aidl 是不支持继承的,所以,在最后,我们必须将子类转为父类,这里注意,不是转型,是重新生成一个父类然后给他赋值,这点很关键,如果你的接口方法参数只有一个,那么你可以直接将子类传入.

继承关系引发的参数失效或为null 问题

如果你的接口方法是这样的。
同时使用时又是这样的:

 PerB perB=new PerB (1,"xiaoming",2);PersonR dge=perB ;iDeviceListener.onDeviceConnect (dge,0,"kjggjjjj");

那么恭喜你中彩,这将引发persernR 后边的两个参数无法得到有效的值,int 类型会返回 -1,string 会返回 null ,但是persernR 是正常的,无论是一个参数还是多个参数,自定类都可以获取到值,但是有多个参数这将导致其他参数无法正常获取到值,例如这样的
void testAi(in PersonR persernR,int anInt,String aString);
所以我们必须这样操作,才能有效避免

  public PersonR createBaseDeviceInfo(PersonR persernR) {PersonR bean = null;if (persernR == null) {return bean;}if (persernR instanceof PerB) {bean = new PersonR ();bean.setAge (persernR.getAge ());bean.setName (persernR.getName ());} else {bean = persernR;}return bean;}

4.那么如何正确的使用继承呢

首先我们需要一个包装类,且实现Parcelable 接口,然后将父类作为变量

public class PerProxy implements Parcelable {PersonR personR;public PersonR getPerB() {return personR;}public void setPerB(PersonR personR) {this.personR = personR;}public static Creator<PerProxy> getCREATOR() {return CREATOR;}protected PerProxy(Parcel in) {personR = in.readParcelable (PersonR.class.getClassLoader ());}public static final Creator<PerProxy> CREATOR = new Creator<PerProxy> () {@Overridepublic PerProxy createFromParcel(Parcel in) {return new PerProxy (in);}@Overridepublic PerProxy[] newArray(int size) {return new PerProxy[size];}};@Overridepublic int describeContents() {return 0;}@Overridepublic void writeToParcel(Parcel dest, int flags) {dest.writeParcelable (personR, flags);}
}

通过PerProxy 获取到 PersonR 对象,然后再通过

 @Overridepublic void onPerProxy(PerProxy perProxy) throws RemoteException {if (perProxy!=null) {PersonR personR=  perProxy.getPerB ();if (personR instanceof  PerB) {Log.d (TAG, "子类:onPerProxy perB:"+ personR.toString ());}else if (personR instanceof PersonR) {Log.d (TAG, "父类 onPerProxy PersonR:"+ personR.toString ());}}}

这样客户端就可以获取到相应类型的类了

5.服务的绑定与数据通信

 Intent intent = new Intent (MainActivity.this, ClientService.class);bindService (intent, new ServiceConnection () {@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {iMyAidlInterface = IMyAidlInterface.Stub.asInterface (service);Log.d (TAG, "onServiceConnected: " + iMyAidlInterface);if (iMyAidlInterface != null) {try {Log.d (TAG, "发送消息");iMyAidlInterface.testAi ( new PersonR (23, "ikfkkkkkk"),1, "jgjr");} catch (RemoteException e) {e.printStackTrace ();}try {iMyAidlInterface.setDeviceListener (iDeviceListener);} catch (RemoteException e) {e.printStackTrace ();}}}@Overridepublic void onServiceDisconnected(ComponentName name) {Log.d (TAG, "onServiceDisconnected: ");}}, Context.BIND_AUTO_CREATE);

接口类:

IDeviceListener iDeviceListener=new IDeviceListener.Stub () {@Overridepublic void onDiscovery(List<PersonR> devieInfos, int failedReason) throws RemoteException {}@Overridepublic void onDeviceConnect(PersonR device, int failedReason, String message) throws RemoteException {Log.d (TAG, "onDeviceConnect: " +failedReason + "---:"+message +"---"+ device.toString ());}
};

完整的调用类 MainActivity

public class MainActivity extends AppCompatActivity {private static final String TAG = "ClientServiceMain";IMyAidlInterface iMyAidlInterface;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate (savedInstanceState);Log.d (TAG, "onCreate: ");setContentView (R.layout.activity_main);TextView textView=(TextView)findViewById (R.id.test);textView.setOnClickListener (new View.OnClickListener () {@Overridepublic void onClick(View v) {Log.d (TAG, "onClick: ");Intent intent = new Intent (MainActivity.this, ClientService.class);bindService (intent, new ServiceConnection () {@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {iMyAidlInterface = IMyAidlInterface.Stub.asInterface (service);Log.d (TAG, "onServiceConnected: " + iMyAidlInterface);if (iMyAidlInterface != null) {try {Log.d (TAG, "发送消息");iMyAidlInterface.testAi ( new PersonR (23, "ikfkkkkkk"),1, "jgjr");} catch (RemoteException e) {e.printStackTrace ();}try {iMyAidlInterface.setDeviceListener (iDeviceListener);} catch (RemoteException e) {e.printStackTrace ();}}}@Overridepublic void onServiceDisconnected(ComponentName name) {Log.d (TAG, "onServiceDisconnected: ");}}, Context.BIND_AUTO_CREATE);}});}
IDeviceListener iDeviceListener=new IDeviceListener.Stub () {@Overridepublic void onDiscovery(List<PersonR> devieInfos, int failedReason) throws RemoteException {}@Overridepublic void onDeviceConnect(PersonR device, int failedReason, String message) throws RemoteException {Log.d (TAG, "onDeviceConnect: " +failedReason + "---:"+message +"---"+ device.toString ());}
};
}

6. 新建接口IDeviceListener.Stub 服务端收到为null 问题

当通过 iMyAidlInterface.setDeviceListener (iDeviceListener); 设置一个接口,那个理论上我们在服务端

public void setDeviceListener(IDeviceListener iDeviceListener) throws RemoteException {}

函数将会收到一个该接口的实例,但是,我们在new IDeviceListener.Stub 时,该接口将默认重写了asBinder函数

IDeviceListener iDeviceListener=new IDeviceListener.Stub () {@Overridepublic void onDiscovery(List<PersonR> devieInfos, int failedReason) throws RemoteException {}@Overridepublic void onDeviceConnect(PersonR device, int failedReason, String message) throws RemoteException {Log.d (TAG, "onDeviceConnect: " +failedReason + "---:"+message +"---"+ device.toString ());}@Overridepublic IBinder asBinder() {return super.asBinder ();}
};

如果返回值为null ,那么我们服务端收到的将是一个null
那么如果避免这个问题呢?
1.直接删除
2.修改重写类为

 @Overridepublic IBinder asBinder() {return super.asBinder ();}

这样就可以,但是针对个业务场景我们没有必要重写,所以,建议删除掉。

7.服务的注册

 <service android:name=".ClientService"android:enabled="true"android:exported="true"android:process=":newService"/>

这里是将服务单独运行在了一个叫newService 的进程中,这个可以根据业务来定是否需要。

项目目录图

在这里插入图片描述

自定义类服务端和客户端不统一问题

正常情况下,我们的服务都是一对一,也就是一个客户端一个服务端,这样基本保证了,自定义对象的一致性(因为简单),但是面对多对一的局面就不是那么的好处理了,可能出现某些客户端使用的 aidl 接口与服务端使用的对不上,这样机会导致一个奇怪的问题,拿到的对象数错乱。

写在最后:这些基本覆盖了aidl 的所有业务场景,如果你是新手,出现找不到接口类的问题,那么建议你先构建下,因为编译器需要将aidl 接口生成对应的java 类,供程序调用,如果出现找不到自定义类,那么你一定是包的路径和实体类的路基不一样,或者实体类没有对应的 aidl 类,并且注意包的引用路径。

这篇关于AIDL使用继承关系自定义类及调用数据异常问题记录的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1123084

相关文章

Java中流式并行操作parallelStream的原理和使用方法

《Java中流式并行操作parallelStream的原理和使用方法》本文详细介绍了Java中的并行流(parallelStream)的原理、正确使用方法以及在实际业务中的应用案例,并指出在使用并行流... 目录Java中流式并行操作parallelStream0. 问题的产生1. 什么是parallelS

Linux join命令的使用及说明

《Linuxjoin命令的使用及说明》`join`命令用于在Linux中按字段将两个文件进行连接,类似于SQL的JOIN,它需要两个文件按用于匹配的字段排序,并且第一个文件的换行符必须是LF,`jo... 目录一. 基本语法二. 数据准备三. 指定文件的连接key四.-a输出指定文件的所有行五.-o指定输出

Linux jq命令的使用解读

《Linuxjq命令的使用解读》jq是一个强大的命令行工具,用于处理JSON数据,它可以用来查看、过滤、修改、格式化JSON数据,通过使用各种选项和过滤器,可以实现复杂的JSON处理任务... 目录一. 简介二. 选项2.1.2.2-c2.3-r2.4-R三. 字段提取3.1 普通字段3.2 数组字段四.

Linux kill正在执行的后台任务 kill进程组使用详解

《Linuxkill正在执行的后台任务kill进程组使用详解》文章介绍了两个脚本的功能和区别,以及执行这些脚本时遇到的进程管理问题,通过查看进程树、使用`kill`命令和`lsof`命令,分析了子... 目录零. 用到的命令一. 待执行的脚本二. 执行含子进程的脚本,并kill2.1 进程查看2.2 遇到的

详解SpringBoot+Ehcache使用示例

《详解SpringBoot+Ehcache使用示例》本文介绍了SpringBoot中配置Ehcache、自定义get/set方式,并实际使用缓存的过程,文中通过示例代码介绍的非常详细,对大家的学习或者... 目录摘要概念内存与磁盘持久化存储:配置灵活性:编码示例引入依赖:配置ehcache.XML文件:配置

Java 虚拟线程的创建与使用深度解析

《Java虚拟线程的创建与使用深度解析》虚拟线程是Java19中以预览特性形式引入,Java21起正式发布的轻量级线程,本文给大家介绍Java虚拟线程的创建与使用,感兴趣的朋友一起看看吧... 目录一、虚拟线程简介1.1 什么是虚拟线程?1.2 为什么需要虚拟线程?二、虚拟线程与平台线程对比代码对比示例:三

k8s按需创建PV和使用PVC详解

《k8s按需创建PV和使用PVC详解》Kubernetes中,PV和PVC用于管理持久存储,StorageClass实现动态PV分配,PVC声明存储需求并绑定PV,通过kubectl验证状态,注意回收... 目录1.按需创建 PV(使用 StorageClass)创建 StorageClass2.创建 PV

IDEA和GIT关于文件中LF和CRLF问题及解决

《IDEA和GIT关于文件中LF和CRLF问题及解决》文章总结:因IDEA默认使用CRLF换行符导致Shell脚本在Linux运行报错,需在编辑器和Git中统一为LF,通过调整Git的core.aut... 目录问题描述问题思考解决过程总结问题描述项目软件安装shell脚本上git仓库管理,但拉取后,上l

Redis 基本数据类型和使用详解

《Redis基本数据类型和使用详解》String是Redis最基本的数据类型,一个键对应一个值,它的功能十分强大,可以存储字符串、整数、浮点数等多种数据格式,本文给大家介绍Redis基本数据类型和... 目录一、Redis 入门介绍二、Redis 的五大基本数据类型2.1 String 类型2.2 Hash

Redis中Hash从使用过程到原理说明

《Redis中Hash从使用过程到原理说明》RedisHash结构用于存储字段-值对,适合对象数据,支持HSET、HGET等命令,采用ziplist或hashtable编码,通过渐进式rehash优化... 目录一、开篇:Hash就像超市的货架二、Hash的基本使用1. 常用命令示例2. Java操作示例三