Android監聽耳機插拔狀態實現看視訊插拔耳機暫停播放
最近接到一個需求,需求的內容是:看視訊時拔出耳機,視訊暫停播放;插入耳機,視訊繼續播放。
首先我們分析下這個需求,最重要是監聽耳機的插拔狀態。然後耳機又分為兩種:有線耳機和藍芽耳機,也就是我們要通過廣播的方式監聽這兩種插拔狀態,同時還要考慮著兩種耳機同時連線時哪個優先收到音訊聲音呢?大家可以先想想。
動態註冊廣播監聽
private var isRegisteredHeadsetReceiver = false override fun onResume() { super.onResume() //註冊廣播 if (!isRegisteredHeadsetReceiver) { try { val filter = IntentFilter() //監聽有線耳機的兩種方式 filter.addAction(Intent.ACTION_HEADSET_PLUG) filter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY) //監聽藍芽耳機 filter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED) registerReceiver(mReceiver, filter) isRegisteredHeadsetReceiver = true } catch (e: Exception) { } } } override fun onPause() { //登出廣播 if (isRegisteredHeadsetReceiver) { try { unregisterReceiver(mReceiver) isRegisteredHeadsetReceiver = false } catch (e: Exception) { } } super.onPause() }
監聽有線耳機的連線狀態
方式一:監聽系統廣播Intent.ACTION_HEADSET_PLUG
通過這種方式,可以監聽到耳機連線和斷開的狀態。
private var isHeadsetOn = false private var mReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { val action = intent?.action if (TextUtils.equals(action, Intent.ACTION_HEADSET_PLUG)) { if (intent?.hasExtra("state") == true) { if (intent.getIntExtra("state", 2) == 0) { if (isHeadsetOn) { Toast.makeText(mContext, "有線耳機拔出", Toast.LENGTH_SHORT).show() isHeadsetOn = false ... } } else if (intent.getIntExtra("state", 2) == 1) { if (!isHeadsetOn) { Toast.makeText(mContext, "有線耳機插入", Toast.LENGTH_SHORT).show() isHeadsetOn = true ... } } } } } } @Suppress("DEPRECATION") private fun isWiredHeadsetOn(): Boolean { val am = getSystemService(Context.AUDIO_SERVICE) as AudioManager return am.isWiredHeadsetOn } override fun onCreate(savedInstanceState: Bundle?) { ... isHeadsetOn = isWiredHeadsetOn() ... }
方式二:監聽系統廣播AudioManager.ACTION_AUDIO_BECOMING_NOISY
通過這種方式只能監聽到有線和藍芽耳機的斷開的狀態,不能監聽其連線的狀態。很顯然滿足不了我的需求。
private var mReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { val action = intent?.action if (TextUtils.equals(AudioManager.ACTION_AUDIO_BECOMING_NOISY)) { Toast.makeText(mContext, "有線耳機拔出", Toast.LENGTH_SHORT).show() ... } } }
監聽藍芽耳機的連線狀態
監聽系統廣播BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED,用於廣播Headset配置檔案的連線狀態的更改。
//首先需要藍芽的許可權,否則無法接收到。 <uses-permission android:name="android.permission.BLUETOOTH"/> private var mReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { val action = intent?.action if (TextUtils.equals(action, BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED)) { val state = intent?.getIntExtra(BluetoothProfile.EXTRA_STATE, -1) when (state) { BluetoothProfile.STATE_CONNECTED -> { Toast.makeText(mContext, "藍芽耳機連線", Toast.LENGTH_SHORT).show() ... } BluetoothProfile.STATE_DISCONNECTED -> { Toast.makeText(mContext, "藍芽耳機未連線", Toast.LENGTH_SHORT).show() ... } } } } }
最後,兩種耳機同時連線時哪個優先收到音訊聲音呢?上面的程式碼一測試你就會發現,有線耳機優先於藍芽耳機。