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:io.radio.streamer.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Allow keys to change volume without playing
    setVolumeControlStream(AudioManager.STREAM_MUSIC);

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

    // Initialize Remote Controls if SDK Version >=14
    initializeRemoteControls();/*from   w w  w  .  jav a2  s.  com*/

    initializeVariables();
    initializeSideBar();

    updateApiData();

    // first page in the menu (homepage) on first load
    if (savedInstanceState == null) {
        selectItem(0);
    }

    // Get the fxView
    fxView = (FXView) findViewById(R.id.audioFxView);

    apiTimer = new Timer();
    apiTimer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            try {
                updateApiData();
            } catch (Exception e) {
                Log.e("api", "exception", e);
            }
        }
    }, 0, 10000);

    progressTimer = new Timer();
    progressTimer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            try {
                Message m = new Message();
                m.what = Util.PROGRESSUPDATE;

                mMessenger.send(m);

            } catch (Exception e) {
                Log.e("api", "exception", e);
            }
        }
    }, 0, 1000);
}

From source file:com.andreadec.musicplayer.MusicService.java

/**
 * Called when the service is created./*from   ww  w .  ja va  2 s. c o  m*/
 */
@Override
public void onCreate() {
    PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MusicServiceWakelock");

    // Initialize the telephony manager
    telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    phoneStateListener = new MusicPhoneStateListener();
    notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    // Initialize pending intents
    quitPendingIntent = PendingIntent.getBroadcast(this, 0, new Intent("com.andreadec.musicplayer.quit"), 0);
    previousPendingIntent = PendingIntent.getBroadcast(this, 0,
            new Intent("com.andreadec.musicplayer.previous"), 0);
    playpausePendingIntent = PendingIntent.getBroadcast(this, 0,
            new Intent("com.andreadec.musicplayer.playpause"), 0);
    nextPendingIntent = PendingIntent.getBroadcast(this, 0, new Intent("com.andreadec.musicplayer.next"), 0);
    pendingIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP),
            PendingIntent.FLAG_UPDATE_CURRENT);

    // Read saved user preferences
    preferences = PreferenceManager.getDefaultSharedPreferences(this);

    // Initialize the media player
    mediaPlayer = new MediaPlayer();
    mediaPlayer.setOnCompletionListener(this);
    mediaPlayer.setWakeMode(this, PowerManager.PARTIAL_WAKE_LOCK); // Enable the wake lock to keep CPU running when the screen is switched off

    shuffle = preferences.getBoolean(Constants.PREFERENCE_SHUFFLE, Constants.DEFAULT_SHUFFLE);
    repeat = preferences.getBoolean(Constants.PREFERENCE_REPEAT, Constants.DEFAULT_REPEAT);
    repeatAll = preferences.getBoolean(Constants.PREFERENCE_REPEATALL, Constants.DEFAULT_REPEATALL);
    try { // This may fail if the device doesn't support bass boost
        bassBoost = new BassBoost(1, mediaPlayer.getAudioSessionId());
        bassBoost.setEnabled(
                preferences.getBoolean(Constants.PREFERENCE_BASSBOOST, Constants.DEFAULT_BASSBOOST));
        setBassBoostStrength(preferences.getInt(Constants.PREFERENCE_BASSBOOSTSTRENGTH,
                Constants.DEFAULT_BASSBOOSTSTRENGTH));
        bassBoostAvailable = true;
    } catch (Exception e) {
        bassBoostAvailable = false;
    }
    try { // This may fail if the device doesn't support equalizer
        equalizer = new Equalizer(1, mediaPlayer.getAudioSessionId());
        equalizer.setEnabled(
                preferences.getBoolean(Constants.PREFERENCE_EQUALIZER, Constants.DEFAULT_EQUALIZER));
        setEqualizerPreset(
                preferences.getInt(Constants.PREFERENCE_EQUALIZERPRESET, Constants.DEFAULT_EQUALIZERPRESET));
        equalizerAvailable = true;
    } catch (Exception e) {
        equalizerAvailable = false;
    }
    random = new Random(System.nanoTime()); // Necessary for song shuffle

    shakeListener = new ShakeListener(this);
    if (preferences.getBoolean(Constants.PREFERENCE_SHAKEENABLED, Constants.DEFAULT_SHAKEENABLED)) {
        shakeListener.enable();
    }

    telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE); // Start listen for telephony events

    // Inizialize the audio manager
    audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    mediaButtonReceiverComponent = new ComponentName(getPackageName(), MediaButtonReceiver.class.getName());
    audioManager.registerMediaButtonEventReceiver(mediaButtonReceiverComponent);
    audioManager.requestAudioFocus(null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);

    // Initialize remote control client
    if (Build.VERSION.SDK_INT >= 14) {
        icon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
        Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
        mediaButtonIntent.setComponent(mediaButtonReceiverComponent);
        PendingIntent mediaPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0,
                mediaButtonIntent, 0);

        remoteControlClient = new RemoteControlClient(mediaPendingIntent);
        remoteControlClient.setTransportControlFlags(RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE
                | RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS | RemoteControlClient.FLAG_KEY_MEDIA_NEXT);
        audioManager.registerRemoteControlClient(remoteControlClient);
    }

    updateNotificationMessage();

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction("com.andreadec.musicplayer.quit");
    intentFilter.addAction("com.andreadec.musicplayer.previous");
    intentFilter.addAction("com.andreadec.musicplayer.previousNoRestart");
    intentFilter.addAction("com.andreadec.musicplayer.playpause");
    intentFilter.addAction("com.andreadec.musicplayer.next");
    intentFilter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
    broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals("com.andreadec.musicplayer.quit")) {
                sendBroadcast(new Intent("com.andreadec.musicplayer.quitactivity"));
                stopSelf();
                return;
            } else if (action.equals("com.andreadec.musicplayer.previous")) {
                previousItem(false);
            } else if (action.equals("com.andreadec.musicplayer.previousNoRestart")) {
                previousItem(true);
            } else if (action.equals("com.andreadec.musicplayer.playpause")) {
                playPause();
            } else if (action.equals("com.andreadec.musicplayer.next")) {
                nextItem();
            } else if (action.equals(AudioManager.ACTION_AUDIO_BECOMING_NOISY)) {
                if (preferences.getBoolean(Constants.PREFERENCE_STOPPLAYINGWHENHEADSETDISCONNECTED,
                        Constants.DEFAULT_STOPPLAYINGWHENHEADSETDISCONNECTED)) {
                    pause();
                }
            }
        }
    };
    registerReceiver(broadcastReceiver, intentFilter);

    if (!isPlaying()) {
        loadLastSong();
    }

    startForeground(Constants.NOTIFICATION_MAIN, notification);
}

From source file:org.hansel.myAlert.AlarmFragment.java

private void playSound(Context context, Uri alert) {
    mMediaPlayer = new MediaPlayer();
    try {/*from www  .  j  a  v  a 2s  .  co  m*/
        mMediaPlayer.setDataSource(context, alert);
        final AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
            mMediaPlayer.prepare();
            mMediaPlayer.start();
        }
    } catch (IOException e) {
        System.out.println("Error tocando alarma");
    }
}

From source file:it.interfree.leonardoce.bootreceiver.AlarmKlaxon.java

private void startAlarm(MediaPlayer player)
        throws java.io.IOException, IllegalArgumentException, IllegalStateException {
    final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

    // Non deve suonare se il cellulare e' silenzioso
    Log.v(LTAG, "Stato del telefono: " + audioManager.getRingerMode());

    // do not play alarms if stream volume is 0
    // (typically because ringer mode is silent).
    if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0
            && audioManager.getRingerMode() != AudioManager.RINGER_MODE_SILENT
            && audioManager.getRingerMode() != AudioManager.RINGER_MODE_VIBRATE) {
        player.setAudioStreamType(AudioManager.STREAM_ALARM);
        player.setLooping(true);//from   ww  w .  j a v a 2s.  c  o  m
        player.prepare();
        player.start();
    }
}

From source file:org.chromium.latency.walt.AudioFragment.java

@Override
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.button_start_audio:
        chartLayout.setVisibility(View.GONE);
        disableButtons();// w  w w  . j a  v a 2  s  . c  o m
        AudioTestType testType = getSelectedTestType();
        switch (testType) {
        case CONTINUOUS_PLAYBACK:
        case CONTINUOUS_RECORDING:
        case DISPLAY_WAVEFORM:
            audioTest.setAudioMode(AudioTest.AudioMode.CONTINUOUS);
            audioTest.setPeriod(AudioTest.CONTINUOUS_TEST_PERIOD);
            break;
        case COLD_PLAYBACK:
        case COLD_RECORDING:
            audioTest.setAudioMode(AudioTest.AudioMode.CONTINUOUS);
            audioTest.setPeriod(AudioTest.COLD_TEST_PERIOD);
            break;
        }
        if (testType == AudioTestType.DISPLAY_WAVEFORM) {
            // Only need to record 1 beep to display wave
            audioTest.setRecordingRepetitions(1);
        } else {
            audioTest.setRecordingRepetitions(
                    getIntPreference(getContext(), R.string.preference_audio_in_reps, 5));
        }
        if (testType == AudioTestType.CONTINUOUS_PLAYBACK || testType == AudioTestType.COLD_PLAYBACK
                || testType == AudioTestType.CONTINUOUS_RECORDING || testType == AudioTestType.COLD_RECORDING) {
            latencyChart.setVisibility(View.VISIBLE);
            latencyChart.clearData();
            latencyChart.setLegendEnabled(false);
            final String description = getResources().getStringArray(R.array.audio_mode_array)[modeSpinner
                    .getSelectedItemPosition()] + " [ms]";
            latencyChart.setDescription(description);
        }
        switch (testType) {
        case CONTINUOUS_RECORDING:
        case COLD_RECORDING:
        case DISPLAY_WAVEFORM:
            attemptRecordingTest();
            break;
        case CONTINUOUS_PLAYBACK:
        case COLD_PLAYBACK:
            // Set media volume to max
            AudioManager am = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
            am.setStreamVolume(AudioManager.STREAM_MUSIC, am.getStreamMaxVolume(AudioManager.STREAM_MUSIC), 0);
            audioTest.beginPlaybackMeasurement();
            break;
        }
        break;
    case R.id.button_stop_audio:
        audioTest.stopTest();
        break;
    case R.id.button_close_chart:
        chartLayout.setVisibility(View.GONE);
        break;
    }
}

From source file:uk.ac.ucl.excites.sapelli.shared.util.android.DeviceControl.java

/**
 * Increases the Media Volume/*from  w  w  w. j av  a  2 s .  co  m*/
 * 
 * @param context
 */
public static void increaseMediaVolume(Context context) {
    // Get the AudioManager
    final AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    // Set the volume
    audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, 0);
}

From source file:net.gcompris.GComprisActivity.java

public static boolean requestAudioFocus() {
    Context mContext = m_instance.getApplicationContext();
    AudioManager am = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);

    // Request audio focus for playback
    int result = am.requestAudioFocus(null,
            // Use the music stream.
            AudioManager.STREAM_MUSIC,/*from   w  ww  . j  a v a 2s  .  co  m*/
            // Request permanent focus.
            AudioManager.AUDIOFOCUS_GAIN);

    if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
        return true;
    }
    return false;
}

From source file:net.networksaremadeofstring.rhybudd.Notifications.java

public static void SendGCMNotification(ZenossEvent Event, Context context) {
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);

    Time now = new Time();
    now.setToNow();/*from  w  w w  . j  a  v  a  2 s. com*/

    //We don't need to overwhelm the user with their notification sound / vibrator
    if ((now.toMillis(true) - PreferenceManager.getDefaultSharedPreferences(context).getLong("lastCheck",
            now.toMillis(true))) < 3000) {
        //Log.e("SendGCMNotification", "Not publishing a notification due to stampede control");
        return;
    }

    Intent notificationIntent = new Intent(context, ViewZenossEventsListActivity.class);
    notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    notificationIntent.putExtra("forceRefresh", true);
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

    Uri soundURI = null;
    try {
        if (settings.getBoolean("notificationSound", true)) {
            if (settings.getString("notificationSoundChoice", "").equals("")) {
                soundURI = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            } else {
                try {
                    soundURI = Uri.parse(settings.getString("notificationSoundChoice", ""));
                } catch (Exception e) {
                    soundURI = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                }
            }
        } else {
            soundURI = null;
        }
    } catch (Exception e) {

    }

    String notifTitle = "New Events Received";
    int notifPriority = Notification.PRIORITY_DEFAULT;
    //int AlertType = NOTIFICATION_GCM_GENERIC;

    try {
        if (Event.getSeverity().equals("5")) {
            notifTitle = context.getString(R.string.CriticalNotificationTitle);
            notifPriority = Notification.PRIORITY_MAX;
            //AlertType = NOTIFICATION_GCM_CRITICAL;
        } else if (Event.getSeverity().equals("4")) {
            notifTitle = context.getString(R.string.ErrorNotificationTitle);
            notifPriority = Notification.PRIORITY_HIGH;
            //AlertType = NOTIFICATION_GCM_ERROR;
        } else if (Event.getSeverity().equals("3")) {
            notifTitle = context.getString(R.string.WarnNotificationTitle);
            notifPriority = Notification.PRIORITY_DEFAULT;
            //AlertType = NOTIFICATION_GCM_WARNING;
        } else if (Event.getSeverity().equals("2")) {
            notifTitle = context.getString(R.string.InfoNotificationTitle);
            notifPriority = Notification.PRIORITY_LOW;
            //AlertType = NOTIFICATION_GCM_INFO;
        } else if (Event.getSeverity().equals("1")) {
            notifTitle = context.getString(R.string.DebugNotificationTitle);
            notifPriority = Notification.PRIORITY_MIN;
            //AlertType = NOTIFICATION_GCM_DEBUG;
        }
    } catch (Exception e) {

    }

    long[] vibrate = { 0, 100, 200, 300 };

    try {
        AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);

        //Log.e("audio.getRingerMode()",Integer.toString(audio.getRingerMode()));
        switch (audio.getRingerMode()) {
        case AudioManager.RINGER_MODE_SILENT:
            //Do nothing to fix GitHub issue #13
            //Log.e("AudioManager","Doing nothing because we are silent");
            vibrate = new long[] { 0, 0 };
            break;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    Intent broadcastMassAck = new Intent();
    broadcastMassAck.setAction(MassAcknowledgeReceiver.BROADCAST_ACTION);
    PendingIntent pBroadcastMassAck = PendingIntent.getBroadcast(context, 0, broadcastMassAck, 0);

    if (Build.VERSION.SDK_INT >= 16) {
        Notification noti = new Notification.BigTextStyle(new Notification.Builder(context)
                .setContentTitle(notifTitle).setPriority(notifPriority).setAutoCancel(true).setSound(soundURI)
                .setVibrate(vibrate).setContentText(Event.getDevice()).setContentIntent(contentIntent)
                .addAction(R.drawable.ic_action_resolve_all, "Acknowledge all Events", pBroadcastMassAck)
                .setSmallIcon(R.drawable.ic_stat_alert)).bigText(
                        Event.getSummary() + "\r\n" + Event.getComponentText() + "\r\n" + Event.geteventClass())
                        .build();

        if (settings.getBoolean("notificationSoundInsistent", false))
            noti.flags |= Notification.FLAG_INSISTENT;

        noti.tickerText = notifTitle;

        NotificationManager mNM = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        mNM.notify(NOTIFICATION_GCM_GENERIC, noti);
    } else {
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
                .setSmallIcon(R.drawable.ic_stat_alert).setContentTitle(notifTitle)
                .setContentText(Event.getDevice() + ": " + Event.getSummary()).setContentIntent(contentIntent)
                .setSound(soundURI).setVibrate(vibrate)
                .addAction(R.drawable.ic_action_resolve_all, "Acknowledge all Events", pBroadcastMassAck)
                .setAutoCancel(true).setPriority(notifPriority);

        NotificationManager mNM = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        mNM.notify(NOTIFICATION_GCM_GENERIC, mBuilder.build());
    }
}

From source file:com.apps.howard.vicissitude.services.NotificationService.java

private void maybeOverrideVolumeBeforeNotify() {

    boolean settingsOverrideVolumeEnabled = prefs.getBoolean(this.getString(R.string.pref_override_volume_key),
            false);//  w w w . j a  va 2 s . com
    int settingsOverrideVolume = prefs.getInt(this.getString(R.string.pref_alert_volume_key), 1);

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

    if (settingsOverrideVolumeEnabled) {
        audioManager.setStreamVolume(AudioManager.STREAM_ALARM, settingsOverrideVolume, 0);
    }
}

From source file:com.imagine.BaseActivity.java

AudioManager audioManager() {
    return (AudioManager) getSystemService(Context.AUDIO_SERVICE);
}