HTML5+判断ios、android耳机状态

HTML5+判断ios、android耳机状态

废话不多说直接上代码

// #ifdef APP-PLUS
	let that = this;
	//true 检测到耳机、false 未检测到耳机
	let headsetStatus = false;
   	if(plus.os.name == 'iOS') {
   		headsetStatus = that.getIosHeadsetStatus();
   	} else {
   		headsetStatus = that.getAndroidHeadsetStatus();
   	}
// #endif
//获取ios耳机状态
getIosHeadsetStatus(){
	let b = false;
	console.log("ios 获取是否插入耳机")
	let AVAudioSession  = plus.ios.importClass("AVAudioSession");
	let sharedInstance = AVAudioSession.sharedInstance();
	let currentRoute = sharedInstance.currentRoute();
	let desc = currentRoute.plusGetAttribute("outputs")
	let firstObject = desc.plusGetAttribute("firstObject")
	let portType = firstObject.plusGetAttribute("portType")
	console.log(portType)
	//插入 Headphones
	//未插入 Speaker
	//蓝牙耳机 BluetoothA2DPOutput
	if(portType === 'Headphones' || portType === 'BluetoothA2DPOutput'){
		b = true;
	}
	return b;
},
// 获取安卓耳机状态
getAndroidHeadsetStatus(){
	console.log("获取是否插入耳机")
	let b = false;
	try{
		let intent = plus.android.newObject("android.content.Intent");
		let context = plus.android.importClass("android.content.Context");
		let main = plus.android.runtimeMainActivity(); 
		let systemService = main.getSystemService(context.AUDIO_SERVICE);
		b = plus.android.invoke(systemService,"isWiredHeadsetOn")
	} catch (e) {
		console.log(e);
	}
	if(!b){
		console.log("未获取到插孔耳机开始获取蓝牙耳机状态")
		try{
	 		let BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
			let BAdapter = BluetoothAdapter.getDefaultAdapter();
			let BluetoothProfile = plus.android.importClass("android.bluetooth.BluetoothProfile");
			let connectionState = BAdapter.getProfileConnectionState(BluetoothProfile.HEADSET);
			if(connectionState === 2){
				b = true;
			}
		} catch (e) {
			console.log(e);
		}
	}
		return b;
},

附:HTML5+ API
http://www.html5plus.org/doc/zh_cn/android.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值