快速建站php,全国建筑行业查询平台,网站建设与管理实训心得体会,杭州的网站设计公司项目开发遇到下面这个报错了#xff01; 问题原因 直接说原因#xff0c;就是因为进程间不能直接传递对象#xff0c;应该传递该Binder对象的映射#xff08;代理对象#xff09;#xff0c;所以类型转换就出错了。如果在同一个进程中#xff0c;直接传递对象没有关系 问题原因 直接说原因就是因为进程间不能直接传递对象应该传递该Binder对象的映射代理对象所以类型转换就出错了。如果在同一个进程中直接传递对象没有关系下面的类型强转是没有问题的但是如果是不同进程强转就会失败就会报上面的错误。 那启动应用内启动service怎么就成进程间通信了呢因为service是指定了android:process:remote。就算自己的service没有指定android:process如果应用中其他service写了android:process也会导致自己的service报错。 我的Service是一个websocket通信服务本来我把bindService写在Activity中但是这有一个问题就是页面跳转服务会随着声明周期被销毁重建这样每次跳转页面都重新连接浪费时间于是我就把Service挪到了Application里面。我的页面一个LoginActivity一个MainActivity页面跳转到MainActivity的时候就报错了因为我的MainActivity里面使用了百度地图而百度地图的service如下
!-- 百度地图定位的service组件--service android:namecom.baidu.location.fandroid:enabledtrueandroid:process:remote/
这样就导致我的Service的binder转换报错了。把百度地图Service里面的android:process:remote去掉就就可以了。
解决办法
一.去掉android:process:remote
二.aidl方式 下面记录一下进程间Service要想解决这个问题就是需要用aidl方式。
1.创建aidl文件 Android Studio可以直接创建在与java文件平级的文件下会创建一个aidl文件夹里面包名是app的包名创建一个后缀为.aidl的文件夹 创建之后是这样的 aidl文件如下
// IMyAidlInterface.aidl
package com.deviser.androidremote;// Declare any non-default types here with import statementsinterface IMyAidlInterface {//这用来传递Service的包名和文件名传递之后通过反射获取Service对象String getName();
}
编译之后build下面会生成 2.重写Service的Binder方法
// //用于Activity和service通讯//这是原来的方法直接把WebClientService这个对象返回了
// public class WebClientBinder extends Binder {
// public WebClientService getService() {
// return WebClientService.this;
// }
// }//通过aidl方式继承IMyAidlInterface.Stub返回的是WebClientService的包名和文件名//进程间传递的是字符串public class WebClientBinder extends IMyAidlInterface.Stub{Overridepublic String getName() throws RemoteException {return WebClientService.class.getName();}}
3.修改onServiceConnected private var webServiceConnection: ServiceConnection object : ServiceConnection {override fun onServiceConnected(componentName: ComponentName?, iBinder: IBinder?) {//原来就是这里iBinder强转成WebClientService.WebClientBinder报错
// var binder: WebClientService.WebClientBinder iBinder as WebClientService.WebClientBinder
// webClientService binder.service// 获得代理对象var proxy IMyAidlInterface.Stub.asInterface(iBinder)try {//通过反射机制把字符串转换成对象WebClientService对象var clazz Class.forName(proxy.name)webClientService clazz.newInstance() as WebClientService?}catch (e: Exception){e.printStackTrace()}}override fun onServiceDisconnected(componentName: ComponentName?) {Log.e(MyConstant.TAG,服务与活动成功断开);}}
到这里问题就解决啦