我有一个面向 API 级别 19+ 的应用程序。我需要检查耳机是否已连接(有线或蓝牙)。
我看到 AudioManager.isWiredHeadsetOn()
从 API 级别 16 开始被弃用,文档提供了使用 AudioManager.getDevices()
的方法,它仅从 API 开始引入23 级。
问题:检查耳机是否已连接 API 级别 16 - 22 的正确方法是什么?
注意:我知道我仍然可以使用已弃用的方法,但我不想这样做。如果他们弃用它,他们应该引入一个替代 API(我虽然找不到)。
最佳答案
您需要监听 ACTION_HEADSET_PLUG,它会在耳机事件上触发,并且即使没有任何变化也显然会定期触发。
根据我现有的代码,我在主要服务的 onCreate
中有这个:
// listen for headphone events so we can auto switch the audio output when headphones are plugged in
myHeadphoneMonitor = new HeadphoneMonitor();
android.content.IntentFilter headphone_filter = new
android.content.IntentFilter(Intent.ACTION_HEADSET_PLUG);
registerReceiver(myHeadphoneMonitor, headphone_filter);
我的显示器是这样的:
package com.myname.foo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.os.Message;
public class HeadphoneMonitor extends BroadcastReceiver
{
public boolean headphonesActive=false;
@Override
public void onReceive(final Context context, final Intent intent)
{
if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG))
{
int state = intent.getIntExtra("state", -1);
switch (state) {
case 0:
Log.d("HeadphoneMonitor", "Headset is unplugged");
headphonesActive=false;
break;
case 1:
Log.d("HeadphoneMonitor", "Headset is plugged in");
headphonesActive=true;
break;
default:
Log.d("HeadphoneMonitor", "I have no idea what the headset state is");
break;
}
// push this event onto the queue to be processed by the Handler
Message msg = MyApp.uiHandler.obtainMessage(MyApp.HEADPHONE_EVENT);
MyApp.uiHandler.sendMessage(msg);
}
}
}
list 中不需要任何内容来监听此广播事件。
关于java - 检查耳机是否在不同的 API 级别上连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52127683/