大佬教程收集整理的这篇文章主要介绍了android – 如何使用服务连接的BLE连接在不停止服务或断开连接的情况下跨活动使用?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
> Activity1具有用于连接和断开BLE连接的按钮
> Activity2需要从BLE设备获取数据.
>服务所有连接逻辑(如getRemoteDevice(),connectGatt等)属于服务.
Activity1通过绑定服务连接到BLE设备.
Intent gattserviceIntent = new Intent(mContext,Bleservice.class);//In Activity1 context bindservice(gattserviceIntent,mserviceConnection,BIND_AUTO_create);
按下按钮后立即连接到ble设备.
现在,当我从Activity1移动到Activity2时,我在Activity1中取消绑定服务.
@H_486_13@mContext.unbindservice(mserviceConnection);//In Activity1 context
现在如何在Activity2中使用现有的BLE设备连接?
我临时解决方案:
我正在通过从Activity2上下文绑定到它的新服务实例移动到Activity2时再次连接BLE设备. (我不想要.)
在Activity2中,我正在检查我的服务是否已经在运行,如果没有运行,那么我再次从Activity2 Context绑定服务.
if(!isMyserviceRunning(BleWrapper.class)){ Intent wrapperserviceIntent = new Intent(mContext,BleWrapper.class); bindservice(wrapperserviceIntent,mBLEWrapperserviceConnection,BIND_AUTO_create); }else{ Log.w(LOGTAG,"service already connected. In onCreate"); }
在serviceConnection回调下触发onserviceConnected()中的连接
@Override public void onserviceConnected(ComponentName componentName,IBinder servicE) { mBluetoothLeservice = ((BleWrapper.LocalBinder) servicE).getservice(); if (!mBluetoothLeservice.initialize()) { showAlertDialog(getString(R.String.ble_not_supported_on_this_devicE)); }else { mBluetoothLeservice = BleWrapper.geTinstance(); } mBluetoothLeservice.connect(/*address from shared preference*/); //ReconnecTing to the same device using address stored in Shared pref }
用于检查我的服务是否正在运行
private Boolean isMyserviceRunning(Class<?> serviceClass) { Activitymanager manager = (Activitymanager) getSystemservice(Context.ACTIVITY_serviCE); for (RunningserviceInfo service : manager.getRunningservices(Integer.max_value)) { if (serviceClass.getName().equals(service.service.getClassName())) { return true; } } return false; }
但是函数isMyserviceRunning()总是返回false.意味着从Activity1移动到Activity2时服务会断开连接
任何解决方案都可以在活动中保持连接设备的连接?
以上是大佬教程为你收集整理的android – 如何使用服务连接的BLE连接在不停止服务或断开连接的情况下跨活动使用?全部内容,希望文章能够帮你解决android – 如何使用服务连接的BLE连接在不停止服务或断开连接的情况下跨活动使用?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。