2017-09-05 122 views
0

當耳機插入android時,我只想從耳機發出聲音。 (按報警音量)[Android]耳機插入時只有耳機聲音

 AudioManager audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE); 
     audioManager.setStreamVolume(AudioManager.STREAM_ALARM,alarmVolume,0); 

     mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM); 
     mediaPlayer.prepare(); 
     mediaPlayer.setLooping(false); 

     mediaPlayer.start(); 

回答

0

爲此,您需要監聽有線耳機狀態。

private void registerWiredHeadsetIntentBroadcast() { 
    IntentFilter filter = new IntentFilter("android.intent.action.HEADSET_PLUG"); 
    this.wiredHeadsetReceiver = new BroadcastReceiver() { 
     public void onReceive(Context context, Intent intent) { 
      int state = intent.getIntExtra("state", 0); 
      int microphone = intent.getIntExtra("microphone", 0); 
      boolean hasWiredHeadset = state == 1; 
      isWiredHeadsetPlugged=hasWiredHeadset; 
       switch (state) { 
        case 0: 
         //unplugged 
         audioManager.setWiredHeadsetOn(false); 
         audioManager.setSpeakerphoneOn(true); 
         break; 
        case 1: 
         //plugged 
         audioManager.setWiredHeadsetOn(true); 
         break; 
        default: 
       } 
     } 
    }; 
    this.apprtcContext.registerReceiver(this.wiredHeadsetReceiver, filter); 
} 

將音頻流類型分配給音頻管理器,你很好。

+0

嗨,非常感謝。 不幸的是我嘗試了以下,但它不起作用。幫幫我。 。 -------------------- 'AudioManager audioManager =(AudioManager)context.getSystemService(Context.AUDIO_SERVICE); audioManager.setStreamVolume(AudioManager.STREAM_ALARM,alarmVolume,0); audioManager.setWiredHeadsetOn(true); audioManager.setSpeakerphoneOn(false); mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM); mediaPlayer.prepare(); mediaPlayer.setLooping(false); mediaPlayer.start();' – user3323951