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:fr.inria.ucn.collectors.SysStateCollector.java

@SuppressWarnings("deprecation")
private JSONObject getAudioState(Context c) throws JSONException {
    AudioManager am = (AudioManager) c.getSystemService(Context.AUDIO_SERVICE);

    JSONObject data = new JSONObject();

    data.put("is_bluetooth_a2dp_on", am.isBluetoothA2dpOn());
    data.put("is_microphone_mute", am.isMicrophoneMute());
    data.put("is_music_active", am.isMusicActive());
    data.put("is_speaker_phone_on", am.isSpeakerphoneOn());
    data.put("is_wired_headset_on", am.isWiredHeadsetOn());

    switch (am.getMode()) {
    case AudioManager.MODE_IN_CALL:
        data.put("mode", "in_call");
        break;//from  w ww . j  a v  a 2  s.  c o  m
    case AudioManager.MODE_IN_COMMUNICATION:
        data.put("mode", "in_comm");
        break;
    case AudioManager.MODE_NORMAL:
        data.put("mode", "normal");
        break;
    case AudioManager.MODE_RINGTONE:
        data.put("mode", "ringtone");
        break;
    case AudioManager.MODE_INVALID:
    default:
        data.put("mode", "invalid");
        break;
    }

    switch (am.getRingerMode()) {
    case AudioManager.RINGER_MODE_VIBRATE:
        data.put("ringer_mode", "vibrate");
        break;
    case AudioManager.RINGER_MODE_SILENT:
        data.put("ringer_mode", "silent");
        break;
    case AudioManager.RINGER_MODE_NORMAL:
        data.put("ringer_mode", "normal");
        break;
    default:
        data.put("ringer_mode", "invalid");
        break;
    }
    return data;
}

From source file:org.noise_planet.noisecapture.MeasurementService.java

@Override
public void onDestroy() {
    // Hide notification
    mNM.cancel(NOTIFICATION);/*from  ww w  .  ja  va2 s.c o  m*/
    // Stop record
    if (isRecording()) {
        cancel();
    }
    try {
        AudioManager mgr = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        mgr.setStreamMute(AudioManager.STREAM_SYSTEM, false);
    } catch (SecurityException ex) {
        // Ignore
    }
}

From source file:net.geniecode.ttr.ScheduleReceiver.java

@SuppressWarnings("deprecation")
@SuppressLint({ "Recycle", "NewApi", "InlinedApi" })
@Override/* ww w  .  j a  v a 2s  .c o m*/
public void onReceive(Context context, Intent intent) {
    if (!Schedules.SCHEDULE_ACTION.equals(intent.getAction())) {
        // Unknown intent, bail.
        return;
    }

    Schedule schedule = null;
    // Grab the schedule from the intent. Since the remote AlarmManagerService
    // fills in the Intent to add some extra data, it must unparcel the
    // Schedule object. It throws a ClassNotFoundException when unparcelling.
    // To avoid this, do the marshalling ourselves.
    final byte[] data = intent.getByteArrayExtra(Schedules.SCHEDULE_RAW_DATA);
    if (data != null) {
        Parcel in = Parcel.obtain();
        in.unmarshall(data, 0, data.length);
        in.setDataPosition(0);
        schedule = Schedule.CREATOR.createFromParcel(in);
    }

    if (schedule == null) {
        // Make sure we set the next schedule if needed.
        Schedules.setNextSchedule(context);
        return;
    }

    // Disable this schedule if it does not repeat.
    if (!schedule.daysOfWeek.isRepeatSet()) {
        Schedules.enableSchedule(context, schedule.id, false);
    } else {
        // Enable the next schedule if there is one. The above call to
        // enableSchedule will call setNextSchedule so avoid calling it twice.
        Schedules.setNextSchedule(context);
    }

    long now = System.currentTimeMillis();

    if (now > schedule.time + STALE_WINDOW) {
        return;
    }

    // Get telephony service
    mTelephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

    // Execute only for devices with versions of Android less than 4.2
    if (android.os.Build.VERSION.SDK_INT < 17) {
        // Get flight mode state
        boolean isEnabled = Settings.System.getInt(context.getContentResolver(),
                Settings.System.AIRPLANE_MODE_ON, 0) == 1;

        // Get Wi-Fi service
        mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

        if ((schedule.aponoff) && (!isEnabled) && (schedule.mode.equals("1"))
                && (mTelephonyManager.getCallState() == TelephonyManager.CALL_STATE_IDLE)) {
            // Enable flight mode
            Settings.System.putInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON,
                    isEnabled ? 0 : 1);

            // Get Wi-Fi state and disable that one too, just in case
            // (On some devices it doesn't get disabled when the flight mode is
            // turned on, so we do it here)
            boolean isWifiEnabled = mWifiManager.isWifiEnabled();

            SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);

            if (isWifiEnabled) {
                SharedPreferences.Editor editor = settings.edit();
                editor.putBoolean(WIFI_STATE, isWifiEnabled);
                editor.commit();
                mWifiManager.setWifiEnabled(false);
            } else {
                SharedPreferences.Editor editor = settings.edit();
                editor.putBoolean(WIFI_STATE, isWifiEnabled);
                editor.commit();
            }

            // Post an intent to reload
            Intent relintent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
            relintent.putExtra("state", !isEnabled);
            context.sendBroadcast(relintent);
        } else if ((!schedule.aponoff) && (isEnabled) && (schedule.mode.equals("1"))) {
            // Disable flight mode
            Settings.System.putInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON,
                    isEnabled ? 0 : 1);

            // Restore previously remembered Wi-Fi state
            SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
            Boolean WiFiState = settings.getBoolean(WIFI_STATE, true);

            if (WiFiState) {
                mWifiManager.setWifiEnabled(true);
            }

            // Post an intent to reload
            Intent relintent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
            relintent.putExtra("state", !isEnabled);
            context.sendBroadcast(relintent);
        }
        // Check whether there are ongoing phone calls, and if so
        // show notification instead of just enabling the flight mode
        else if ((schedule.aponoff) && (!isEnabled) && (schedule.mode.equals("1"))
                && (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE)) {
            setNotification(context);
        }
        // Execute for devices with Android 4.2   or higher
    } else {
        // Get flight mode state
        String result = Settings.Global.getString(context.getContentResolver(),
                Settings.Global.AIRPLANE_MODE_ON);

        if ((schedule.aponoff) && (result.equals("0")) && (schedule.mode.equals("1"))
                && (mTelephonyManager.getCallState() == TelephonyManager.CALL_STATE_IDLE)) {
            // Keep the device awake while enabling flight mode
            Intent service = new Intent(context, ScheduleIntentService.class);
            startWakefulService(context, service);
        } else if ((!schedule.aponoff) && (result.equals("1")) && (schedule.mode.equals("1"))) {
            // Keep the device awake while enabling flight mode
            Intent service = new Intent(context, ScheduleIntentService.class);
            startWakefulService(context, service);
        } else if ((schedule.aponoff) && (result.equals("0")) && (schedule.mode.equals("1"))
                && (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE)) {
            setNotification(context);
        }
    }

    // Get audio service
    mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);

    // Get current ringer mode and set silent or normal mode accordingly
    switch (mAudioManager.getRingerMode()) {
    case AudioManager.RINGER_MODE_SILENT:
        if ((!schedule.silentonoff) && (schedule.mode.equals("2"))) {
            mAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
        }
        break;
    case AudioManager.RINGER_MODE_NORMAL:
        if ((schedule.silentonoff) && (schedule.mode.equals("2"))) {
            mAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
        }
        break;
    case AudioManager.RINGER_MODE_VIBRATE:
        // If the phone is set to vibrate let's make it completely silent
        if ((schedule.silentonoff) && (schedule.mode.equals("2"))) {
            mAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
        }
        // or restore the regular sounds on it if that's scheduled
        else if ((!schedule.silentonoff) && (schedule.mode.equals("2"))) {
            mAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
        }
        break;
    }
}

From source file:com.mylovemhz.simplay.MusicService.java

private void cueTrack() throws IOException, IndexOutOfBoundsException {
    Log.d(TAG_MUSIC_SERVICE, "Cue Track...");

    AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    int result = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
    if (result != AudioManager.AUDIOFOCUS_GAIN) {
        return; //Failed to gain audio focus
    }//w  w w . j a  v a2 s  . c  o  m

    if (getCurrentState() == State.STOPPED) {
        mediaPlayer.reset();
        currentState = State.IDLE;

    }
    if (getCurrentState() == State.IDLE) {
        if (trackQueue.size() == 0) {
            return; //nothing to play
        }
        if (hasPermission(Manifest.permission.WAKE_LOCK)) {
            if (!wifiLock.isHeld()) {
                wifiLock.acquire();
            }
            Track track = trackQueue.get(currentTrackIndex);
            mediaPlayer.setDataSource(track.getUrl());
            currentState = State.INITIALIZED;
            mediaPlayer.prepareAsync();
            currentState = State.PREPARING;
            if (callbacks != null)
                callbacks.onLoading();
        } else {
            Log.e(TAG_MUSIC_SERVICE, "need permission " + Manifest.permission.WAKE_LOCK);
            if (callbacks != null) {
                callbacks.onPermissionRequired(REQUEST_PERMISSION_WAKE_LOCK, Manifest.permission.WAKE_LOCK,
                        RATIONALE_WAKE_LOCK);
            }
        }
    }
}

From source file:com.andryr.musicplayer.PlaybackService.java

@Override
public void onCreate() {
    super.onCreate();
    mStatePrefs = getSharedPreferences(STATE_PREFS_NAME, MODE_PRIVATE);

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

    mMediaPlayer = new MediaPlayer();
    mMediaPlayer.setOnCompletionListener(this);
    mMediaPlayer.setOnErrorListener(this);
    mMediaPlayer.setOnPreparedListener(this);
    mMediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
    mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

    Intent i = new Intent(this, AudioEffectsReceiver.class);
    i.setAction(AudioEffectsReceiver.ACTION_OPEN_AUDIO_EFFECT_SESSION);
    i.putExtra(AudioEffectsReceiver.EXTRA_AUDIO_SESSION_ID, mMediaPlayer.getAudioSessionId());
    sendBroadcast(i);//from   w w  w .  j a  v  a2  s .c o m

    IntentFilter receiverFilter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
    registerReceiver(mHeadsetStateReceiver, receiverFilter);

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    mAutoPause = prefs.getBoolean(PREF_AUTO_PAUSE, false);

    initTelephony();

    restoreState();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        setupMediaSession();
    }

}

From source file:teamb.minicap.phaze.BackgroundService.java

@Override
public void onCreate() {
    super.onCreate();
    // First, we initialize the Hub singleton with an application identifier.
    hub = Hub.getInstance();//w ww  . j a v  a2 s  .  c om
    if (!hub.init(this, getPackageName())) {
        showToast("Couldn't initialize Hub");
        stopSelf();
        return;
    }
    // Disable standard Myo locking policy. All poses will be delivered.
    hub.setLockingPolicy(Hub.LockingPolicy.NONE);
    // Next, register for DeviceListener callbacks.
    hub.addListener(mListener);
    volume = false;
    audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
}

From source file:de.tubs.ibr.dtn.dtalkie.service.TalkieService.java

@Override
public void onCreate() {
    // call onCreate of the super-class
    super.onCreate();

    mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    // get the audio-manager
    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    prefs.registerOnSharedPreferenceChangeListener(mPrefListener);

    // create message database
    mDatabase = new MessageDatabase(this);

    // init sound pool
    mSoundManager = new SoundFXManager(AudioManager.STREAM_VOICE_CALL, 2);

    mSoundManager.load(this, Sound.BEEP);
    mSoundManager.load(this, Sound.CONFIRM);
    mSoundManager.load(this, Sound.QUIT);
    mSoundManager.load(this, Sound.RING);
    mSoundManager.load(this, Sound.SQUELSH_LONG);
    mSoundManager.load(this, Sound.SQUELSH_SHORT);

    // create a player
    mPlayer = new MediaPlayer();
    mPlayer.setOnCompletionListener(mCompletionListener);
    mPlayer.setOnPreparedListener(mPrepareListener);

    // create registration
    Registration reg = new Registration("dtalkie");
    reg.add(RecorderService.TALKIE_GROUP_EID);

    // register own data handler for incoming bundles
    mClient = new DTNClient(_session_listener);

    try {//from w w w .  j a  v a 2s  . c om
        mClient.initialize(this, reg);
        mServiceError = ServiceError.NO_ERROR;
    } catch (ServiceNotAvailableException e) {
        mServiceError = ServiceError.SERVICE_NOT_FOUND;
    } catch (SecurityException ex) {
        mServiceError = ServiceError.PERMISSION_NOT_GRANTED;
    }

    Log.d(TAG, "Service created.");

    if (prefs.getBoolean("autoplay", false) || HeadsetService.ENABLED) {
        Intent play_i = new Intent(TalkieService.this, TalkieService.class);
        play_i.setAction(TalkieService.ACTION_PLAY_NEXT);
        startService(play_i);
    }
}

From source file:com.phonegap.AudioHandler.java

/**
 * Get the audio device to be used for playback.
 * /*from  w  w w. j  a v a 2  s.  c  o  m*/
 * @return               1=earpiece, 2=speaker
 */
public int getAudioOutputDevice() {
    AudioManager audiMgr = (AudioManager) this.ctx.getSystemService(Context.AUDIO_SERVICE);
    if (audiMgr.getRouting(AudioManager.MODE_NORMAL) == AudioManager.ROUTE_EARPIECE) {
        return 1;
    } else if (audiMgr.getRouting(AudioManager.MODE_NORMAL) == AudioManager.ROUTE_SPEAKER) {
        return 2;
    } else {
        return -1;
    }
}

From source file:com.google.fpl.gim.examplegame.MainService.java

@Override
public void onCreate() {
    // The service is being created.
    Utils.logDebug(TAG, "onCreate");
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(CHOICE_NOTIFICATION_ACTION_1);
    intentFilter.addAction(CHOICE_NOTIFICATION_ACTION_2);
    intentFilter.addAction(CHOICE_NOTIFICATION_ACTION_3);
    registerReceiver(mReceiver, intentFilter);

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

    // Determines the behavior for handling Audio Focus surrender.
    mAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
        @Override//from w  w  w  . j  av  a 2 s  .com
        public void onAudioFocusChange(int focusChange) {
            if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT
                    || focusChange == AudioManager.AUDIOFOCUS_LOSS) {

                if (mTextToSpeech.isSpeaking()) {
                    mTextToSpeech.setOnUtteranceProgressListener(null);
                    mTextToSpeech.stop();
                }

                if (mMediaPlayer.isPlaying()) {
                    mMediaPlayer.stop();
                }

                // Abandon Audio Focus, if it's requested elsewhere.
                mAudioManager.abandonAudioFocus(mAudioFocusChangeListener);

                // Restart the current moment if AudioFocus was lost. Since AudioFocus is only
                // requested away from this application if this application was using it,
                // only Moments that play sound will restart in this way.
                if (mMission != null) {
                    mMission.restartMoment();
                }
            }
        }
    };

    // Asynchronously prepares the TextToSpeech.
    mTextToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
        @Override
        public void onInit(int status) {
            if (status == TextToSpeech.SUCCESS) {
                // Check if language is available.
                switch (mTextToSpeech.isLanguageAvailable(DEFAULT_TEXT_TO_SPEECH_LOCALE)) {
                case TextToSpeech.LANG_AVAILABLE:
                case TextToSpeech.LANG_COUNTRY_AVAILABLE:
                case TextToSpeech.LANG_COUNTRY_VAR_AVAILABLE:
                    Utils.logDebug(TAG, "TTS locale supported.");
                    mTextToSpeech.setLanguage(DEFAULT_TEXT_TO_SPEECH_LOCALE);
                    mIsTextToSpeechReady = true;
                    break;
                case TextToSpeech.LANG_MISSING_DATA:
                    Utils.logDebug(TAG, "TTS missing data, ask for install.");
                    Intent installIntent = new Intent();
                    installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
                    startActivity(installIntent);
                    break;
                default:
                    Utils.logDebug(TAG, "TTS local not supported.");
                    break;
                }
            }
        }
    });

    mMediaPlayer = new MediaPlayer();
}

From source file:net.micode.soundrecorder.RecorderService.java

private void localStartRecording(int outputfileformat, String path, boolean highQuality, long maxFileSize) {
    if (mRecorder == null) {
        mRemainingTimeCalculator.reset();
        if (maxFileSize != -1) {
            mRemainingTimeCalculator.setFileSizeLimit(new File(path), maxFileSize);
        }//from   w w w. java 2  s . c om

        mRecorder = new MediaRecorder();
        mRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);

        if (outputfileformat == MediaRecorder.OutputFormat.THREE_GPP) {
            mRemainingTimeCalculator.setBitRate(SoundRecorder.BITRATE_3GPP);
            //
            mRecorder.setAudioChannels(1);
            mRecorder.setAudioSamplingRate(mAudioSampleRate);
            mRecorder.setAudioEncodingBitRate(SoundRecorder.BITRATE_3GPP);
            mRecorder.setOutputFormat(outputfileformat);
            mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
        } else if (outputfileformat == MediaRecorder.OutputFormat.AMR_NB) {
            mRemainingTimeCalculator.setBitRate(SoundRecorder.BITRATE_AMR);
            mRecorder.setAudioSamplingRate(highQuality ? 16000 : 8000);

            mRecorder.setOutputFormat(outputfileformat);
            mRecorder.setAudioEncoder(
                    highQuality ? MediaRecorder.AudioEncoder.AMR_WB : MediaRecorder.AudioEncoder.AMR_NB);
        } else {
            mRemainingTimeCalculator.setBitRate(SoundRecorder.BITRATE_MP3);
            //
            mRecorder.setAudioChannels(1);
            mRecorder.setAudioSamplingRate(mAudioSampleRate);
            mRecorder.setAudioEncodingBitRate(SoundRecorder.BITRATE_MP3);
            mRecorder.setOutputFormat(outputfileformat);
            mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
        }

        mRecorder.setOutputFile(path);
        mRecorder.setOnErrorListener(this);

        // Handle IOException
        try {
            mRecorder.prepare();
        } catch (IOException exception) {
            sendErrorBroadcast(Recorder.INTERNAL_ERROR);
            mRecorder.reset();
            mRecorder.release();
            mRecorder = null;
            return;
        }
        // Handle RuntimeException if the recording couldn't start
        try {
            mRecorder.start();
        } catch (RuntimeException exception) {
            AudioManager audioMngr = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
            boolean isInCall = (audioMngr.getMode() == AudioManager.MODE_IN_CALL);
            if (isInCall) {
                sendErrorBroadcast(Recorder.IN_CALL_RECORD_ERROR);
            } else {
                sendErrorBroadcast(Recorder.INTERNAL_ERROR);
            }
            mRecorder.reset();
            mRecorder.release();
            mRecorder = null;
            return;
        }
        mFilePath = path;
        mStartTime = System.currentTimeMillis();
        mWakeLock.acquire();
        mNeedUpdateRemainingTime = false;
        sendStateBroadcast();
        showRecordingNotification();
        NotificationManager nMgr = (NotificationManager) getApplicationContext()
                .getSystemService(NOTIFICATION_SERVICE);
        nMgr.cancel(notifyID);
    }
}