android.media.AudioManager Java Examples

The following examples show how to use android.media.AudioManager. 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: CustomMediaController.java    From MyHearts with Apache License 2.0 6 votes vote down vote up
/**
 * 声音高低
 *
 * @param percent
 */
private void onVolumeSlide(float percent) {
    if (mVolume == -1) {
        mVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        if (mVolume < 0)
            mVolume = 0;

        mOperationBg.setImageResource(R.drawable.video_volumn_bg);
        mVolumeBrightnessLayout.setVisibility(View.VISIBLE);
    }

    int index = (int) (percent * mMaxVolume) + mVolume;
    if (index > mMaxVolume)
        index = mMaxVolume;
    else if (index < 0)
        index = 0;

    mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, index, 0);
    ViewGroup.LayoutParams lp = mOperationPercent.getLayoutParams();
    lp.width = findViewById(R.id.operation_full).getLayoutParams().width * index / mMaxVolume;
    mOperationPercent.setLayoutParams(lp);
}
 
Example #2
Source File: VideoViewerActivity.java    From CameraV with GNU General Public License v3.0 6 votes vote down vote up
private void playVideo(Uri uri) {
doCleanUp();
try {


  // Create a new media player and set the listeners
  mMediaPlayer = new MediaPlayer();
  mMediaPlayer.setDataSource(this, uri);
  mMediaPlayer.setDisplay(holder);
  mMediaPlayer.prepare();
  mMediaPlayer.setOnBufferingUpdateListener(this);
  mMediaPlayer.setOnCompletionListener(this);
  mMediaPlayer.setOnPreparedListener(this);
  mMediaPlayer.setOnVideoSizeChangedListener(this);
  mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

} catch (Exception e) {
  Log.e(TAG, "error: " + e.getMessage(), e);
}
}
 
Example #3
Source File: KcaUtils.java    From kcanotify with GNU General Public License v3.0 6 votes vote down vote up
public static void playNotificationSound(MediaPlayer mediaPlayer, Context context, Uri uri) {
    try {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
            mediaPlayer.reset();
        }
        if (uri != null && !Uri.EMPTY.equals(uri)) {
            mediaPlayer.setDataSource(context, uri);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                AudioAttributes attr = new AudioAttributes.Builder()
                        .setLegacyStreamType(AudioManager.STREAM_NOTIFICATION)
                        .build();
                mediaPlayer.setAudioAttributes(attr);
            } else {
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
            }
            mediaPlayer.prepare();
            mediaPlayer.start();
        }
    } catch (IllegalArgumentException | SecurityException | IllegalStateException | IOException e) {
        e.printStackTrace();
    }
}
 
Example #4
Source File: BluetoothManager.java    From Linphone4Android with GNU General Public License v3.0 6 votes vote down vote up
public void initBluetooth() {
	if (!ensureInit()) {
		Log.w("[Bluetooth] Manager tried to init bluetooth but LinphoneService not ready yet...");
		return;
	}
	
	IntentFilter filter = new IntentFilter();
	filter.addCategory(BluetoothHeadset.VENDOR_SPECIFIC_HEADSET_EVENT_COMPANY_ID_CATEGORY + "." + BluetoothAssignedNumbers.PLANTRONICS);
	filter.addAction(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
	filter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);
	filter.addAction(BluetoothHeadset.ACTION_VENDOR_SPECIFIC_HEADSET_EVENT);
	mContext.registerReceiver(this,  filter);
	Log.d("[Bluetooth] Receiver started");
	
	startBluetooth();
}
 
Example #5
Source File: AudioFlingerProxy.java    From Noyze with Apache License 2.0 6 votes vote down vote up
/**
 * Set the volume_3 of a calibrated stream.
 * @see {@link #setStreamVolume(int, float)}
 * @throws RemoteException
 */
public int adjustStreamVolume(int stream, int direction, int index, int max) throws RemoteException {
    LogUtils.LOGI("AudioFlingerProxy", "adjustStreamVolume(" + stream + ", " + direction + ")");
    if (null == mAudioFlinger || TextUtils.isEmpty(mInterfaceDescriptor) || !isCalibrated(stream)) {
        return BAD_VALUE;
    }

    float value = getStreamVolume(stream);
    float increment = getStreamIncrement(stream);

    float newValue = value;
    switch (direction) {
        case AudioManager.ADJUST_LOWER:
            newValue -= increment;
        case AudioManager.ADJUST_RAISE:
            newValue += increment;
    }
    newValue = Math.max(0, Math.min(newValue, max * increment));

    LogUtils.LOGI("AudioFlingerProxy", "adjustStreamVolume() increment = " + increment + ", newVolume = " + newValue);
    return setStreamVolume(stream, newValue);
}
 
Example #6
Source File: SubsonicActivity.java    From Audinaut with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle bundle) {
    PackageManager pm = getPackageManager();
    if (!pm.hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN)) {
        touchscreen = false;
    }

    applyTheme();
    applyFullscreen();
    super.onCreate(bundle);
    startService(new Intent(this, DownloadService.class));
    setVolumeControlStream(AudioManager.STREAM_MUSIC);

    if (getIntent().hasExtra(Constants.FRAGMENT_POSITION)) {
        lastSelectedPosition = getIntent().getIntExtra(Constants.FRAGMENT_POSITION, 0);
    }

    if (preferencesListener == null) {
        Util.getPreferences(this).registerOnSharedPreferenceChangeListener(preferencesListener);
    }

    if (ContextCompat.checkSelfPermission(this, permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{permission.WRITE_EXTERNAL_STORAGE}, PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
    }
}
 
Example #7
Source File: PronounceService.java    From Gojuon with MIT License 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    String charset = intent.getStringExtra(EXTRA_CHARSET);
    if (charset != null && charset.length() > 0) {
        try {
            AssetFileDescriptor pronounceFile = getPronounceAssetFile(charset);
            if (pronounceFile.getLength() > 0) {
                final int playId = mSoundPool.load(pronounceFile, 1);
                mSoundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
                    @Override
                    public void onLoadComplete(SoundPool soundPool, int i, int i2) {
                        int volume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
                        mSoundPool.play(playId, volume, volume, 1, 0, 1f);
                        mSoundPool.unload(playId);
                    }
                });
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
 
Example #8
Source File: AudioSlidePlayer.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
private AudioSlidePlayer(@NonNull Context context,
                         @NonNull AudioSlide slide,
                         @NonNull Listener listener)
{
  this.context              = context;
  this.slide                = slide;
  this.listener             = new WeakReference<>(listener);
  this.progressEventHandler = new ProgressEventHandler(this);
  this.audioManager         = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
  this.sensorManager        = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
  this.proximitySensor      = sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);

  if (Build.VERSION.SDK_INT >= 21) {
    this.wakeLock = ServiceUtil.getPowerManager(context).newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, TAG);
  } else {
    this.wakeLock = null;
  }
}
 
Example #9
Source File: HostPhoneProfile.java    From DeviceConnect-Android with MIT License 6 votes vote down vote up
private void setPhoneMode(Intent response, PhoneMode mode) {
    // AudioManager
    AudioManager mAudioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
    if (mode.equals(PhoneMode.SILENT)) {
        mAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
        setResult(response, DConnectMessage.RESULT_OK);
    } else if (mode.equals(PhoneMode.SOUND)) {
        mAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
        setResult(response, DConnectMessage.RESULT_OK);
    } else if (mode.equals(PhoneMode.MANNER)) {
        mAudioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
        setResult(response, DConnectMessage.RESULT_OK);
    } else if (mode.equals(PhoneMode.UNKNOWN)) {
        MessageUtils.setInvalidRequestParameterError(response, "mode is invalid.");
    }
}
 
Example #10
Source File: StatusBarPlusVolumePanel.java    From Noyze with Apache License 2.0 6 votes vote down vote up
@Override
public void onRingerModeChange(int ringerMode) {
    super.onRingerModeChange(ringerMode);
    if (null != mLastVolumeChange) {
        switch (mLastVolumeChange.mStreamType) {
            case AudioManager.STREAM_NOTIFICATION:
            case AudioManager.STREAM_RING:
                switch (ringerMode) {
                    case RINGER_MODE_VIBRATE:
                        icon.setImageResource(getVibrateIcon());
                        break;
                    case RINGER_MODE_SILENT:
                    default:
                        icon.setImageResource(getSilentIcon());
                        break;
                }
                break;
        }
    }
}
 
Example #11
Source File: JCVideoPlayer.java    From JCVideoPlayer with MIT License 6 votes vote down vote up
@Override
    public void onCompletion() {
        setUiWitStateAndScreen(CURRENT_STATE_NORMAL);
        if (textureViewContainer.getChildCount() > 0) {
            textureViewContainer.removeAllViews();
        }

        JCVideoPlayerManager.setListener(null);//这里还不完全,
//        JCVideoPlayerManager.setLastListener(null);
        JCMediaManager.instance().currentVideoWidth = 0;
        JCMediaManager.instance().currentVideoHeight = 0;

        AudioManager mAudioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
        mAudioManager.abandonAudioFocus(onAudioFocusChangeListener);
        JCUtils.scanForActivity(getContext()).getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        clearFullscreenLayout();
    }
 
Example #12
Source File: ListAdapter.java    From jmessage-android-uikit with MIT License 6 votes vote down vote up
public void setAudioPlayByEarPhone(int state) {
    AudioManager audioManager = (AudioManager) mContext
            .getSystemService(Context.AUDIO_SERVICE);
    int currVolume = audioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL);
    audioManager.setMode(AudioManager.MODE_IN_CALL);
    if (state == 0) {
        mIsEarPhoneOn = false;
        audioManager.setSpeakerphoneOn(true);
        audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,
                audioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL),
                AudioManager.STREAM_VOICE_CALL);
        Log.i(TAG, "set SpeakerphoneOn true!");
    } else {
        mIsEarPhoneOn = true;
        audioManager.setSpeakerphoneOn(false);
        audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, currVolume,
                AudioManager.STREAM_VOICE_CALL);
        Log.i(TAG, "set SpeakerphoneOn false!");
    }
}
 
Example #13
Source File: SelectValueActivity.java    From PTVGlass with MIT License 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

    mAdapter = new SelectValueScrollAdapter(
            this, getIntent().getIntExtra(EXTRA_COUNT, DEFAULT_COUNT));

    mView = new CardScrollView(this) {
        @Override
        public final boolean dispatchGenericFocusedEvent(MotionEvent event) {
            if (mDetector.onMotionEvent(event)) {
                return true;
            }
            return super.dispatchGenericFocusedEvent(event);
        }
    };
    mView.setAdapter(mAdapter);
    setContentView(mView);

    mDetector = new GestureDetector(this).setBaseListener(this);
}
 
Example #14
Source File: ExoVideoView.java    From v9porn with MIT License 6 votes vote down vote up
/**
 * Requests to obtain the audio focus
 *
 * @return True if the focus was granted
 */
public boolean requestFocus() {
    if (!handleAudioFocus || currentFocus == AudioManager.AUDIOFOCUS_GAIN) {
        return true;
    }

    if (audioManager == null) {
        return false;
    }

    int status = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
    if (AudioManager.AUDIOFOCUS_REQUEST_GRANTED == status) {
        currentFocus = AudioManager.AUDIOFOCUS_GAIN;
        return true;
    }

    startRequested = true;
    return false;
}
 
Example #15
Source File: MainActivity.java    From connectivity-samples with Apache License 2.0 6 votes vote down vote up
@Override
protected void onStop() {
  mSensorManager.unregisterListener(this);

  // Restore the original volume.
  AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
  audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, mOriginalVolume, 0);
  setVolumeControlStream(AudioManager.USE_DEFAULT_STREAM_TYPE);

  if (isRecording()) {
    stopRecording();
  }
  if (isPlaying()) {
    stopPlaying();
  }

  setState(State.UNKNOWN);

  mUiHandler.removeCallbacksAndMessages(null);

  if (mCurrentAnimator != null && mCurrentAnimator.isRunning()) {
    mCurrentAnimator.cancel();
  }

  super.onStop();
}
 
Example #16
Source File: SetTimerActivity.java    From PTVGlass with MIT License 6 votes vote down vote up
@Override
public boolean onGesture(Gesture gesture) {
    if (gesture == Gesture.TAP) {
        int position = mView.getSelectedItemPosition();
        SetTimerScrollAdapter.TimeComponents component =
                (SetTimerScrollAdapter.TimeComponents) mAdapter.getItem(position);
        Intent selectValueIntent = new Intent(this, SelectValueActivity.class);

        selectValueIntent.putExtra(SelectValueActivity.EXTRA_COUNT, component.getMaxValue());
        selectValueIntent.putExtra(
                SelectValueActivity.EXTRA_INITIAL_VALUE,
                (int) mAdapter.getTimeComponent(component));
        startActivityForResult(selectValueIntent, SELECT_VALUE);
        mAudioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
        return true;
    }
    return false;
}
 
Example #17
Source File: IflySynthesizer.java    From AssistantBySDK with Apache License 2.0 6 votes vote down vote up
@Override
public void onAudioFocusChange(int focusChange) {
    Log.e(TAG, "audioFocusChangeListener.onAudioFocusChange>>>>>>>>>>>>>>>>>>" + focusChange);
    switch (focusChange) {
        case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
        case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
            // pauseSpeaking();
            break;
        case AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK:
        case AudioManager.AUDIOFOCUS_GAIN_TRANSIENT:
            /*if (isSpeaking()) {
                synthesizer.resumeSpeaking();
            }*/
            break;
        default:
            break;
    }
}
 
Example #18
Source File: MqttSettingsCodeReaderFragment.java    From Bluefruit_LE_Connect_Android_V2 with MIT License 6 votes vote down vote up
@Override
public void onCodeScanned(String contents) {
    Log.d(TAG, "Code Scanned: " + contents);
    if (isCodeAlreadyScanned) {
        return;
    }       // To avoid double scans and pop 2 times the fragment
    isCodeAlreadyScanned = true;

    // Beep
    final ToneGenerator tg = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 100);
    tg.startTone(ToneGenerator.TONE_PROP_BEEP);

    //
    mListener.onPasswordUpdated(contents);

    // Pop current fragment
    FragmentActivity activity = getActivity();
    if (activity != null) {
        FragmentManager fragmentManager = activity.getSupportFragmentManager();
        fragmentManager.popBackStack();
    }
}
 
Example #19
Source File: BluetoothStateManager.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
private boolean isBluetoothAvailable() {
    try {
        synchronized (LOCK) {
            AudioManager audioManager = AppUtil.INSTANCE.getAudioManager(context);

            if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
                return false;
            }
            if (!audioManager.isBluetoothScoAvailableOffCall()) {
                return false;
            }

            return bluetoothHeadset != null && !bluetoothHeadset.getConnectedDevices().isEmpty();
        }
    } catch (Exception e) {
        Log.w(TAG, e);
        return false;
    }
}
 
Example #20
Source File: LatinIME.java    From hackerskeyboard with Apache License 2.0 6 votes vote down vote up
private void playKeyClick(int primaryCode) {
    // if mAudioManager is null, we don't have the ringer state yet
    // mAudioManager will be set by updateRingerMode
    if (mAudioManager == null) {
        if (mKeyboardSwitcher.getInputView() != null) {
            updateRingerMode();
        }
    }
    if (mSoundOn && !mSilentMode) {
        // FIXME: Volume and enable should come from UI settings
        // FIXME: These should be triggered after auto-repeat logic
        int sound = AudioManager.FX_KEYPRESS_STANDARD;
        switch (primaryCode) {
        case Keyboard.KEYCODE_DELETE:
            sound = AudioManager.FX_KEYPRESS_DELETE;
            break;
        case ASCII_ENTER:
            sound = AudioManager.FX_KEYPRESS_RETURN;
            break;
        case ASCII_SPACE:
            sound = AudioManager.FX_KEYPRESS_SPACEBAR;
            break;
        }
        mAudioManager.playSoundEffect(sound, getKeyClickVolume());
    }
}
 
Example #21
Source File: DatabaseHelper.java    From Study_Android_Demo with Apache License 2.0 6 votes vote down vote up
private void loadVibrateSetting(SQLiteDatabase db, boolean deleteOld) {
    if (deleteOld) {
        db.execSQL("DELETE FROM system WHERE name='" + Settings.System.VIBRATE_ON + "'");
    }

    SQLiteStatement stmt = null;
    try {
        stmt = db.compileStatement("INSERT OR IGNORE INTO system(name,value)"
                + " VALUES(?,?);");

        // Vibrate on by default for ringer, on for notification
        int vibrate = 0;
        vibrate = AudioSystem.getValueForVibrateSetting(vibrate,
                AudioManager.VIBRATE_TYPE_NOTIFICATION,
                AudioManager.VIBRATE_SETTING_ONLY_SILENT);
        vibrate |= AudioSystem.getValueForVibrateSetting(vibrate,
                AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_ONLY_SILENT);
        loadSetting(stmt, Settings.System.VIBRATE_ON, vibrate);
    } finally {
        if (stmt != null) stmt.close();
    }
}
 
Example #22
Source File: MainActivity.java    From crazyflie-android-client with GNU General Public License v2.0 5 votes vote down vote up
private void initializeSounds() {
    this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
    // Load sounds
    mSoundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
    mSoundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
        @Override
        public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
            mLoaded = true;
        }
    });
    mSoundConnect = mSoundPool.load(this, R.raw.proxima, 1);
    mSoundDisconnect = mSoundPool.load(this, R.raw.tejat, 1);
}
 
Example #23
Source File: MediaPlayerUtils.java    From itag with GNU General Public License v3.0 5 votes vote down vote up
public void stopSound(Context context) {
    if (MediaPlayerUtils.getInstance().isSound()) {
        stopFindingPhones();
        MediaPlayerUtils.getInstance().stop();
        if (mVolumeLevel >= 0) {
            AudioManager am = (AudioManager) context.getSystemService(AUDIO_SERVICE);
            if (am != null) {
                am.setStreamVolume(AudioManager.STREAM_ALARM, mVolumeLevel, 0);
                mVolumeLevel = -1;
            }
        }
    }
    stopVibrate();
}
 
Example #24
Source File: AndroidMediaPlayer.java    From ShareBox with Apache License 2.0 5 votes vote down vote up
public AndroidMediaPlayer() {
    synchronized (mInitLock) {
        mInternalMediaPlayer = new MediaPlayer();
    }
    mInternalMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mInternalListenerAdapter = new AndroidMediaPlayerListenerHolder(this);
    attachInternalListeners();
}
 
Example #25
Source File: MediaActionService.java    From LibreTasks with Apache License 2.0 5 votes vote down vote up
/**
  * set the phone to silent
  */
 private void playMedia() {
   AudioManager audioManager =(AudioManager) getSystemService(Context.AUDIO_SERVICE);
   long eventtime = SystemClock.uptimeMillis() - 1;
KeyEvent downEvent = new KeyEvent(eventtime, eventtime, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PLAY, 0);
KeyEvent upEvent = new KeyEvent(eventtime, eventtime, KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MEDIA_PLAY, 0);
audioManager.dispatchMediaKeyEvent(downEvent);
audioManager.dispatchMediaKeyEvent(upEvent);
  }
 
Example #26
Source File: RadioPlaybackService.java    From Sky31Radio with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    App app = (App) getApplication();
    app.inject(this);

    player = new RadioPlayer();
    receiver = new PlayerReceiver();
    notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    IntentFilter filter = new IntentFilter();
    filter.addAction(ACTION_SELECT_PROGRAM_LIST);
    filter.addAction(ACTION_PLAY);
    filter.addAction(ACTION_PAUSE);
    filter.addAction(ACTION_NEXT);
    filter.addAction(ACTION_STOP);
    filter.addAction(ACTION_PREVIOUS);
    filter.addAction(ACTION_SEEK_TO_POSITION);
    filter.addAction(ACTION_SEEK_TO_PERCENT);
    filter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
    registerReceiver(receiver, filter);

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

    WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
    wifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, "wifi_lock");
    wifiLock.acquire();
    int result = audioManager.requestAudioFocus(this,
            AudioManager.STREAM_MUSIC,
            AudioManager.AUDIOFOCUS_GAIN);

    if (result != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
        // could not get audio focus.
    }
    TelephonyManager telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
    telephonyManager.listen(mPhoneListener, PhoneStateListener.LISTEN_CALL_STATE);
}
 
Example #27
Source File: CustomTwilioVideoView.java    From react-native-twilio-video-webrtc with MIT License 5 votes vote down vote up
public void toggleBluetoothHeadset(boolean enabled) {
    AudioManager audioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
    if(enabled){
        audioManager.startBluetoothSco();
    } else {
        audioManager.stopBluetoothSco();
    }
}
 
Example #28
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 #29
Source File: BeepManager.java    From FoodOrdering with Apache License 2.0 5 votes vote down vote up
/**
 * 判断是否需要响铃
 * 
 * @param prefs
 * @param activity
 * @return
 */
private static boolean shouldBeep(SharedPreferences prefs, Context activity) {
	boolean shouldPlayBeep = prefs.getBoolean(
			PreferencesActivity.KEY_PLAY_BEEP, true);
	if (shouldPlayBeep) {
		// See if sound settings overrides this
		AudioManager audioService = (AudioManager) activity
				.getSystemService(Context.AUDIO_SERVICE);
		if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
			shouldPlayBeep = false;
		}
	}
	return shouldPlayBeep;
}
 
Example #30
Source File: CallActivity.java    From Social with Apache License 2.0 5 votes vote down vote up
@Override
protected void onDestroy() {
    if (soundPool != null)
        soundPool.release();
    if (ringtone != null && ringtone.isPlaying())
        ringtone.stop();
    audioManager.setMode(AudioManager.MODE_NORMAL);
    audioManager.setMicrophoneMute(false);

    if(callStateListener != null)
        EMClient.getInstance().callManager().removeCallStateChangeListener(callStateListener);
    releaseHandler();
    super.onDestroy();
}