提问者:小点点

插入耳机时,请勿通过扬声器播放通知声音


我在我的应用程序中为某些通知添加声音,就像这样:

Notification notification = ...
...
notification.sound = Uri.parse(...);

播放通知声音时,即使将耳机插入手机,也会通过扬声器播放,因此扬声器和耳机都会播放该声音。

如果插上耳机,有没有办法只通过耳机播放声音?


共2个答案

匿名用户

目前还不能通过耳机播放声音

寄存器接收器

ReceiveBroadcast receiver=new ReceiveBroadcast();       
registerReceiver(receiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG));

onReceive()代码

public void onReceive(Context context, Intent intent) {
     if (intent.hasExtra("state")){
         if (headsetConnected && intent.getIntExtra("state", 0) == 0){
             headsetConnected = false;
            
         } else if (!headsetConnected && intent.getIntExtra("state", 0) == 1){
            headsetConnected = true;
         }
     }
 }

匿名用户

您可以使用< code > audio manager . iswiredheadseton()来检查耳机是否已插入。

你需要

例子:

AudioManager am1 = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
am1.isWiredHeadsetOn();