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:com.sean.takeastand.alarmprocess.AlarmService.java

private void sendNotification() {
    NotificationManager notificationManager = (NotificationManager) this
            .getSystemService(Context.NOTIFICATION_SERVICE);
    PendingIntent[] pendingIntents = makeNotificationIntents();
    RemoteViews rvRibbon = new RemoteViews(getPackageName(), R.layout.stand_notification);
    rvRibbon.setOnClickPendingIntent(R.id.btnStood, pendingIntents[1]);
    notificationClockTime = Utils.getFormattedCalendarTime(Calendar.getInstance(), this);
    rvRibbon.setTextViewText(R.id.notificationTimeStamp, notificationClockTime);
    NotificationCompat.Builder alarmNotificationBuilder = new NotificationCompat.Builder(this);
    alarmNotificationBuilder.setContent(rvRibbon).setContentIntent(pendingIntents[0]).setAutoCancel(false)
            .setTicker(getString(R.string.stand_up_time_low)).setSmallIcon(R.drawable.ic_notification_small)
            .setContentTitle("Take A Stand ").setContentText(
                    "Mark Stood")
            .extend(new NotificationCompat.WearableExtender().addAction(
                    new NotificationCompat.Action.Builder(R.drawable.ic_action_done, "Stood", pendingIntents[2])
                            .build())/*from www  .j a v  a 2  s  . co  m*/
                    .setContentAction(0).setHintHideIcon(true)
    //                    .setBackground(BitmapFactory.decodeResource(getResources(), R.drawable.alarm_schedule_passed))
    );

    //Purpose of below is to figure out what type of user alert to give with the notification
    //If scheduled, check settings for that schedule
    //If unscheduled, check user defaults
    if (mCurrentAlarmSchedule != null) {
        boolean[] alertType = mCurrentAlarmSchedule.getAlertType();
        if ((alertType[0])) {
            alarmNotificationBuilder.setLights(238154000, 1000, 4000);
        }
        if (alertType[1]) {
            alarmNotificationBuilder.setVibrate(mVibrationPattern);
            AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
            if (audioManager.getMode() == AudioManager.RINGER_MODE_SILENT && Utils.getVibrateOverride(this)) {
                Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                v.vibrate(mVibrationPattern, -1);
            }
        }
        if (alertType[2]) {
            Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            alarmNotificationBuilder.setSound(soundUri);
        }
    } else {
        boolean[] alertType = Utils.getDefaultAlertType(this);
        if ((alertType[0])) {
            alarmNotificationBuilder.setLights(238154000, 1000, 4000);
        }
        if (alertType[1]) {
            alarmNotificationBuilder.setVibrate(mVibrationPattern);
            AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
            if (audioManager.getMode() == AudioManager.RINGER_MODE_SILENT && Utils.getVibrateOverride(this)) {
                Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                v.vibrate(mVibrationPattern, -1);
            }
        }
        if (alertType[2]) {
            Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            alarmNotificationBuilder.setSound(soundUri);
        }
    }
    Notification alarmNotification = alarmNotificationBuilder.build();
    notificationManager.notify(R.integer.AlarmNotificationID, alarmNotification);

    if (getSharedPreferences(Constants.USER_SHARED_PREFERENCES, 0).getBoolean(Constants.STANDDTECTORTM_ENABLED,
            false)) {
        Intent standSensorIntent = new Intent(this, StandDtectorTM.class);
        standSensorIntent.setAction(com.heckbot.standdtector.Constants.STANDDTECTOR_START);
        standSensorIntent.putExtra("MILLISECONDS", (long) 60000);

        standSensorIntent.putExtra("pendingIntent", pendingIntents[1]);

        startService(standSensorIntent);
    }
}

From source file:org.wso2.mdm.agent.services.Operation.java

/**
 * Mute the device.//ww  w  .j a  va  2s.  co  m
 * @param code        - Operation code.
 * @param requestMode - Request mode(Normal mode or policy bundle mode).
 */
private void muteDevice(String code) {
    resultBuilder.build(code);

    AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    audioManager.setStreamVolume(AudioManager.STREAM_RING, DEFAULT_VOLUME, DEFAULT_FLAG);
}

From source file:net.sourceforge.servestream.service.MediaPlaybackService.java

@Override
public void onCreate() {
    super.onCreate();

    int imageThumbSize = getResources().getDimensionPixelSize(R.dimen.image_notification_size);

    ImageCache.ImageCacheParams cacheParams = new ImageCache.ImageCacheParams(this,
            NOTIFICATION_IMAGE_CACHE_DIR);

    cacheParams.setMemCacheSizePercent(0.25f); // Set memory cache to 25% of app memory

    mNotificationImageFetcher = new DatabaseImageResizer(this, imageThumbSize);
    mNotificationImageFetcher.addImageCache(cacheParams);

    cacheParams = new ImageCache.ImageCacheParams(this, LOCK_SCREEN_IMAGE_CACHE_DIR);

    cacheParams.setMemCacheSizePercent(0.25f); // Set memory cache to 25% of app memory

    mLockScreenImageFetcher = new DatabaseImageResizer(this, 600);
    mLockScreenImageFetcher.addImageCache(cacheParams);

    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    mMediaButtonReceiverComponent = new ComponentName(this, MediaButtonIntentReceiver.class);
    mAudioManager.registerMediaButtonEventReceiver(mMediaButtonReceiverComponent);

    // Use the remote control APIs (if available) to set the playback state
    if (mRemoteControlClientCompat == null) {
        Intent intent = new Intent(Intent.ACTION_MEDIA_BUTTON);
        intent.setComponent(mMediaButtonReceiverComponent);
        mRemoteControlClientCompat = new RemoteControlClientCompat(PendingIntent.getBroadcast(this /*context*/,
                0 /*requestCode, ignored*/, intent /*intent*/, 0 /*flags*/));
        RemoteControlHelper.registerRemoteControlClient(mAudioManager, mRemoteControlClientCompat);
    }//from   w w  w .j a va 2  s.  com

    mRemoteControlClientCompat.setTransportControlFlags(RemoteControlClientCompat.FLAG_KEY_MEDIA_PREVIOUS
            | RemoteControlClientCompat.FLAG_KEY_MEDIA_PLAY | RemoteControlClientCompat.FLAG_KEY_MEDIA_PAUSE
            | RemoteControlClientCompat.FLAG_KEY_MEDIA_NEXT | RemoteControlClientCompat.FLAG_KEY_MEDIA_STOP);

    mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    mPreferences.registerOnSharedPreferenceChangeListener(this);

    final boolean lockingWifi = mPreferences.getBoolean(PreferenceConstants.WIFI_LOCK, true);
    mConnectivityManager = new ConnectivityReceiver(this, lockingWifi);

    mRetrieveShoutCastMetadata = mPreferences.getBoolean(PreferenceConstants.RETRIEVE_SHOUTCAST_METADATA,
            false);

    mMediaButtonReceiverComponent = new ComponentName(this, MediaButtonIntentReceiver.class);

    mCardId = MusicUtils.getCardId(this);

    registerExternalStorageListener();

    // Needs to be done in this thread, since otherwise ApplicationContext.getPowerManager() crashes.
    mPlayer = new MultiPlayer(this);
    mPlayer.setHandler(mMediaplayerHandler);

    reloadQueue();
    notifyChange(QUEUE_CHANGED);
    notifyChange(META_CHANGED);

    IntentFilter commandFilter = new IntentFilter();
    commandFilter.addAction(SERVICECMD);
    commandFilter.addAction(TOGGLEPAUSE_ACTION);
    commandFilter.addAction(PAUSE_ACTION);
    commandFilter.addAction(NEXT_ACTION);
    commandFilter.addAction(PREVIOUS_ACTION);
    registerReceiver(mIntentReceiver, commandFilter);

    // If the service was idle, but got killed before it stopped itself, the
    // system will relaunch it. Make sure it gets stopped again in that case.
    Message msg = mDelayedStopHandler.obtainMessage();
    mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
}

From source file:com.fastbootmobile.encore.service.PlaybackService.java

/**
 * Release the audio focus and unregisters the media controls
 *//* w  w w  . j a  va2s  .  com*/
private synchronized void abandonAudioFocus() {
    if (mHasAudioFocus) {
        // Release the audio focus
        final AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        am.abandonAudioFocus(this);
        unregisterReceiver(mAudioNoisyReceiver);

        // Release our CPU wakelock
        mWakeLock.release();

        // Notify the remote metadata that we're getting down
        mRemoteMetadata.setActive(false);

        mHasAudioFocus = false;
    }
}

From source file:org.mariotaku.harmony.MusicPlaybackService.java

@Override
public void onCreate() {
    super.onCreate();
    // Needs to be done in this thread, since otherwise
    // ApplicationContext.getPowerManager() crashes.
    mResources = getResources();/*from  w w  w.j av  a2 s.c om*/
    mPlayer = new MultiPlayer(this);
    mResolver = getContentResolver();
    mPlayer.setHandler(mMediaplayerHandler);

    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

    mAudioManager.registerMediaButtonEventReceiver(
            new ComponentName(getPackageName(), MediaButtonIntentReceiver.class.getName()));

    mPreferences = new PreferencesEditor(this);

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

    mCardId = MusicUtils.getCardId(this);

    registerExternalStorageListener();
    registerA2dpServiceListener();

    reloadQueue();

    IntentFilter commandFilter = new IntentFilter();
    commandFilter.addAction(SERVICECMD);
    commandFilter.addAction(TOGGLEPAUSE_ACTION);
    commandFilter.addAction(PAUSE_ACTION);
    commandFilter.addAction(NEXT_ACTION);
    commandFilter.addAction(PREVIOUS_ACTION);
    commandFilter.addAction(CYCLEREPEAT_ACTION);
    commandFilter.addAction(TOGGLESHUFFLE_ACTION);
    commandFilter.addAction(BROADCAST_PLAYSTATUS_REQUEST);
    registerReceiver(mIntentReceiver, commandFilter);

    registerReceiver(mExternalAudioDeviceStatusReceiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG));

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this.getClass().getName());
    mWakeLock.setReferenceCounted(false);

    // If the service was idle, but got killed before it stopped itself, the
    // system will relaunch it. Make sure it gets stopped again in that
    // case.
    Message msg = mDelayedStopHandler.obtainMessage();
    mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
}

From source file:com.ruesga.timelinechart.TimelineChartView.java

private void init(Context ctx, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    mUiHandler = new Handler(Looper.getMainLooper(), mMessenger);
    if (!isInEditMode()) {
        mAudioManager = (AudioManager) ctx.getSystemService(Context.AUDIO_SERVICE);
    }/*from   w  w w  .j  a v  a2  s  .  c  o  m*/

    final Resources res = getResources();
    final Resources.Theme theme = ctx.getTheme();

    mTickFormats = getResources().getStringArray(R.array.tlcDefTickLabelFormats);
    mTickLabels = getResources().getStringArray(R.array.tlcDefTickLabelValues);

    final DisplayMetrics dp = getResources().getDisplayMetrics();
    mSize8 = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 8, dp);
    mSize12 = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 12, dp);
    mSize20 = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 20, dp);

    final ViewConfiguration vc = ViewConfiguration.get(ctx);
    mLongPressTimeout = ViewConfiguration.getLongPressTimeout();
    mTouchSlop = vc.getScaledTouchSlop() / 2;
    mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity();
    mScroller = new OverScroller(ctx);

    int graphBgColor = ContextCompat.getColor(ctx, R.color.tlcDefGraphBackgroundColor);
    int footerBgColor = ContextCompat.getColor(ctx, R.color.tlcDefFooterBackgroundColor);

    mDefFooterBarHeight = mFooterBarHeight = res.getDimension(R.dimen.tlcDefFooterBarHeight);
    mShowFooter = res.getBoolean(R.bool.tlcDefShowFooter);
    mGraphMode = res.getInteger(R.integer.tlcDefGraphMode);
    mPlaySelectionSoundEffect = res.getBoolean(R.bool.tlcDefPlaySelectionSoundEffect);
    mSelectionSoundEffectSource = res.getInteger(R.integer.tlcDefSelectionSoundEffectSource);
    mAnimateCursorTransition = res.getBoolean(R.bool.tlcDefAnimateCursorTransition);
    mFollowCursorPosition = res.getBoolean(R.bool.tlcDefFollowCursorPosition);
    mAlwaysEnsureSelection = res.getBoolean(R.bool.tlcDefAlwaysEnsureSelection);

    mGraphAreaBgPaint = new Paint();
    mGraphAreaBgPaint.setColor(graphBgColor);
    mFooterAreaBgPaint = new Paint();
    mFooterAreaBgPaint.setColor(footerBgColor);
    mTickLabelFgPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.LINEAR_TEXT_FLAG);
    mTickLabelFgPaint.setFakeBoldText(true);
    mTickLabelFgPaint.setColor(MaterialPaletteHelper.isDarkColor(footerBgColor) ? Color.LTGRAY : Color.DKGRAY);

    mBarItemWidth = res.getDimension(R.dimen.tlcDefBarItemWidth);
    mBarItemSpace = res.getDimension(R.dimen.tlcDefBarItemSpace);

    TypedArray a = theme.obtainStyledAttributes(attrs, R.styleable.tlcTimelineChartView, defStyleAttr,
            defStyleRes);
    try {
        int n = a.getIndexCount();
        for (int i = 0; i < n; i++) {
            int attr = a.getIndex(i);
            if (attr == R.styleable.tlcTimelineChartView_tlcGraphBackground) {
                graphBgColor = a.getColor(attr, graphBgColor);
                mGraphAreaBgPaint.setColor(graphBgColor);
            } else if (attr == R.styleable.tlcTimelineChartView_tlcShowFooter) {
                mShowFooter = a.getBoolean(attr, mShowFooter);
            } else if (attr == R.styleable.tlcTimelineChartView_tlcFooterBackground) {
                footerBgColor = a.getColor(attr, footerBgColor);
                mFooterAreaBgPaint.setColor(footerBgColor);
            } else if (attr == R.styleable.tlcTimelineChartView_tlcFooterBarHeight) {
                mFooterBarHeight = a.getDimension(attr, mFooterBarHeight);
            } else if (attr == R.styleable.tlcTimelineChartView_tlcGraphMode) {
                mGraphMode = a.getInt(attr, mGraphMode);
            } else if (attr == R.styleable.tlcTimelineChartView_tlcAnimateCursorTransition) {
                mAnimateCursorTransition = a.getBoolean(attr, mAnimateCursorTransition);
            } else if (attr == R.styleable.tlcTimelineChartView_tlcFollowCursorPosition) {
                mFollowCursorPosition = a.getBoolean(attr, mFollowCursorPosition);
            } else if (attr == R.styleable.tlcTimelineChartView_tlcAlwaysEnsureSelection) {
                mAlwaysEnsureSelection = a.getBoolean(attr, mAlwaysEnsureSelection);
            } else if (attr == R.styleable.tlcTimelineChartView_tlcBarItemWidth) {
                mBarItemWidth = a.getDimension(attr, mBarItemWidth);
            } else if (attr == R.styleable.tlcTimelineChartView_tlcBarItemSpace) {
                mBarItemSpace = a.getDimension(attr, mBarItemSpace);
            } else if (attr == R.styleable.tlcTimelineChartView_tlcPlaySelectionSoundEffect) {
                mPlaySelectionSoundEffect = a.getBoolean(attr, mPlaySelectionSoundEffect);
            } else if (attr == R.styleable.tlcTimelineChartView_tlcSelectionSoundEffectSource) {
                mSelectionSoundEffectSource = a.getInt(attr, mSelectionSoundEffectSource);
            }
        }
    } finally {
        a.recycle();
    }

    // SurfaceView requires a background
    if (getBackground() == null) {
        setBackgroundColor(ContextCompat.getColor(ctx, android.R.color.transparent));
    }

    // Minimize the impact of create dynamic layouts by assume that in most case
    // we will have a day formatter
    mTickHasDayFormat = true;

    // Initialize stuff
    setupBackgroundHandler();
    setupTickLabels();
    if (ViewCompat.getOverScrollMode(this) != ViewCompat.OVER_SCROLL_NEVER) {
        setupEdgeEffects();
    }
    setupAnimators();
    setupSoundEffects();

    // Initialize the drawing refs (this will be update when we have
    // the real size of the canvas)
    computeBoundAreas();

    // Create a fake data for the edit mode
    if (isInEditMode()) {
        setupViewInEditMode();
    }
}

From source file:edu.cmu.mpcs.dashboard.TagViewer.java

private void launchmusicSetting(String settingString) {

    if (settingString.contains("launch music")) {

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

        if (!mAudioManager.isMusicActive()) {
            Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage("com.google.android.music");
            startActivity(LaunchIntent);
        }/*from   w ww.  ja v  a  2  s.  com*/

        if (settingString.contains("launch music:On")) {
            /** Launching the Music App **/
            Intent commandIntent = new Intent("com.android.music.musicservicecommand");
            commandIntent.putExtra("command", "play");
            sendBroadcast(commandIntent);

        } else {
            Intent commandIntent = new Intent("com.android.music.musicservicecommand");
            commandIntent.putExtra("command", "pause");
            sendBroadcast(commandIntent);

        }
    }

}

From source file:com.dmbstream.android.util.Util.java

public static void registerMediaButtonEventReceiver(Context context) {

    // Only do it if enabled in the settings.
    SharedPreferences prefs = getPreferences(context);
    boolean enabled = prefs.getBoolean(Constants.PREFERENCES_KEY_MEDIA_BUTTONS, true);

    if (enabled) {

        // AudioManager.registerMediaButtonEventReceiver() was introduced in Android 2.2.
        // Use reflection to maintain compatibility with 1.5.
        try {//from  www  .  j a v a 2  s. co  m
            AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
            ComponentName componentName = new ComponentName(context.getPackageName(),
                    MediaButtonIntentReceiver.class.getName());
            Method method = AudioManager.class.getMethod("registerMediaButtonEventReceiver",
                    ComponentName.class);
            method.invoke(audioManager, componentName);
        } catch (Throwable x) {
            // Ignored.
        }
    }
}

From source file:com.dmbstream.android.util.Util.java

public static void unregisterMediaButtonEventReceiver(Context context) {
    // AudioManager.unregisterMediaButtonEventReceiver() was introduced in Android 2.2.
    // Use reflection to maintain compatibility with 1.5.
    try {//  w  ww.j ava2 s.c om
        AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        ComponentName componentName = new ComponentName(context.getPackageName(),
                MediaButtonIntentReceiver.class.getName());
        Method method = AudioManager.class.getMethod("unregisterMediaButtonEventReceiver", ComponentName.class);
        method.invoke(audioManager, componentName);
    } catch (Throwable x) {
        // Ignored.
    }
}

From source file:org.sipdroid.sipua.ui.Receiver.java

static void broadcastCallStateChanged(String state, String number) {
    if (state == null) {
        state = laststate;/*w w w  . jav a2s  .  com*/
        number = lastnumber;
    }
    if (android.os.Build.VERSION.SDK_INT < 19) {
        Intent intent = new Intent(ACTION_PHONE_STATE_CHANGED);
        intent.putExtra("state", state);
        if (number != null)
            intent.putExtra("incoming_number", number);
        intent.putExtra(mContext.getString(R.string.app_name), true);
        mContext.sendBroadcast(intent, android.Manifest.permission.READ_PHONE_STATE);
    }
    if (state.equals("IDLE")) {
        if (was_playing) {
            if (pstn_state == null || pstn_state.equals("IDLE"))
                mContext.sendBroadcast(new Intent(TOGGLEPAUSE_ACTION));
            was_playing = false;
        }
    } else {
        AudioManager am = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
        if ((laststate == null || laststate.equals("IDLE")) && (was_playing = am.isMusicActive()))
            mContext.sendBroadcast(new Intent(PAUSE_ACTION));
    }
    laststate = state;
    lastnumber = number;
}