Java Code Examples for android.media.AudioManager#isWiredHeadsetOn()

The following examples show how to use android.media.AudioManager#isWiredHeadsetOn() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RespokeCall.java    From respoke-sdk-android with MIT License 6 votes vote down vote up
private void addLocalStreams(Context context) {
    AudioManager audioManager = ((AudioManager) context.getSystemService(Context.AUDIO_SERVICE));
    // TODO(fischman): figure out how to do this Right(tm) and remove the suppression.
    @SuppressWarnings("deprecation")
    boolean isWiredHeadsetOn = audioManager.isWiredHeadsetOn();
    audioManager.setMode(isWiredHeadsetOn ? AudioManager.MODE_IN_CALL : AudioManager.MODE_IN_COMMUNICATION);
    audioManager.setSpeakerphoneOn(!isWiredHeadsetOn);

    localStream = peerConnectionFactory.createLocalMediaStream("ARDAMS");

    if (!audioOnly) {
        VideoCapturer capturer = getVideoCapturer();
        MediaConstraints videoConstraints = new MediaConstraints();
        videoSource = peerConnectionFactory.createVideoSource(capturer, videoConstraints);
        VideoTrack videoTrack = peerConnectionFactory.createVideoTrack("ARDAMSv0", videoSource);
        videoTrack.addRenderer(new VideoRenderer(localRender));
        localStream.addTrack(videoTrack);
    }

    localStream.addTrack(peerConnectionFactory.createAudioTrack("ARDAMSa0", peerConnectionFactory.createAudioSource(new MediaConstraints())));

    peerConnection.addStream(localStream);
}
 
Example 2
Source File: URawAudioMixFilter.java    From UCDLive_Android with MIT License 6 votes vote down vote up
public URawAudioMixFilter(Context context, Mode mixMode, boolean isLooper) {
    this.context = context;
    this.isLooper = isLooper;
    this.mixMode = mixMode;
    headsetPlugReceiver = new HeadsetPlugReceiver();
    IntentFilter  filter = new IntentFilter();
    filter.addAction(Intent.ACTION_HEADSET_PLUG);
    this.context.registerReceiver(headsetPlugReceiver, filter);
    if (mixMode == Mode.JUST_HEADSET_ON) {
        AudioManager audioManager = (AudioManager) this.context.getSystemService(Context.AUDIO_SERVICE);
        isMixBgm = audioManager.isWiredHeadsetOn();
    }
    else {
        isMixBgm = true;
    }
}
 
Example 3
Source File: HeadsetTracker.java    From Easer with GNU General Public License v3.0 6 votes vote down vote up
HeadsetTracker(Context context, HeadsetUSourceData data,
               @NonNull PendingIntent event_positive,
               @NonNull PendingIntent event_negative) {
    super(context, data, event_positive, event_negative);

    boolean plugged_in = false;
    Boolean has_microphone = null;

    AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
        AudioDeviceInfo[] audioDevices = audioManager.getDevices(AudioManager.GET_DEVICES_ALL);
        for (AudioDeviceInfo deviceInfo : audioDevices) {
            if (deviceInfo.getType() == AudioDeviceInfo.TYPE_WIRED_HEADPHONES
                    || deviceInfo.getType() == AudioDeviceInfo.TYPE_WIRED_HEADSET) {
                plugged_in = true;
                has_microphone = deviceInfo.isSource();
            }
        }
    } else {
        plugged_in = audioManager.isWiredHeadsetOn();
    }
    Boolean match = determine_match(data, plugged_in, has_microphone);
    newSatisfiedState(match);
}
 
Example 4
Source File: AudioUtil.java    From Augendiagnose with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Check if a headset is plugged.
 *
 * @return true if a headset is plugged.
 */
@SuppressWarnings("deprecation")
public static boolean isHeadphonePlugged() {
	AudioManager audioManager = (AudioManager) Application.getAppContext().getSystemService(Context.AUDIO_SERVICE);
	//noinspection deprecation
	return audioManager.isWiredHeadsetOn();
}
 
Example 5
Source File: HxCallBaseActivity.java    From FamilyChat with Apache License 2.0 5 votes vote down vote up
@Override
protected void beforeInitUI(Bundle savedInstanceState)
{
    super.beforeInitUI(savedInstanceState);
    //获取音频管理器
    mAudioMgr = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
    mAudioMgr.setSpeakerphoneOn(false);
    if (mAudioMgr.isWiredHeadsetOn())//耳机模式下设置Mode为Communication,否则设置为Ringtong
        mAudioMgr.setMode(AudioManager.MODE_IN_COMMUNICATION);
    else
        mAudioMgr.setMode(AudioManager.MODE_RINGTONE);
    //获取震动管理器
    mVibratorMgr = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
}
 
Example 6
Source File: MessageListActivity.java    From aurora-imui with MIT License 5 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent event) {
    AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
    try {
        if (audioManager.isBluetoothA2dpOn() || audioManager.isWiredHeadsetOn()) {
            return;
        }
        if (mAdapter.getMediaPlayer().isPlaying()) {
            float distance = event.values[0];
            if (distance >= mSensor.getMaximumRange()) {
                mAdapter.setAudioPlayByEarPhone(0);
                setScreenOn();
            } else {
                mAdapter.setAudioPlayByEarPhone(2);
                ViewHolderController.getInstance().replayVoice();
                setScreenOff();
            }
        } else {
            if (mWakeLock != null && mWakeLock.isHeld()) {
                mWakeLock.release();
                mWakeLock = null;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}
 
Example 7
Source File: ReactMsgListManager.java    From aurora-imui with MIT License 5 votes vote down vote up
@Override
public void onSensorChanged(SensorEvent event) {
    AudioManager audioManager = (AudioManager) mContext.getSystemService(AUDIO_SERVICE);
    try {
        if (audioManager.isBluetoothA2dpOn() || audioManager.isWiredHeadsetOn()) {
            return;
        }
        if (mAdapter.getMediaPlayer().isPlaying()) {
            float distance = event.values[0];
            if (distance >= mSensor.getMaximumRange()) {
                mAdapter.setAudioPlayByEarPhone(0);
                setScreenOn();
            } else {
                mAdapter.setAudioPlayByEarPhone(2);
                ViewHolderController.getInstance().replayVoice();
                setScreenOff();
            }
        } else {
            if (mWakeLock != null && mWakeLock.isHeld()) {
                mWakeLock.release();
                mWakeLock = null;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}
 
Example 8
Source File: Device.java    From unity-ads-android with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
public static boolean isWiredHeadsetOn() {
	if (ClientProperties.getApplicationContext() != null) {
		AudioManager am = (AudioManager)ClientProperties.getApplicationContext().getSystemService(Context.AUDIO_SERVICE);

		// Note: This method is officially deprecated but documentation gives more fine-grained approach. This method
		// returns whether headset is connected or not. Audio playback might be routed through other means. Since we are
		// not using this value for making audio routing decisions, using this is ok and supported by Android docs.
		return am.isWiredHeadsetOn();
	}

	return false;
}
 
Example 9
Source File: AudioManagerUtils.java    From DevUtils with Apache License 2.0 5 votes vote down vote up
/**
 * 判断是否插入了耳机
 * @return {@code true} yes, {@code false} no
 */
public static boolean isWiredHeadsetOn() {
    AudioManager audioManager = AppUtils.getAudioManager();
    if (audioManager != null) {
        try {
            return audioManager.isWiredHeadsetOn();
        } catch (Exception e) {
            LogPrintUtils.eTag(TAG, e, "isWiredHeadsetOn");
        }
    }
    return false;
}
 
Example 10
Source File: SignalAudioManager.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
public void startIncomingRinger() {
  AudioManager audioManager = AppUtil.INSTANCE.getAudioManager(context);
  boolean      speaker      = !audioManager.isWiredHeadsetOn() && !audioManager.isBluetoothScoOn();

  audioManager.setMode(AudioManager.MODE_RINGTONE);
  audioManager.setMicrophoneMute(false);
  audioManager.setSpeakerphoneOn(speaker);

  incomingRinger.start();
}
 
Example 11
Source File: SignalAudioManager.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public void startIncomingRinger(@Nullable Uri ringtoneUri, boolean vibrate) {
  AudioManager audioManager = ServiceUtil.getAudioManager(context);
  boolean      speaker      = !audioManager.isWiredHeadsetOn() && !audioManager.isBluetoothScoOn();

  audioManager.setMode(AudioManager.MODE_RINGTONE);
  audioManager.setMicrophoneMute(false);
  audioManager.setSpeakerphoneOn(speaker);

  incomingRinger.start(ringtoneUri, vibrate);
}
 
Example 12
Source File: WebRtcCallService.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
private LockManager.PhoneState getInCallPhoneState() {
  AudioManager audioManager = ServiceUtil.getAudioManager(this);
  if (audioManager.isSpeakerphoneOn() || audioManager.isBluetoothScoOn() || audioManager.isWiredHeadsetOn()) {
    return LockManager.PhoneState.IN_HANDS_FREE_CALL;
  } else {
    return LockManager.PhoneState.IN_CALL;
  }
}
 
Example 13
Source File: ActivityCallViewModel.java    From iGap-Android with GNU Affero General Public License v3.0 4 votes vote down vote up
public void playRingtone() {
    boolean canPlay = false;
    AudioManager am = (AudioManager) G.context.getSystemService(Context.AUDIO_SERVICE);

    switch (am.getRingerMode()) {
        case AudioManager.RINGER_MODE_SILENT:
            canPlay = false;
            break;
        case AudioManager.RINGER_MODE_VIBRATE:
            canPlay = false;

            vibrator = (Vibrator) G.context.getSystemService(Context.VIBRATOR_SERVICE);
            long[] pattern = {0, 100, 1000};
            vibrator.vibrate(pattern, 0);

            break;
        case AudioManager.RINGER_MODE_NORMAL:
            canPlay = true;
            break;
    }

    if (am.isWiredHeadsetOn()) {
        canPlay = true;
    }

    if (canPlay) {

        try {
            Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
            String path = AttachFile.getFilePathFromUri(alert);

            ringtonePlayer = new MediaPlayer();

            if (path == null) {
                ringtonePlayer.setDataSource(context, Uri.parse("android.resource://" + G.context.getPackageName() + "/" + R.raw.tone));
            } else {
                ringtonePlayer.setDataSource(G.context, alert);
            }

            if (am.isWiredHeadsetOn()) {
                ringtonePlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
            } else {
                ringtonePlayer.setAudioStreamType(AudioManager.STREAM_RING);
            }

            ringtonePlayer.setLooping(true);
            ringtonePlayer.prepare();
            ringtonePlayer.start();
        } catch (Exception e) {
            HelperLog.setErrorLog("activity call view model   set ringtone uri  " + e);
        }
    }

    startRingAnimation();
}
 
Example 14
Source File: PMedia.java    From PHONK with GNU General Public License v3.0 4 votes vote down vote up
public boolean isHeadsetPlugged() {
    AudioManager audioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
    return audioManager.isWiredHeadsetOn();
}
 
Example 15
Source File: WeatherByVoiceService.java    From your-local-weather with GNU General Public License v3.0 4 votes vote down vote up
private Long isAnySettingValidToTellWeather(Long voiceSettingId, boolean initiatedFromBtDevice) {
    AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    if (isActiveCall(audioManager)) {
        appendLog(getBaseContext(), TAG, "There is active phone call, not going to say anything");
        return null;
    }

    if (initiatedFromBtDevice) {
        appendLog(getBaseContext(), TAG, "Initiated from BT device, ommitin the rest of the settings");
        return voiceSettingId;
    }

    boolean isHeadsetConnected = audioManager.isWiredHeadsetOn();
    boolean isBluetoothConnected = Utils.isBluetoothHeadsetEnabledConnected(getBaseContext());

    VoiceSettingParametersDbHelper voiceSettingParametersDbHelper = VoiceSettingParametersDbHelper.getInstance(getBaseContext());
    Map<Long, Long> enabledVoiceDevices = voiceSettingParametersDbHelper.getLongParam(
            VoiceSettingParamType.VOICE_SETTING_ENABLED_VOICE_DEVICES.getVoiceSettingParamTypeId());
    appendLog(getBaseContext(), TAG, "isAnySettingValidToTellWeather enabledVoiceDevices: " + enabledVoiceDevices);
    if (enabledVoiceDevices == null) {
        appendLog(getBaseContext(), TAG, "Bluetooth or wired headset is not enabled or connected");
        return null;
    }
    appendLog(getBaseContext(), TAG, "isAnySettingValidToTellWeather voiceSettingId: " + voiceSettingId);
    if (voiceSettingId != null) {
        if (TimeUtils.isCurrentSettingIndex(enabledVoiceDevices.get(voiceSettingId), 2)) {
            appendLog(getBaseContext(), TAG, "speaker_enabled");
            return !(isBluetoothConnected || isHeadsetConnected)? voiceSettingId : null;
        }
        if (TimeUtils.isCurrentSettingIndex(enabledVoiceDevices.get(voiceSettingId), 1)) {
            appendLog(getBaseContext(), TAG, "wired_enabled");
            return isHeadsetConnected ? voiceSettingId : null;
        }
        if (TimeUtils.isCurrentSettingIndex(enabledVoiceDevices.get(voiceSettingId), 0)) {
            appendLog(getBaseContext(), TAG, "bt_enabled");
            return (isBluetoothConnected && isBtDeviceEnabled(voiceSettingId)) ? voiceSettingId : null;
        }
    } else {
        for (Long currentVoiceSettingId : enabledVoiceDevices.keySet()) {
            Long enabledVoiceDevice = enabledVoiceDevices.get(currentVoiceSettingId);
            appendLog(getBaseContext(), TAG, "isAnySettingValidToTellWeather enabledVoiceDevice: " + enabledVoiceDevice);
            if (TimeUtils.isCurrentSettingIndex(enabledVoiceDevice, 2)) {
                appendLog(getBaseContext(), TAG, "speaker_enabled");
                return !(isBluetoothConnected || isHeadsetConnected)? currentVoiceSettingId : null;
            }
            if (TimeUtils.isCurrentSettingIndex(enabledVoiceDevice, 1)) {
                appendLog(getBaseContext(), TAG, "wired_enabled");
                return isHeadsetConnected ? currentVoiceSettingId : null;
            }
            if (TimeUtils.isCurrentSettingIndex(enabledVoiceDevice, 0)) {
                appendLog(getBaseContext(), TAG, "bt_enabled");
                return (isBluetoothConnected && isBtDeviceEnabled(currentVoiceSettingId)) ? currentVoiceSettingId : null;
            }
        }
    }
    return null;
}
 
Example 16
Source File: VOIPActivity.java    From voip_android with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private boolean getHeadphoneStatus() {
    AudioManager audioManager = (AudioManager)getSystemService(AUDIO_SERVICE);
    boolean headphone = audioManager.isWiredHeadsetOn() || audioManager.isBluetoothA2dpOn();
    return headphone;
}
 
Example 17
Source File: RNDeviceModule.java    From react-native-device-info with MIT License 4 votes vote down vote up
@ReactMethod(isBlockingSynchronousMethod = true)
public boolean isHeadphonesConnectedSync() {
  AudioManager audioManager = (AudioManager)getReactApplicationContext().getSystemService(Context.AUDIO_SERVICE);
  return audioManager.isWiredHeadsetOn() || audioManager.isBluetoothA2dpOn();
}
 
Example 18
Source File: AppRTCDemoActivity.java    From droidkit-webrtc with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  Thread.setDefaultUncaughtExceptionHandler(
      new UnhandledExceptionHandler(this));

  getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
  getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

  Point displaySize = new Point();
  getWindowManager().getDefaultDisplay().getRealSize(displaySize);

  vsv = new AppRTCGLView(this, displaySize);
  VideoRendererGui.setView(vsv);
  remoteRender = VideoRendererGui.create(0, 0, 100, 100);
  localRender = VideoRendererGui.create(70, 5, 25, 25);

  vsv.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        toggleHUD();
      }
    });
  setContentView(vsv);
  logAndToast("Tap the screen to toggle stats visibility");

  hudView = new TextView(this);
  hudView.setTextColor(Color.BLACK);
  hudView.setBackgroundColor(Color.WHITE);
  hudView.setAlpha(0.4f);
  hudView.setTextSize(TypedValue.COMPLEX_UNIT_PT, 5);
  hudView.setVisibility(View.INVISIBLE);
  addContentView(hudView, hudLayout);

  if (!factoryStaticInitialized) {
    abortUnless(PeerConnectionFactory.initializeAndroidGlobals(
        this, true, true),
      "Failed to initializeAndroidGlobals");
    factoryStaticInitialized = true;
  }

  AudioManager audioManager =
      ((AudioManager) getSystemService(AUDIO_SERVICE));
  // TODO(fischman): figure out how to do this Right(tm) and remove the
  // suppression.
  @SuppressWarnings("deprecation")
  boolean isWiredHeadsetOn = audioManager.isWiredHeadsetOn();
  audioManager.setMode(isWiredHeadsetOn ?
      AudioManager.MODE_IN_CALL : AudioManager.MODE_IN_COMMUNICATION);
  audioManager.setSpeakerphoneOn(!isWiredHeadsetOn);

  sdpMediaConstraints = new MediaConstraints();
  sdpMediaConstraints.mandatory.add(new MediaConstraints.KeyValuePair(
      "OfferToReceiveAudio", "true"));
  sdpMediaConstraints.mandatory.add(new MediaConstraints.KeyValuePair(
      "OfferToReceiveVideo", "true"));

  final Intent intent = getIntent();
  if ("android.intent.action.VIEW".equals(intent.getAction())) {
    connectToRoom(intent.getData().toString());
    return;
  }
  showGetRoomUI();
}
 
Example 19
Source File: WebRtcCallService.java    From mollyim-android with GNU General Public License v3.0 4 votes vote down vote up
private void handleSetEnableVideo(Intent intent) {
  boolean      enable       = intent.getBooleanExtra(EXTRA_ENABLE, false);
  AudioManager audioManager = ServiceUtil.getAudioManager(this);

  if (activePeer == null) {
    Log.w(TAG, "handleSetEnableVideo(): Ignoring for inactive call.");
    return;
  }

  Log.i(TAG, "handleSetEnableVideo(): call_id: " + activePeer.getCallId());

  if (activePeer.getState() != CallState.CONNECTED) {
    enableVideoOnCreate = enable;

    if (enableVideoOnCreate              &&
        !audioManager.isSpeakerphoneOn() &&
        !audioManager.isBluetoothScoOn() &&
        !audioManager.isWiredHeadsetOn())
    {
      audioManager.setSpeakerphoneOn(true);
    }

    return;
  }

  try {
    callManager.setVideoEnable(enable);
  } catch  (CallException e) {
    callFailure("setVideoEnable() failed: ", e);
    return;
  }

  localCameraState = camera.getCameraState();

  if (localCameraState.isEnabled()) {
    lockManager.updatePhoneState(LockManager.PhoneState.IN_VIDEO);
  } else {
    lockManager.updatePhoneState(getInCallPhoneState());
  }

  if (localCameraState.isEnabled() &&
      !audioManager.isSpeakerphoneOn() &&
      !audioManager.isBluetoothScoOn() &&
      !audioManager.isWiredHeadsetOn())
  {
    audioManager.setSpeakerphoneOn(true);
  }

  sendMessage(viewModelStateFor(activePeer), activePeer, localCameraState, remoteVideoEnabled, bluetoothAvailable, microphoneEnabled, isRemoteVideoOffer);
}
 
Example 20
Source File: BluetoothUtil.java    From sealrtc-android with MIT License 2 votes vote down vote up
/**
 * 是否插入了有线耳机
 *
 * @param context
 * @return
 */
public static boolean isWiredHeadsetOn(Context context) {
    AudioManager audioManager = (AudioManager) context.getSystemService(AUDIO_SERVICE);
    return audioManager.isWiredHeadsetOn();
}