我正在开发一个具有以下必要条件的应用程序:如果设备中插入了耳机并且用户将其删除,我需要将所有流静音.要做到这一点,我需要听广播AudioManager.ACTION_AUDIO_BECOMING_NOISY.还行吧!这里没问题.
但是当用户再次插入耳机时,我需要取消静音设备.但是没有AudioManager.ACTION_AUDIO_BECOMING_NOISY相反的广播.我不知道耳机何时再次插上.
一个解决办法是定期检查是否AudioManager.isWiredHeadsetOn()是true但这似乎并没有得到很好的解决了我.
有没有办法检测用户何时在设备上插入耳机?
编辑:我试图用Intent.ACTION_HEADSET_PLUG这种方式,但它没有用.
在manifest.xml中我放了:
<receiver android:name=".MusicIntentReceiver" >
<intent-filter>
<action android:name="android.intent.action.HEADSET_PLUG" />
</intent-filter>
</receiver>
Run Code Online (Sandbox Code Playgroud)
以下是我的代码MusicIntentReceiver.java:
public class MusicIntentReceiver extends BroadcastReceiver {
public void onReceive(Context ctx, Intent intent) {
AudioManager audioManager = (AudioManager)ctx.getSystemService(Context.AUDIO_SERVICE);
if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
Log.d("Let's turn the sound on!");
//other things to un-mute the streams
}
}
}
Run Code Online (Sandbox Code Playgroud)
尝试其他任何解决方案?
如何检查耳机当前是否已插入.我不希望广播接收器在连接到设备时通知我.我需要这样的东西:
if(/*headphone is connected*/)
...
Run Code Online (Sandbox Code Playgroud) 如果我的应用程序正在运行,我知道如何检测耳机插件事件.您必须为ACTION_HEADSET_PLUG注册广播接收器.但是你无法使用Manifest声明为广播接收器捕获此动作.因此,捕获耳机插件事件的唯一选择是后台服务.但它耗尽电池等等.
我检查了一些音乐播放器并发现他们没有任何额外服务就捕获了该事件.他们是怎么做到的?有任何想法吗?