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:de.tubs.ibr.dtn.chat.service.ChatService.java

@SuppressWarnings("deprecation")
private void showNotification(Intent intent) {
    int defaults = 0;

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    if (prefs.getBoolean("vibrateOnMessage", true)) {
        defaults |= Notification.DEFAULT_VIBRATE;
    }/*  w  w w.java 2s . c  o  m*/

    Long buddyId = intent.getLongExtra(EXTRA_BUDDY_ID, -1L);
    String displayName = intent.getStringExtra(EXTRA_DISPLAY_NAME);
    String textBody = intent.getStringExtra(EXTRA_TEXT_BODY);

    CharSequence tickerText = getString(R.string.new_message_from) + " " + displayName;
    CharSequence contentTitle = getString(R.string.new_message);
    CharSequence contentText = displayName + ":\n" + textBody;

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);

    // forward intent to the activity
    intent.setClass(this, MainActivity.class);

    // Adds the intent to the main view
    stackBuilder.addNextIntent(intent);
    // Gets a PendingIntent containing the entire back stack
    PendingIntent contentIntent = stackBuilder.getPendingIntent(buddyId.intValue(),
            PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    builder.setContentTitle(contentTitle);
    builder.setContentText(contentText);
    builder.setSmallIcon(R.drawable.ic_message);
    builder.setTicker(tickerText);
    builder.setDefaults(defaults);
    builder.setWhen(System.currentTimeMillis());
    builder.setContentIntent(contentIntent);
    builder.setLights(0xffff0000, 300, 1000);
    builder.setSound(
            Uri.parse(prefs.getString("ringtoneOnMessage", "content://settings/system/notification_sound")));
    builder.setAutoCancel(true);

    Notification notification = builder.getNotification();

    NotificationManager mNotificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(buddyId.toString(), MESSAGE_NOTIFICATION, notification);

    if (prefs.getBoolean("ttsWhenOnHeadset", false)) {
        AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

        if (am.isBluetoothA2dpOn() || am.isWiredHeadsetOn()) {
            // speak the notification
            Intent tts_intent = new Intent(this, TTSService.class);
            tts_intent.setAction(TTSService.INTENT_SPEAK);
            tts_intent.putExtra("speechText", tickerText + ": " + textBody);
            startService(tts_intent);
        }
    }
}

From source file:com.nbplus.vbroadlauncher.RealtimeBroadcastActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
    acquireCpuWakeLock();/*from w w  w . j ava  2s  .  c o  m*/

    KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
    km.inKeyguardRestrictedInputMode();
    if (km.inKeyguardRestrictedInputMode()) {
        Log.i(TAG, " ??");
        isKeyguardRestrictedInputMode = true;
    } else {
        Log.i(TAG, "   ??");
    }

    mLastNetworkStatus = NetworkUtils.isConnected(this);
    Intent intent = getIntent();
    if (intent == null || !PushConstants.ACTION_PUSH_MESSAGE_RECEIVED.equals(intent.getAction())) {
        Log.d(TAG, "empty or none broadcast intent value ...");
        finishActivity();
        return;
    }

    mBroadcastData = intent.getParcelableExtra(Constants.EXTRA_BROADCAST_PAYLOAD_DATA);
    if (mBroadcastData == null) {
        Log.d(TAG, ">> payload data is null");
        finishActivity();
        return;
    }

    mBroadcastPayloadIdx = intent.getLongExtra(Constants.EXTRA_BROADCAST_PAYLOAD_INDEX, -1);
    Log.d(TAG, ">> onCreate() mBroadcastPayloadIdx= " + mBroadcastPayloadIdx);

    // ? ms  ? ?? ? ?   ?  ????
    // broadcast ? .
    //  ?? ?? ??.
    Intent i = new Intent(this, RealtimeBroadcastActivity.class);
    i.setAction(intent.getAction());
    i.putExtra(Constants.EXTRA_BROADCAST_PAYLOAD_DATA, mBroadcastData);
    i.putExtra(Constants.EXTRA_BROADCAST_PAYLOAD_INDEX, mBroadcastPayloadIdx);
    LocalBroadcastManager.getInstance(this).sendBroadcast(i);

    IntentFilter filter = new IntentFilter();
    filter.addAction(PushConstants.ACTION_PUSH_MESSAGE_RECEIVED);
    filter.addAction(Constants.ACTION_BROWSER_ACTIVITY_CLOSE);
    LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, filter);

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    registerReceiver(mBroadcastReceiver, intentFilter);

    hideSystemUI();
    /*
    final Window win = getWindow();
    win.setFlags(
        WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                | WindowManager.LayoutParams.FLAG_FULLSCREEN
                | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
                | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD,
        WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                | WindowManager.LayoutParams.FLAG_FULLSCREEN
                | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
                | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
            
    win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
                | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
                | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON);
    */

    if (Constants.PUSH_PAYLOAD_TYPE_TEXT_BROADCAST.equals(mBroadcastData.getServiceType())) {
        setContentView(R.layout.fragment_text_broadcast);
    } else {
        setContentView(R.layout.fragment_audio_broadcast);
    }
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
            | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);

    if (Constants.PUSH_PAYLOAD_TYPE_TEXT_BROADCAST.equals(mBroadcastData.getServiceType())) {
        mcheckText2SpeechLister = this;
        // ?
        mTextView = (TextView) findViewById(R.id.broadcast_text);
        mTextView.setText(mBroadcastData.getMessage());
        mTextView.setVerticalScrollBarEnabled(true);
        mTextView.setHorizontalScrollBarEnabled(false);
        mTextView.setMovementMethod(new ScrollingMovementMethod());

        mHandler.sendEmptyMessageDelayed(HANDLER_MESSAGE_SETUP_CURRENT_PLAYING, 800);
        Log.d(TAG, "text broadcast = " + mBroadcastData.getMessage());

        mText2SpeechHandler = new TextToSpeechHandler(this, this);
        checkText2SpeechAvailable();
        mIsTTS = true;
    } else {
        // , ??
        mWebView = (WebView) findViewById(R.id.webview);
        mWebViewClient = new RealtimeBroadcastWebViewClient(this, mWebView, this);
        mWebViewClient.setBackgroundTransparent();

        String url = mBroadcastData.getMessage();
        if (url.indexOf("?") > 0) {
            if (!url.contains("UUID=")) {
                url += ("&UUID=" + LauncherSettings.getInstance(this).getDeviceID());
            }
            if (!url.contains("APPID=")) {
                url += ("&APPID=" + getApplicationContext().getPackageName());
            }
        } else {
            if (!url.contains("UUID=")) {
                url += ("?UUID=" + LauncherSettings.getInstance(this).getDeviceID());
            }
            if (!url.contains("APPID=")) {
                if (!url.contains("UUID=")) {
                    url += ("?APPID=" + getApplicationContext().getPackageName());
                } else {
                    url += ("&APPID=" + getApplicationContext().getPackageName());
                }
            }
        }

        mWebViewClient.loadUrl(url);
        mIsTTS = false;
    }
    AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    mStreamMusicVolume = audio.getStreamVolume(AudioManager.STREAM_MUSIC);
    audio.setStreamVolume(AudioManager.STREAM_MUSIC, audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC),
            AudioManager.FLAG_PLAY_SOUND);

    if (Constants.OPEN_BETA_PHONE && LauncherSettings.getInstance(this).isSmartPhone()) {
        StateListener phoneStateListener = new StateListener();
        TelephonyManager telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
    }
}

From source file:edu.sfsu.csc780.chathub.ui.activities.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    DesignUtils.applyColorfulTheme(this);
    setContentView(R.layout.activity_main);
    mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
    mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    // Set default username is anonymous.
    mUsername = ANONYMOUS;/* w w w .j  ava2s . co m*/
    //Initialize Auth
    mAuth = FirebaseAuth.getInstance();
    mUser = mAuth.getCurrentUser();
    if (mUser == null) {
        startActivity(new Intent(this, SignInActivity.class));
        finish();
        return;
    } else {
        mUsername = mUser.getDisplayName();
        if (mUser.getPhotoUrl() != null) {
            mPhotoUrl = mUser.getPhotoUrl().toString();
        }
    }

    AudioUtil.startAudioListener(this);

    mSinchClient = Sinch.getSinchClientBuilder().context(getApplicationContext())
            .applicationKey(APIKeys.SINCH_API_KEY).applicationSecret(APIKeys.SINCH_APP_SECRET)
            .environmentHost("sandbox.sinch.com")
            .userId(UserUtil.parseUsername(mSharedPreferences.getString("username", "anonymous"))).build();
    mSinchClient.setSupportCalling(true);

    mCurrentChannel = mSharedPreferences.getString("currentChannel", "general");
    mCurrChanTextView = (TextView) findViewById(R.id.currentChannelName);
    mCurrChanTextView.setText(ChannelUtil.getChannelDisplayName(mCurrentChannel, this));

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
            .addApi(Auth.GOOGLE_SIGN_IN_API).build();

    // Initialize ProgressBar and RecyclerView.

    mMessageRecyclerView = (RecyclerView) findViewById(R.id.messageRecyclerView);
    mLinearLayoutManager = new LinearLayoutManager(this);
    mLinearLayoutManager.setStackFromEnd(true);
    mMessageRecyclerView.setLayoutManager(mLinearLayoutManager);
    mChannelAdd = (RelativeLayout) findViewById(R.id.channelAdd);

    mToolBar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(mToolBar);
    mToolBar.setTitleTextColor(Color.WHITE);

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
    mDrawerLayout.setStatusBarBackgroundColor(ContextCompat.getColor(this, R.color.colorPrimary));

    mFirebaseAdapter = MessageUtil.getFirebaseAdapter(this, this, /* MessageLoadListener */
            mLinearLayoutManager, mMessageRecyclerView, mImageClickListener);
    mMessageRecyclerView.setAdapter(mFirebaseAdapter);

    mProgressBar.setVisibility(ProgressBar.INVISIBLE);

    mMessageEditText = (EditText) findViewById(R.id.messageEditText);
    mMessageEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(MSG_LENGTH_LIMIT) });
    mMessageEditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            if (charSequence.toString().trim().length() > 0) {
                mSendButton.setEnabled(true);
            } else {
                mSendButton.setEnabled(false);
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {
        }
    });

    mSendButton = (FloatingActionButton) findViewById(R.id.sendButton);
    mSendButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // Send messages on click.
            mMessageRecyclerView.scrollToPosition(0);
            ChatMessage chatMessage = new ChatMessage(mMessageEditText.getText().toString(), mUsername,
                    mPhotoUrl, mCurrentChannel);
            MessageUtil.send(chatMessage, MainActivity.this);
            mMessageEditText.setText("");
        }
    });

    mImageButton = (ImageButton) findViewById(R.id.shareImageButton);
    mImageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            pickImage();
        }
    });

    mPhotoButton = (ImageButton) findViewById(R.id.cameraButton);
    mPhotoButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dispatchTakePhotoIntent();
        }
    });

    mLocationButton = (ImageButton) findViewById(R.id.locationButton);
    mLocationButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            loadMap();
        }
    });

    mChannelAdd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(MainActivity.this, ChannelSearchActivity.class);
            startActivityForResult(intent, REQUEST_NEW_CHANNEL);
        }
    });

    SearchView jumpSearchView = (SearchView) findViewById(R.id.jumpSearch);
    int id = jumpSearchView.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
    TextView textView = (TextView) jumpSearchView.findViewById(id);
    textView.setTextColor(Color.WHITE);
    textView.setHintTextColor(Color.WHITE);

    jumpSearchView.setIconified(false);
    jumpSearchView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(MainActivity.this, "Not implemented", Toast.LENGTH_SHORT).show();
        }
    });

    mNavRecyclerView = (RecyclerView) findViewById(R.id.navRecyclerView);
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
    mNavRecyclerView.setLayoutManager(linearLayoutManager);
    mNavRecyclerView.setAdapter(ChannelUtil.getFirebaseAdapterForUserChannelList(mChannelClickListener,
            mAuth.getCurrentUser().getDisplayName()));

    RecyclerView userListRecyclerView = (RecyclerView) findViewById(R.id.userListRecyclerView);
    LinearLayoutManager linearLayoutManager2 = new LinearLayoutManager(this);
    userListRecyclerView.setLayoutManager(linearLayoutManager2);
    userListRecyclerView.setAdapter(UserUtil.getFirebaseAdapterForUserList(mChannelClickListener));

    Button voiceCallButton = (Button) findViewById(R.id.voiceCall);
    mCallProgressTextView = (TextView) findViewById(R.id.callinprogress);

    final AudioManager audioManager = (AudioManager) getApplicationContext()
            .getSystemService(Context.AUDIO_SERVICE);
    voiceCallButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            CallClient callClient = mSinchClient.getCallClient();
            if (canCall) {
                call = callClient.callConference("General");
                call.addCallListener(new CallListener() {
                    @Override
                    public void onCallProgressing(Call call) {
                        //setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
                        audioManager.adjustStreamVolume(AudioManager.STREAM_VOICE_CALL,
                                AudioManager.ADJUST_RAISE, 10);
                        Log.d("Call", "Call progressing");
                    }

                    @Override
                    public void onCallEstablished(Call call) {
                        setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
                        mCallProgressTextView.setVisibility(View.VISIBLE);
                        Log.d("Call", "Calling now");
                    }

                    @Override
                    public void onCallEnded(Call call) {
                        setVolumeControlStream(AudioManager.USE_DEFAULT_STREAM_TYPE);
                        Log.d("Call", "Stopped calling");
                        mCallProgressTextView.setVisibility(View.INVISIBLE);
                    }

                    @Override
                    public void onShouldSendPushNotification(Call call, List<PushPair> list) {
                        Log.d("Call", "Push");
                    }
                });
            }
        }
    });

    Button endCallButton = (Button) findViewById(R.id.endCall);
    endCallButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (call != null) {
                call.hangup();
                call = null;
            }
        }
    });
}

From source file:com.google.sample.castcompanionlibrary.cast.VideoCastManager.java

private VideoCastManager(Context context, String applicationId, Class<?> targetActivity, String dataNamespace) {
    super(context, applicationId);
    LOGD(TAG, "VideoCastManager is instantiated");
    mDataNamespace = dataNamespace;/* w w  w .j  av  a2 s. c om*/
    if (null == targetActivity) {
        targetActivity = VideoCastControllerActivity.class;
    }
    mTargetActivity = targetActivity;
    Utils.saveStringToPreference(mContext, PREFS_KEY_CAST_ACTIVITY_NAME, mTargetActivity.getName());
    if (null != mDataNamespace) {
        Utils.saveStringToPreference(mContext, PREFS_KEY_CAST_CUSTOM_DATA_NAMESPACE, dataNamespace);
    }

    mMiniControllers = Collections.synchronizedSet(new HashSet<IMiniController>());

    mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    mMediaButtonReceiverComponent = new ComponentName(context, VideoIntentReceiver.class);
}

From source file:com.devalladolid.musictoday.MusicService.java

@Override
public void onCreate() {
    if (D)//from w w  w .ja  v  a2  s.  c  o m
        Log.d(TAG, "Creating service");
    super.onCreate();

    mNotificationManager = NotificationManagerCompat.from(this);

    // gets a pointer to the playback state store
    mPlaybackStateStore = MusicPlaybackState.getInstance(this);
    mSongPlayCount = SongPlayCount.getInstance(this);
    mRecentStore = RecentStore.getInstance(this);

    mHandlerThread = new HandlerThread("MusicPlayerHandler", android.os.Process.THREAD_PRIORITY_BACKGROUND);
    mHandlerThread.start();

    mPlayerHandler = new MusicPlayerHandler(this, mHandlerThread.getLooper());

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

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
        setUpMediaSession();

    mPreferences = getSharedPreferences("Service", 0);
    mCardId = getCardId();

    registerExternalStorageListener();

    mPlayer = new MultiPlayer(this);
    mPlayer.setHandler(mPlayerHandler);

    // Initialize the intent filter and each action
    final IntentFilter filter = new IntentFilter();
    filter.addAction(SERVICECMD);
    filter.addAction(TOGGLEPAUSE_ACTION);
    filter.addAction(PAUSE_ACTION);
    filter.addAction(STOP_ACTION);
    filter.addAction(NEXT_ACTION);
    filter.addAction(PREVIOUS_ACTION);
    filter.addAction(PREVIOUS_FORCE_ACTION);
    filter.addAction(REPEAT_ACTION);
    filter.addAction(SHUFFLE_ACTION);
    // Attach the broadcast listener
    registerReceiver(mIntentReceiver, filter);

    mMediaStoreObserver = new MediaStoreObserver(mPlayerHandler);
    getContentResolver().registerContentObserver(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, true,
            mMediaStoreObserver);
    getContentResolver().registerContentObserver(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, true,
            mMediaStoreObserver);

    // Initialize the wake lock
    final PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());
    mWakeLock.setReferenceCounted(false);

    final Intent shutdownIntent = new Intent(this, MusicService.class);
    shutdownIntent.setAction(SHUTDOWN);

    mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    mShutdownIntent = PendingIntent.getService(this, 0, shutdownIntent, 0);

    scheduleDelayedShutdown();

    reloadQueueAfterPermissionCheck();
    notifyChange(QUEUE_CHANGED);
    notifyChange(META_CHANGED);
}

From source file:com.google.android.libraries.cast.companionlibrary.cast.VideoCastManager.java

protected VideoCastManager(Context context, String applicationId, Class<?> targetActivity,
        String dataNamespace) {/*from w  w  w. j  ava 2 s  . c o  m*/
    super(context, applicationId);
    LOGD(TAG, "VideoCastManager is instantiated");
    mDataNamespace = dataNamespace;
    if (targetActivity == null) {
        targetActivity = VideoCastControllerActivity.class;
    }
    mTargetActivity = targetActivity;
    mPreferenceAccessor.saveStringToPreference(PREFS_KEY_CAST_ACTIVITY_NAME, mTargetActivity.getName());
    if (!TextUtils.isEmpty(mDataNamespace)) {
        mPreferenceAccessor.saveStringToPreference(PREFS_KEY_CAST_CUSTOM_DATA_NAMESPACE, dataNamespace);
    }

    mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
    mMediaButtonReceiverComponent = new ComponentName(mContext, VideoIntentReceiver.class);
}

From source file:edu.stanford.mobisocial.dungbeetle.ui.fragments.AppsViewFragment.java

@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
    if (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP) {
        if (!event.isTracking()) {
            return true;
        }/*  w  w  w.j  a  v  a 2s  .  c  o m*/
        if (!event.isLongPress()) {
            AudioManager audio = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
            audio.adjustVolume(AudioManager.ADJUST_RAISE,
                    AudioManager.FLAG_PLAY_SOUND | AudioManager.FLAG_SHOW_UI);
            return true;
        }
    }
    if (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_DOWN) {
        if (!event.isTracking()) {
            return true;
        }
        if (!event.isLongPress()) {
            AudioManager audio = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
            audio.adjustVolume(AudioManager.ADJUST_LOWER,
                    AudioManager.FLAG_PLAY_SOUND | AudioManager.FLAG_SHOW_UI);
            return true;
        }
    }
    return false;
}

From source file:de.spiritcroc.modular_remote.MainActivity.java

@Override
protected void onPause() {
    super.onPause();

    viewPager.removeOnPageChangeListener(this);

    saveConnections();/*from  w  w w  .  j  av a2  s .  c om*/
    appWidgetHost.stopListening();

    if (changedRingerMode) {
        changedRingerMode = false;
        AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        audioManager.setRingerMode(previousRingerMode);
    }
}

From source file:br.com.viniciuscr.notification2android.mediaPlayer.MediaPlaybackService.java

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

    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    ComponentName rec = new ComponentName(getPackageName(), MediaButtonIntentReceiver.class.getName());
    mAudioManager.registerMediaButtonEventReceiver(rec);

    Intent i = new Intent(Intent.ACTION_MEDIA_BUTTON);
    i.setComponent(rec);//from  w w w  .  jav a 2 s  .  c o  m
    PendingIntent pi = PendingIntent.getBroadcast(this /*context*/, 0 /*requestCode, ignored*/, i /*intent*/,
            0 /*flags*/);
    mRemoteControlClient = new RemoteControlClient(pi);
    mAudioManager.registerRemoteControlClient(mRemoteControlClient);

    int flags = RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS | RemoteControlClient.FLAG_KEY_MEDIA_NEXT
            | RemoteControlClient.FLAG_KEY_MEDIA_PLAY | RemoteControlClient.FLAG_KEY_MEDIA_PAUSE
            | RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE | RemoteControlClient.FLAG_KEY_MEDIA_STOP;
    mRemoteControlClient.setTransportControlFlags(flags);

    mPreferences = getSharedPreferences("Music", MODE_WORLD_READABLE | MODE_WORLD_WRITEABLE);
    mCardId = MusicUtils.getCardId(this);

    registerExternalStorageListener();

    // Needs to be done in this thread, since otherwise ApplicationContext.getPowerManager() crashes.
    mPlayer = new MultiPlayer();
    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);

    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);
}