Example usage for android.content Context AUDIO_SERVICE

List of usage examples for android.content Context AUDIO_SERVICE

Introduction

In this page you can find the example usage for android.content Context AUDIO_SERVICE.

Prototype

String AUDIO_SERVICE

To view the source code for android.content Context AUDIO_SERVICE.

Click Source Link

Document

Use with #getSystemService(String) to retrieve a android.media.AudioManager for handling management of volume, ringer modes and audio routing.

Usage

From source file:org.deviceconnect.android.deviceplugin.host.HostDeviceService.java

/**
 * ?.//ww  w .  j  ava 2  s  . co m
 * 
 * @param status 
 */
public void sendOnStatusChangeEvent(final String status) {

    if (onStatusChangeEventFlag) {
        List<Event> events = EventManager.INSTANCE.getEventList(mDeviceId, MediaPlayerProfile.PROFILE_NAME,
                null, MediaPlayerProfile.ATTRIBUTE_ON_STATUS_CHANGE);

        AudioManager manager = (AudioManager) this.getContext().getSystemService(Context.AUDIO_SERVICE);

        double maxVolume = 1;
        double mVolume = 0;

        mVolume = manager.getStreamVolume(AudioManager.STREAM_MUSIC);
        maxVolume = manager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);

        double mVolumeValue = mVolume / maxVolume;

        for (int i = 0; i < events.size(); i++) {

            Event event = events.get(i);
            Intent intent = EventManager.createEventMessage(event);

            MediaPlayerProfile.setAttribute(intent, MediaPlayerProfile.ATTRIBUTE_ON_STATUS_CHANGE);
            Bundle mediaPlayer = new Bundle();
            MediaPlayerProfile.setStatus(mediaPlayer, status);
            MediaPlayerProfile.setMediaId(mediaPlayer, myCurrentFilePath);
            MediaPlayerProfile.setMIMEType(mediaPlayer, myCurrentFileMIMEType);
            MediaPlayerProfile.setPos(mediaPlayer, myCurrentMediaPosition);
            MediaPlayerProfile.setVolume(mediaPlayer, mVolumeValue);
            MediaPlayerProfile.setMediaPlayer(intent, mediaPlayer);
            getContext().sendBroadcast(intent);
        }
    }
}

From source file:ibme.sleepap.recording.SignalsRecorder.java

protected void stopRecording() {

    // Cancel dialogs.
    if (delayAlertDialog != null) {
        delayAlertDialog.cancel();//www. j a  va 2s. c o m
    }

    // Unregister listeners.
    try {
        if (ppgEnabled) {
            unregisterReceiver(bluetoothDisconnectReceiver);
        }
    } catch (Exception e) {
        Log.e(Constants.CODE_APP_TAG, "Error unregistering bluetooth disconnect BroadcastReceiver", e);
    }
    try {
        unregisterReceiver(batteryLevelReceiver);
    } catch (Exception e) {
        Log.e(Constants.CODE_APP_TAG, "Error unregistering bluetooth disconnect BroadcastReceiver", e);
    }

    // Stop graphs update.
    if (graphUpdateTask.isRunning()) {
        graphUpdateTask.stopUiUpdates();
    }

    // Audio
    if (audioEnabled) {
        extAudioRecorder.stop();
        extAudioRecorder.release();
    }

    // PPG
    if (ppgEnabled) {
        noninManager.prepareToStop();
    }

    // Actigraphy
    if (actigraphyEnabled) {
        sensorManager.unregisterListener(this);
    }

    try {
        wakeLock.release();
    } catch (Throwable t) {
        Log.e(Constants.CODE_APP_TAG, "Wakelock has already been released", t);
    }

    // Check if we have both stopped and started recording properly. If we
    // have, everything has worked properly. If we haven't, user probably
    // interrupted recordings and we should delete the files they made.
    boolean shouldDelete = sharedPreferences.getBoolean(Constants.PREF_EARLY_EXIT_DELETION,
            Constants.DEFAULT_EARLY_EXIT_DELETION);
    boolean recordingSuccessful = startRecordingFlag && finishRecordingFlag;
    if (shouldDelete && !recordingSuccessful) {
        // User interrupted recording. Recordings are useless - get rid of
        // them.
        if (filesDirPath != null) {
            File filesDir = new File(filesDirPath);
            Utils.deleteDirectory(filesDir);
        }
    } else {
        // Otherwise save the position data - woudn't need to do this if
        // files were to be deleted.
        saveBodyPositionData();
    }

    // Cancel recording notification.
    if (sharedPreferences.getBoolean(Constants.PREF_NOTIFICATIONS, Constants.DEFAULT_NOTIFICATIONS)) {
        notificationManager.cancel(Constants.CODE_APP_NOTIFICATION_ID);
    }

    recordingSign.setVisibility(View.GONE);

    // Let the user know the recording is over.
    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
    dialogBuilder.setTitle(getString(R.string.finishedAlertTitle));
    if (shouldDelete && !recordingSuccessful) {
        dialogBuilder.setMessage(getString(R.string.finishedAlertFailure));
    } else {
        dialogBuilder.setMessage(getString(R.string.finishedAlertSuccess));
        dialogBuilder.setNegativeButton(getString(R.string.analyseButtonText),
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(SignalsRecorder.this, ChooseData.class);
                        File recordingDir = new File(filesDirPath);
                        intent.putExtra(Constants.EXTRA_RECORDING_DIRECTORY, recordingDir);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);
                        finish();
                    }
                });
    }
    dialogBuilder.setPositiveButton(getString(R.string.mainMenuButtonText),
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(SignalsRecorder.this, MainMenu.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);
                }
            });
    dialogBuilder.setCancelable(false);
    dialogBuilder.create().show();

    // Change logcat back if necessary.
    if (sharedPreferences.getBoolean(Constants.PREF_WRITE_LOG, Constants.DEFAULT_WRITE_LOG)) {
        String[] cmd = new String[] { "logcat", "-f", "stdout", "*:V" };
        try {
            Runtime.getRuntime().exec(cmd);
        } catch (IOException e) {
            Log.e(Constants.CODE_APP_TAG, "Error changing logcat back to default", e);
        }
    }

    // Reset phone ringing mode to what it was before user changed it to
    // silent.
    AudioManager am = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
    am.setRingerMode(extras.getInt(Constants.EXTRA_RING_SETTING));
}

From source file:org.cryptsecure.Utility.java

/**
 * Check if is phone completely muted (even no vibration).
 * /*ww w. j  a v  a2 s.  com*/
 * @param context
 *            the context
 * @return true, if is phone muted
 */
public static boolean isPhoneMuted(Context context) {
    AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    switch (audio.getRingerMode()) {
    case AudioManager.RINGER_MODE_NORMAL:
        return false;
    case AudioManager.RINGER_MODE_SILENT:
        return true;
    case AudioManager.RINGER_MODE_VIBRATE:
        return false;
    }
    return false;
}

From source file:org.cryptsecure.Utility.java

/**
 * Check if is phone muted but vibration may still be on.
 * //w w w.  j  a  v  a 2  s. c  o  m
 * @param context
 *            the context
 * @return true, if is phone muted with vibration
 */
public static boolean isPhoneMutedOrVibration(Context context) {
    AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    switch (audio.getRingerMode()) {
    case AudioManager.RINGER_MODE_NORMAL:
        return false;
    case AudioManager.RINGER_MODE_SILENT:
        return false;
    case AudioManager.RINGER_MODE_VIBRATE:
        return true;
    }
    return false;
}

From source file:com.shinymayhem.radiopresets.ServiceRadioPlayer.java

protected void setVolume(int newVolume) {
    AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    audio.setStreamVolume(AudioManager.STREAM_MUSIC, newVolume, 0);
    if (LOCAL_LOGV)
        log("volume set:" + String.valueOf(audio.getStreamVolume(AudioManager.STREAM_MUSIC)), "v");
}

From source file:github.daneren2005.dsub.util.Util.java

@TargetApi(8)
public static void requestAudioFocus(final Context context) {
    if (Build.VERSION.SDK_INT >= 8 && focusListener == null) {
        final AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        audioManager.requestAudioFocus(focusListener = new OnAudioFocusChangeListener() {
            public void onAudioFocusChange(int focusChange) {
                DownloadService downloadService = (DownloadService) context;
                if ((focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT
                        || focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK)
                        && !downloadService.isRemoteEnabled()) {
                    if (downloadService.getPlayerState() == PlayerState.STARTED) {
                        Log.i(TAG, "Temporary loss of focus");
                        SharedPreferences prefs = getPreferences(context);
                        int lossPref = Integer
                                .parseInt(prefs.getString(Constants.PREFERENCES_KEY_TEMP_LOSS, "1"));
                        if (lossPref == 2 || (lossPref == 1
                                && focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK)) {
                            lowerFocus = true;
                            downloadService.setVolume(0.1f);
                        } else if (lossPref == 0
                                || (lossPref == 1 && focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT)) {
                            pauseFocus = true;
                            downloadService.pause(true);
                        }//from   w w w . ja va  2  s.  co m
                    }
                } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
                    if (pauseFocus) {
                        pauseFocus = false;
                        downloadService.start();
                    } else if (lowerFocus) {
                        lowerFocus = false;
                        downloadService.setVolume(1.0f);
                    }
                } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS && !downloadService.isRemoteEnabled()) {
                    Log.i(TAG, "Permanently lost focus");
                    focusListener = null;
                    downloadService.pause();
                    audioManager.abandonAudioFocus(this);
                }
            }
        }, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
    }
}

From source file:com.yangtsaosoftware.pebblemessenger.services.PebbleCenter.java

private void answerCall(boolean isSpeakon) {

    Context context = getApplicationContext();
    AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    // ??// www .  j ava2  s  . c o  m
    if (!(audioManager.isWiredHeadsetOn() || audioManager.isBluetoothA2dpOn())) {
        // 4.1??? 4.1??Permission Denial: not allowed to
        // send broadcast android.intent.action.HEADSET_PLUG from pid=1324,
        // uid=10017
        // ??????android.permission.CALL_PRIVLEGED?????4.1??????????NULL??

        Constants.log("speakerset", String.format("AudioManager before mode:%d speaker mod:%s",
                audioManager.getMode(), String.valueOf(audioManager.isSpeakerphoneOn())));
        Intent meidaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
        KeyEvent keyEvent = new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_HEADSETHOOK);
        meidaButtonIntent.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent);
        context.sendOrderedBroadcast(meidaButtonIntent, "android.permission.CALL_PRIVILEGED");

        /*TelephonyManager telMag = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        Class<TelephonyManager> c = TelephonyManager.class;
        Method mthAnswerCall;
        try {
        mthAnswerCall = c.getDeclaredMethod("getITelephony", (Class[]) null);
        mthAnswerCall.setAccessible(true);
        ITelephony iTel = (ITelephony) mthAnswerCall.invoke(telMag, (Object[]) null);
        iTel.answerRingingCall();
                
        } catch (Exception e) {
        e.printStackTrace();
        }*/
        if (isSpeakon) {
            try {
                Thread.sleep(500);

            } catch (InterruptedException e) {
                Constants.log("speakerset", "Problem while sleeping");
            }
            Constants.log("speakerset", "AudioManager answer mode:" + audioManager.getMode() + " speaker mod:"
                    + String.valueOf(audioManager.isSpeakerphoneOn()));
            while (audioManager.getMode() != AudioManager.MODE_IN_CALL) {
                try {
                    Thread.sleep(300);

                } catch (InterruptedException e) {
                    Constants.log("speakerset", "Problem while sleeping");
                }
            }
            // audioManager.setMicrophoneMute(true);
            audioManager.setSpeakerphoneOn(true);
            // audioManager.setMode(AudioManager.MODE_IN_CALL);
            Constants.log("speakerset", String.format("AudioManager set mode:%d speaker mod:%s",
                    audioManager.getMode(), String.valueOf(audioManager.isSpeakerphoneOn())));

        }
    } else {
        Constants.log("speakerset", String.format("AudioManager before mode:%d speaker mod:%s",
                audioManager.getMode(), String.valueOf(audioManager.isSpeakerphoneOn())));

        Intent meidaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
        KeyEvent keyEvent = new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_HEADSETHOOK);
        meidaButtonIntent.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent);
        context.sendOrderedBroadcast(meidaButtonIntent, "android.permission.CALL_PRIVILEGED");

    }
}

From source file:org.drrickorang.loopback.LoopbackActivity.java

/** Refresh the text on the main activity that shows the app states and audio settings. */
void refreshState() {
    log("refreshState!");

    //get current audio level
    AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    int currentVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC);
    mBarMasterLevel.setProgress(currentVolume);

    mTextViewCurrentLevel.setText(String.format("Sound Level: %d/%d", currentVolume, mBarMasterLevel.getMax()));

    log("refreshState 2b");

    // get info/* w ww .j av  a2 s  . co  m*/
    int samplingRate = getApp().getSamplingRate();
    int playerBuffer = getApp().getPlayerBufferSizeInBytes() / Constant.BYTES_PER_FRAME;
    int recorderBuffer = getApp().getRecorderBufferSizeInBytes() / Constant.BYTES_PER_FRAME;
    StringBuilder s = new StringBuilder(200);
    s.append("SR: " + samplingRate + " Hz");
    int audioThreadType = getApp().getAudioThreadType();
    switch (audioThreadType) {
    case Constant.AUDIO_THREAD_TYPE_JAVA:
        s.append(" Play Frames: " + playerBuffer);
        s.append(" Record Frames: " + recorderBuffer);
        s.append(" Audio: JAVA");
        break;
    case Constant.AUDIO_THREAD_TYPE_NATIVE:
        s.append(" Frames: " + playerBuffer);
        s.append(" Audio: NATIVE");
        break;
    }

    // mic source
    int micSource = getApp().getMicSource();
    String micSourceName = getApp().getMicSourceString(micSource);
    if (micSourceName != null) {
        s.append(String.format(" Mic: %s", micSourceName));
    }

    String info = getApp().getSystemInfo();
    s.append(" " + info);

    // show buffer test duration
    int bufferTestDuration = getApp().getBufferTestDuration();
    s.append("\nBuffer Test Duration: " + bufferTestDuration + "s");

    // show buffer test wave plot duration
    int bufferTestWavePlotDuration = getApp().getBufferTestWavePlotDuration();
    s.append("   Buffer Test Wave Plot Duration: last " + bufferTestWavePlotDuration + "s");

    mTextInfo.setText(s.toString());

    String estimatedLatency = "----";

    if (mCorrelation.mEstimatedLatencyMs > 0.0001) {
        estimatedLatency = String.format("%.2f ms", mCorrelation.mEstimatedLatencyMs);
    }

    mTextViewEstimatedLatency.setText(String.format("Latency: %s Confidence: %.2f", estimatedLatency,
            mCorrelation.mEstimatedLatencyConfidence));
}

From source file:github.daneren2005.dsub.util.Util.java

public static void abandonAudioFocus(Context context) {
    if (focusListener != null) {
        final AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        audioManager.abandonAudioFocus(focusListener);
        focusListener = null;/*from   w  w  w .  ja  v a2  s  .c om*/
    }
}

From source file:android.support.v7.app.AppCompatDelegateImplV7.java

private void onKeyUpPanel(int featureId, KeyEvent event) {
    if (mActionMode != null) {
        return;// w  w w. j  a v  a2 s . c om
    }

    boolean playSoundEffect = false;
    final PanelFeatureState st = getPanelState(featureId, true);
    if (featureId == FEATURE_OPTIONS_PANEL && mDecorContentParent != null
            && mDecorContentParent.canShowOverflowMenu()
            && !ViewConfigurationCompat.hasPermanentMenuKey(ViewConfiguration.get(mContext))) {
        if (!mDecorContentParent.isOverflowMenuShowing()) {
            if (!isDestroyed() && preparePanel(st, event)) {
                playSoundEffect = mDecorContentParent.showOverflowMenu();
            }
        } else {
            playSoundEffect = mDecorContentParent.hideOverflowMenu();
        }
    } else {
        if (st.isOpen || st.isHandled) {

            // Play the sound effect if the user closed an open menu (and not if
            // they just released a menu shortcut)
            playSoundEffect = st.isOpen;

            // Close menu
            closePanel(st, true);

        } else if (st.isPrepared) {
            boolean show = true;
            if (st.refreshMenuContent) {
                // Something may have invalidated the menu since we prepared it.
                // Re-prepare it to refresh.
                st.isPrepared = false;
                show = preparePanel(st, event);
            }

            if (show) {
                // Show menu
                openPanel(st, event);

                playSoundEffect = true;
            }
        }
    }

    if (playSoundEffect) {
        AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
        if (audioManager != null) {
            audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
        } else {
            Log.w(TAG, "Couldn't get audio manager");
        }
    }
}