Android打开/关闭免提(SpeakerPhone)

//打开扬声器
     public void OpenSpeaker() {

         try{
         AudioManager audioManager = (AudioManager) mContext.getSystemService  (Context.AUDIO_SERVICE);
         //audioManager.setMode(AudioManager.ROUTE_SPEAKER);
      audioManager.setMode(AudioManager.MODE_IN_CALL);

         currVolume = audioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL);

         if(!audioManager.isSpeakerphoneOn()) {
           audioManager.setSpeakerphoneOn(true);

           audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,
                  audioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL ),
                  AudioManager.STREAM_VOICE_CALL);
         }
        } catch (Exception e) {
            e.printStackTrace();
        }
     }


    //关闭扬声器
    public void CloseSpeaker() {
    
        try {
            AudioManager audioManager = (AudioManager) mContext.getSystemService     (Context.AUDIO_SERVICE);
            if(audioManager != null) {
                if(audioManager.isSpeakerphoneOn()) {
                  audioManager.setSpeakerphoneOn(false);
                  audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,currVolume,
                             AudioManager.STREAM_VOICE_CALL);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
          //Toast.makeText(context,"扬声器已经关闭",Toast.LENGTH_SHORT).show();
    }

 注意:

              1.setSpeakerphoneOn() only work when audio mode set to MODE_IN_CALL. Try this:

           AudioManager audioManager = (AudioManager)mActivity.getSystemService(Context.AUDIO_SERVICE);

           audioManager.setMode(AudioManager.MODE_IN_CALL);

          audioManager.setSpeakerphoneOn(true);

             2. android.permission.MODIFY_AUDIO_SETTINGS

                  permission set in your manifest file because setSpeakerPhoneOn() requires that permission.

你可能感兴趣的:(Android打开/关闭免提(SpeakerPhone))