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

相关文章

SpringBoot多环境配置数据读取方式

《SpringBoot多环境配置数据读取方式》SpringBoot通过环境隔离机制,支持properties/yaml/yml多格式配置,结合@Value、Environment和@Configura... 目录一、多环境配置的核心思路二、3种配置文件格式详解2.1 properties格式(传统格式)1.

使用Python构建智能BAT文件生成器的完美解决方案

《使用Python构建智能BAT文件生成器的完美解决方案》这篇文章主要为大家详细介绍了如何使用wxPython构建一个智能的BAT文件生成器,它不仅能够为Python脚本生成启动脚本,还提供了完整的文... 目录引言运行效果图项目背景与需求分析核心需求技术选型核心功能实现1. 数据库设计2. 界面布局设计3

使用IDEA部署Docker应用指南分享

《使用IDEA部署Docker应用指南分享》本文介绍了使用IDEA部署Docker应用的四步流程:创建Dockerfile、配置IDEADocker连接、设置运行调试环境、构建运行镜像,并强调需准备本... 目录一、创建 dockerfile 配置文件二、配置 IDEA 的 Docker 连接三、配置 Do

解决pandas无法读取csv文件数据的问题

《解决pandas无法读取csv文件数据的问题》本文讲述作者用Pandas读取CSV文件时因参数设置不当导致数据错位,通过调整delimiter和on_bad_lines参数最终解决问题,并强调正确参... 目录一、前言二、问题复现1. 问题2. 通过 on_bad_lines=‘warn’ 跳过异常数据3

Android Paging 分页加载库使用实践

《AndroidPaging分页加载库使用实践》AndroidPaging库是Jetpack组件的一部分,它提供了一套完整的解决方案来处理大型数据集的分页加载,本文将深入探讨Paging库... 目录前言一、Paging 库概述二、Paging 3 核心组件1. PagingSource2. Pager3.

Java.lang.InterruptedException被中止异常的原因及解决方案

《Java.lang.InterruptedException被中止异常的原因及解决方案》Java.lang.InterruptedException是线程被中断时抛出的异常,用于协作停止执行,常见于... 目录报错问题报错原因解决方法Java.lang.InterruptedException 是 Jav

java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)

《java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)》:本文主要介绍java中pdf模版填充表单踩坑的相关资料,OpenPDF、iText、PDFBox是三... 目录准备Pdf模版方法1:itextpdf7填充表单(1)加入依赖(2)代码(3)遇到的问题方法2:pd

解决RocketMQ的幂等性问题

《解决RocketMQ的幂等性问题》重复消费因调用链路长、消息发送超时或消费者故障导致,通过生产者消息查询、Redis缓存及消费者唯一主键可以确保幂等性,避免重复处理,本文主要介绍了解决RocketM... 目录造成重复消费的原因解决方法生产者端消费者端代码实现造成重复消费的原因当系统的调用链路比较长的时

python使用try函数详解

《python使用try函数详解》Pythontry语句用于异常处理,支持捕获特定/多种异常、else/final子句确保资源释放,结合with语句自动清理,可自定义异常及嵌套结构,灵活应对错误场景... 目录try 函数的基本语法捕获特定异常捕获多个异常使用 else 子句使用 finally 子句捕获所

深度解析Nginx日志分析与499状态码问题解决

《深度解析Nginx日志分析与499状态码问题解决》在Web服务器运维和性能优化过程中,Nginx日志是排查问题的重要依据,本文将围绕Nginx日志分析、499状态码的成因、排查方法及解决方案展开讨论... 目录前言1. Nginx日志基础1.1 Nginx日志存放位置1.2 Nginx日志格式2. 499