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.nbplus.vbroadlauncher.RadioActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (Constants.OPEN_BETA_PHONE && LauncherSettings.getInstance(this).isSmartPhone()) {
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }/*from ww w  . jav  a2s  .  c o  m*/

    mSettingsContentObserver = new SettingsContentObserver(this, new Handler());
    getApplicationContext().getContentResolver().registerContentObserver(
            android.provider.Settings.System.CONTENT_URI, true, mSettingsContentObserver);

    showProgressDialog();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        window.setStatusBarColor(getResources().getColor(R.color.activity_radio_background));
    }

    overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
    setContentView(R.layout.activity_radio);

    Intent i = getIntent();
    mShortcutData = i.getParcelableExtra(Constants.EXTRA_NAME_SHORTCUT_DATA);
    if (mShortcutData == null) {
        Log.e(TAG, "mShortcutData is not found..");
        finishActivity();
        return;
    }

    IntentFilter filter = new IntentFilter();
    filter.addAction(MusicService.ACTION_PLAYED);
    filter.addAction(MusicService.ACTION_PAUSED);
    filter.addAction(MusicService.ACTION_STOPPED);
    filter.addAction(MusicService.ACTION_COMPLETED);
    filter.addAction(MusicService.ACTION_ERROR);
    filter.addAction(MusicService.ACTION_PLAYING_STATUS);

    LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, filter);
    // send playing status
    Intent queryStatus = new Intent(this, MusicService.class);
    queryStatus.setAction(MusicService.ACTION_PLAYING_STATUS);
    startService(queryStatus);

    // ViewPager .
    // ??? ? ? ? .
    mViewPager = (NbplusViewPager) findViewById(R.id.viewPager);
    mIndicator = (CirclePageIndicator) findViewById(R.id.indicator);

    // close button
    ImageButton closeButton = (ImageButton) findViewById(R.id.btn_close);
    closeButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            finishActivity();
        }
    });

    mActivityLayout = (RelativeLayout) findViewById(R.id.radio_activity_background);
    int wallpaperId = LauncherSettings.getInstance(this).getWallpaperId();
    mActivityLayout.setBackgroundResource(LauncherSettings.landWallpaperResource[wallpaperId]);

    // title.
    mRadioTitle = (TextView) findViewById(R.id.radio_activity_label);

    // media controller
    mPlayToggle = (ImageButton) findViewById(R.id.ic_media_control_play);
    mPlayToggle.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (mCurrentPlayingStatus == null) {
                return;
            }
            MusicService.State state = (MusicService.State) mCurrentPlayingStatus
                    .getSerializable(MusicService.EXTRA_PLAYING_STATUS);
            Intent i = new Intent(RadioActivity.this, MusicService.class);
            if (state == MusicService.State.Playing) {
                i.setAction(MusicService.ACTION_PAUSE);
            } else if (state == MusicService.State.Paused) {
                i.setAction(MusicService.ACTION_PLAY);
            }
            startService(i);
        }
    });
    mPlayStop = (ImageButton) findViewById(R.id.ic_media_control_stop);
    mPlayStop.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (mCurrentPlayingStatus == null) {
                return;
            }
            MusicService.State state = (MusicService.State) mCurrentPlayingStatus
                    .getSerializable(MusicService.EXTRA_PLAYING_STATUS);
            if (state == MusicService.State.Playing || state == MusicService.State.Paused) {
                Intent i = new Intent(RadioActivity.this, MusicService.class);
                i.setAction(MusicService.ACTION_STOP);
                i.putExtra(MusicService.EXTRA_MUSIC_FORCE_STOP, false);
                startService(i);
            }
        }
    });

    mSoundToggle = (ImageButton) findViewById(R.id.ic_media_control_volume_btn);
    AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    int currentVolume = audio.getStreamVolume(AudioManager.STREAM_MUSIC);
    int maxVolume = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
    if (currentVolume <= 0) {
        mSoundToggle.setBackgroundResource(R.drawable.ic_button_radio_sound_off);
    } else {
        mSoundToggle.setBackgroundResource(R.drawable.ic_button_radio_sound_on);
    }
    mSoundToggle.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

            if (audio.getStreamVolume(AudioManager.STREAM_MUSIC) <= 0) {
                if (mSoundTogglePreviousValue > 0) {
                    audio.setStreamVolume(AudioManager.STREAM_MUSIC, mSoundTogglePreviousValue,
                            AudioManager.FLAG_PLAY_SOUND);
                } else {
                    mSoundTogglePreviousValue = 1;
                    audio.setStreamVolume(AudioManager.STREAM_MUSIC, mSoundTogglePreviousValue,
                            AudioManager.FLAG_PLAY_SOUND);
                }
                mSoundToggle.setBackgroundResource(R.drawable.ic_button_radio_sound_on);
                mSeekbar.setProgress(mSoundTogglePreviousValue);
                mSoundTogglePreviousValue = -1;
            } else {
                mSoundTogglePreviousValue = audio.getStreamVolume(AudioManager.STREAM_MUSIC);
                audio.setStreamVolume(AudioManager.STREAM_MUSIC, 0, AudioManager.FLAG_PLAY_SOUND);
                mSoundToggle.setBackgroundResource(R.drawable.ic_button_radio_sound_off);
            }
        }
    });

    mSeekbar = (SeekBar) findViewById(R.id.ic_media_control_volume_seek);
    mSeekbar.setMax(maxVolume);
    mSeekbar.setProgress(currentVolume);
    mSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (fromUser) {
                mSoundTogglePreviousValue = -1;
                AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
                audio.setStreamVolume(AudioManager.STREAM_MUSIC, progress, AudioManager.FLAG_PLAY_SOUND);
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });

    getRadioChannelTask = new GetRadioChannelTask();
    if (getRadioChannelTask != null) {
        getRadioChannelTask.setBroadcastApiData(this, mHandler,
                mShortcutData.getDomain() + mShortcutData.getPath());
        mIsExecuteGetRadioChannelTask = true;
        getRadioChannelTask.execute();
    }
}

From source file:org.wso2.iot.agent.services.operation.OperationManager.java

/**
 * Mute the device.// w  w  w  .  ja v  a2  s  . com
 *
 * @param operation - Operation object.
 */
public void muteDevice(org.wso2.iot.agent.beans.Operation operation) {
    operation.setStatus(resources.getString(R.string.operation_value_completed));
    resultBuilder.build(operation);

    AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    audioManager.setStreamVolume(AudioManager.STREAM_RING, DEFAULT_VOLUME, DEFAULT_FLAG);
    if (Constants.DEBUG_MODE_ENABLED) {
        Log.d(TAG, "Device muted");
    }
}

From source file:usbong.android.retrocc.UsbongDecisionTreeEngineActivity.java

public void init() {
    //if return is null, then currScreen=0
    //        currScreen=Integer.parseInt(getIntent().getStringExtra("currScreen")); 
    //modified by JPT, May 25, 2015
    if (getIntent().getStringExtra("currScreen") != null) {
        currScreen = Integer.parseInt(getIntent().getStringExtra("currScreen"));
    }/*from w  w  w  .  ja  va  2 s .c  o m*/

    //updated by Mike, 20160608
    /*        
            currLanguageBeingUsed=UsbongUtils.LANGUAGE_ENGLISH;
          UsbongUtils.setCurrLanguage("English"); //added by Mike, 22 Sept. 2015
    */
    //Reference: http://stackoverflow.com/questions/23024831/android-shared-preferences-example
    //; last accessed: 9 June 2015
    //answer by Elenasys
    //added by Mike, 9 June 2015
    SharedPreferences prefs = getSharedPreferences(UsbongConstants.MY_SAVED_LANGUAGE_SETTING, MODE_PRIVATE);
    if (prefs != null) {
        //@todo: remove this id thing, immediately use the String; otherwise it'll be cumbersome to keep on adding language ids
        currLanguageBeingUsed = prefs.getInt("preferredLanguage",
                UsbongUtils.getLanguageID(UsbongUtils.getCurrLanguage())); //default is Filipino
        /* //commented out by Mike, 20160608
         * //default language will be set based on the default language set in the .xml of the .utree file
         *         UsbongUtils.setDefaultLanguage(UsbongUtils.getLanguageBasedOnID(currLanguageBeingUsed));
         */
        UsbongUtils.setCurrLanguage(UsbongUtils.getLanguageBasedOnID(currLanguageBeingUsed));//prefs.getInt("preferredLanguage", 0))); //updated by Mike, 20160612
    } else {
        //default..
        currLanguageBeingUsed = UsbongUtils.getLanguageID(UsbongUtils.getCurrLanguage());
        //UsbongUtils.setCurrLanguage(UsbongUtils.getLanguageBasedOnID(currLanguageBeingUsed)); //updated by Mike, 20160612
    }

    /*       //commented out by Mike, 20160618
     *       //why? the index numbers used by currSelectedItemForSetLanguage does not always match with currLanguageBeingUsed
     *        //added by Mike, 20160608
     *        currSelectedItemForSetLanguage = currLanguageBeingUsed;
     */
    //==================================================================
    //text-to-speech stuff
    /*//comment out, not needed in DAHON, 
    * commented out by Mike, 20160613
    Intent checkIntent = new Intent();
    checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
    startActivityForResult(checkIntent, UsbongUtils.MY_DATA_CHECK_CODE);
    */
    mTts = new TextToSpeech(this, this);
    mTts.setLanguage(new Locale("en", "US"));//default
    //==================================================================

    myMediaPlayer = new MediaPlayer();
    myMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); //added by Mike, 22 July 2015
    myMediaPlayer.setVolume(1.0f, 1.0f);

    //added by Mike, 25 Sept. 2015
    myBGMediaPlayer = new MediaPlayer();
    myBGMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    myBGMediaPlayer.setVolume(0.5f, 0.5f);

    //added by Mike, 22 July 2015
    AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    am.setStreamVolume(AudioManager.STREAM_MUSIC, am.getStreamMaxVolume(AudioManager.STREAM_MUSIC), 0);

    usbongNodeContainer = new Vector<String>();
    classificationContainer = new Vector<String>();
    radioButtonsContainer = new Vector<String>();
    usbongAnswerContainer = new Vector<String>();
    checkBoxesContainer = new Vector<String>();
    decisionTrackerContainer = new Vector<String>();

    usedBackButton = false;
    currAnswer = "";

    try {
        //commented out by Mike, 4 Oct. 2015
        UsbongUtils.createUsbongFileStructure();

        //added by Mike, 20160417
        UsbongUtils.initUsbongConfigFile();

        //create the usbong_demo_tree and store it in sdcard/usbong/usbong_trees
        //          UsbongUtils.storeAssetsFileIntoSDCard(this,"usbong_demo_tree.xml");
        /*          UsbongUtils.storeAssetsFileIntoSDCard(this,UsbongUtils.DEFAULT_UTREE_TO_LOAD+".utree");
         */
        //edited by Mike, 20160119
        UsbongUtils.storeAssetsFileIntoSDCard(this, UsbongConstants.TREE_TYPE_SELL + ".utree");
        UsbongUtils.storeAssetsFileIntoSDCard(this, UsbongConstants.TREE_TYPE_REQUEST + ".utree");
        UsbongUtils.storeAssetsFileIntoSDCard(this, UsbongConstants.TREE_TYPE_BUY + ".utree"); //added by Mike, 20160126           

        //added by Mike, 20160126
        UsbongUtils.storeAssetsFileIntoSDCard(this, UsbongConstants.ITEMS_LIST_COMICS + ".txt");
        UsbongUtils.storeAssetsFileIntoSDCard(this, UsbongConstants.ITEMS_LIST_TOYS + ".txt");
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }

    //Reference: http://stackoverflow.com/questions/2793004/java-lista-addalllistb-fires-nullpointerexception
    //Last accessed: 14 March 2012
    attachmentFilePaths = new ArrayList<String>();
    //      attachmentFilePaths.clear();
    //      System.out.println(">>>>>>>>> attachmentFilePaths.clear!");
    currAudioRecorder = null;

    myQRCodeContent = "";
    hasReturnedFromAnotherActivity = false; //camera, paint, email, etc

    //added by Mike, March 4, 2013
    usbongAnswerContainerCounter = 0;
    /*              
           ArrayList<String> skuList = new ArrayList<String> ();
           skuList.add(UsbongConstants.ALL_LOCAL_LANGUAGES_PRODUCT_ID);
           skuList.add(UsbongConstants.ALL_FOREIGN_LANGUAGES_PRODUCT_ID);
           Bundle querySkus = new Bundle();
           querySkus.putStringArrayList("ITEM_ID_LIST", skuList);
    */

    new AsyncTask<String, Integer, Boolean>() {
        @Override
        protected void onPostExecute(Boolean result) {
            //added by Mike, 20160421
            //init purchase languages list
            purchaseLanguagesListDialog = new AlertDialog.Builder(getInstance());
            myPurchaseLanguageBundleListAdapter = new PurchaseLanguageBundleListAdapter(getInstance(),
                    UsbongUtils.getInAppOwnedItems(), UsbongUtils.getInAppMService());
            purchaseLanguagesListDialog.setTitle("Purchase");
            purchaseLanguagesListDialog.setSingleChoiceItems(myPurchaseLanguageBundleListAdapter, 0,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            //                         Log.i("Selected Item : ", (String) myPurchaseLanguageBundleListAdapter.getItem(which));
                            dialog.dismiss(); //edited by Mike, 20160508                  
                            //                        purchaseLanguagesListDialogInterface = dialog;
                        }
                    });
            purchaseLanguagesListDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
        }

        @Override
        protected Boolean doInBackground(String... params) {
            try {
                UsbongUtils.initInAppBillingService(getInstance());
                UsbongUtils.initInAppBillingService(getInstance()); //need to call this twice to get the updated languageBundleList
            } catch (Exception e) {
                e.printStackTrace();
            }
            return true;
        }
    }.execute();

    //reference: Labeeb P's answer from stackoverflow;
    //http://stackoverflow.com/questions/4275797/view-setpadding-accepts-only-in-px-is-there-anyway-to-setpadding-in-dp;
    //last accessed: 23 May 2013
    final float scale = getResources().getDisplayMetrics().density;
    padding_in_px = (int) (padding_in_dp * scale + 0.5f);

    //added by Mike, 25 June 2013
    UsbongUtils.setDebugMode(UsbongUtils.isInDebugMode());

    //added by Mike, 25 Feb. 2014
    //        UsbongUtils.setStoreOutput(UsbongUtils.checkIfStoreOutput());
    UsbongUtils.setStoreOutput(false); //don't store output, added by Mike, 27 Sept. 2015

    myUsbongScreenProcessor = new UsbongScreenProcessor(UsbongDecisionTreeEngineActivity.getInstance());
    myUsbongVariableMemory = new HashMap<String, String>();
    /*
           //Reference: http://stackoverflow.com/questions/23024831/android-shared-preferences-example
            //; last accessed: 20150609
            //answer by Elenasys
            //added by Mike, 20150207
            prefs = getSharedPreferences(UsbongConstants.MY_ACCOUNT_DETAILS, MODE_PRIVATE);
            if (prefs!=null) {
             setVariableOntoMyUsbongVariableMemory("firstName", prefs.getString("firstName", ""));//"" is the default value.
             setVariableOntoMyUsbongVariableMemory("surname", prefs.getString("surname", ""));//"" is the default value.
             setVariableOntoMyUsbongVariableMemory("contactNumber", prefs.getString("contactNumber", ""));//"" is the default value.
             setVariableOntoMyUsbongVariableMemory("shippingAddress", prefs.getString("shippingAddress", ""));//"" is the default value.
            }
            else {
              setVariableOntoMyUsbongVariableMemory("firstName", "");//"" is the default value.
              setVariableOntoMyUsbongVariableMemory("surname", "");//"" is the default value.
              setVariableOntoMyUsbongVariableMemory("contactNumber", "");//"" is the default value.
              setVariableOntoMyUsbongVariableMemory("shippingAddress", "");//"" is the default value.           
            }        
    */
    //added by Mike, March 26, 2014
    try {
        Log.d(">>>>", "" + UsbongUtils.STORE_OUTPUT);
        if (UsbongUtils.STORE_OUTPUT) { //added by Mike, 27 Sept. 2015
            UsbongUtils.createNewOutputFolderStructure();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    /*        
    //       initTreeLoader();
          //added by JPT, May 25, 2015
          if(getIntent().getStringExtra(Constants.UTREE_KEY) != null) {
             Log.d("DecisionTree", getIntent().getStringExtra(Constants.UTREE_KEY));
             initParser(getIntent().getStringExtra(Constants.UTREE_KEY));
          } else {         
              initTreeLoader();
          }
          */
    /*       initTreeLoader(); //not needed in Usbong Kuto, Mike, 25 Sept 2015
     */
    //added by Mike, 30 April 2015
    isInTreeLoader = false;

    //added by Mike, 20160119
    if (getIntent().getStringExtra("utreeToLoad") != null) {
        myTree = getIntent().getStringExtra("utreeToLoad");
    } else {
        myTree = UsbongUtils.DEFAULT_UTREE_TO_LOAD; //edited by Mike, 20160418
    }

    UsbongUtils.clearTempFolder();
    //            isr=null; //set inputStreamReader to null; i.e. new tree
    /*              initParser();   
    */

    //              myProgressDialog.dismiss();
    /*              
      //added by Mike, 29 Sept. 2015
      //Reference: http://stackoverflow.com/questions/10407159/how-to-manage-startactivityforresult-on-android;
      //last accessed: 29 Sept. 2015; answer by Nishant, 2 May 2012; edited by Daniel Nugent, 9 July 2015
      Intent returnIntent = new Intent();
      returnIntent.putExtra("result","result");
      setResult(RESULT_OK,returnIntent);
    */
}

From source file:com.brejza.matt.habmodem.Dsp_service.java

public void enableEcho() {
    if (isRecording) {
        AudioManager manager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        manager.setMode(AudioManager.MODE_IN_CALL);
        manager.setSpeakerphoneOn(true);
    }/*from www  .  j av a  2s  . c  om*/
    enableEcho = true;
}

From source file:com.googlecode.mindbell.accessors.ContextAccessor.java

public int getAlarmMaxVolume() {
    AudioManager audioMan = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    return audioMan.getStreamMaxVolume(AudioManager.STREAM_ALARM);
}

From source file:com.brejza.matt.habmodem.Dsp_service.java

public void disableEcho() {
    AudioManager manager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    manager.setMode(AudioManager.MODE_NORMAL);
    manager.setSpeakerphoneOn(false);/*w w w .java  2s  . c o m*/
    enableEcho = false;
}

From source file:org.wso2.emm.agent.services.operation.OperationManager.java

/**
 * Mute the device./*from ww w  .  j av a2s .com*/
 *
 * @param operation - Operation object.
 */
public void muteDevice(org.wso2.emm.agent.beans.Operation operation) {
    operation.setStatus(resources.getString(R.string.operation_value_completed));
    resultBuilder.build(operation);

    AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    audioManager.setStreamVolume(AudioManager.STREAM_RING, DEFAULT_VOLUME, DEFAULT_FLAG);
    if (Constants.DEBUG_MODE_ENABLED) {
        Log.d(TAG, "Device muted");
    }
}

From source file:com.hotstar.player.adplayer.player.PlayerFragment.java

private void requestAudioFocus() {
    AudioManager am = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);

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

    if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
        AdVideoApplication.logger.i(LOG_TAG + "#requestAudioFocus()", "Gained audio focus.");
    }
}

From source file:com.socialdisasters.other.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;
    }/*from   w ww.ja v  a  2  s  . c  om*/

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

    // create a reply intent
    String replyLabel = getResources().getString(R.string.reply_label);
    RemoteInput remoteInput = new RemoteInput.Builder(EXTRA_VOICE_REPLY).setLabel(replyLabel).build();

    Intent replyIntent = new Intent(this, ReplyActivity.class);
    replyIntent.putExtra(EXTRA_BUDDY_ID, buddyId);
    PendingIntent replyPendingIntent = PendingIntent.getActivity(this, buddyId.intValue(), replyIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    NotificationCompat.Action action = new NotificationCompat.Action.Builder(R.drawable.ic_action_reply,
            getString(R.string.reply_label), replyPendingIntent).addRemoteInput(remoteInput).build();

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    builder.setContentTitle(contentTitle);
    builder.setContentText(contentText);
    builder.setSmallIcon(R.drawable.ic_stat_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.extend(new WearableExtender().addAction(action));
    builder.setAutoCancel(false);

    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:org.botlibre.sdk.activity.MicConfiguration.java

private void muteMicBeep(boolean mute) {
    AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    if (mute) {//w  ww.j a  va 2s. c om
        //if its true then the Volume will be zero.
        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
    } else {
        //if its false, the Volume will put back no
        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, MainActivity.volume, 0);
    }
}