Example usage for android.media AudioManager setStreamVolume

List of usage examples for android.media AudioManager setStreamVolume

Introduction

In this page you can find the example usage for android.media AudioManager setStreamVolume.

Prototype

public void setStreamVolume(int streamType, int index, int flags) 

Source Link

Document

Sets the volume index for a particular stream.

Usage

From source file:com.xortech.sender.SmsReceiver.java

public void onReceive(final Context ctx, Intent intent) {
    // GET SMS MAP FROM INTENT
    Bundle extras = intent.getExtras();//from  www. j  a va2  s.c  om
    context = ctx;

    // GPS INSTANCE
    gps = new GPSTracker(context);

    // LOAD PREFERENCES
    preferences = PreferenceManager.getDefaultSharedPreferences(context);
    secretCode = preferences.getString("secretCode", DEFAULT_CODE);
    tagID = preferences.getString("tagID", DEFAULT_TAGID);
    senderEnabled = preferences.getBoolean("senderEnabled", true);

    if (extras != null) {

        // GET THE RECEIVED SMS ARRAY
        Object[] smsExtra = (Object[]) extras.get(SMS_EXTRA_NAME);

        for (int i = 0; i < smsExtra.length; ++i) {

            // GET THE MESSAGE
            SmsMessage sms = SmsMessage.createFromPdu((byte[]) smsExtra[i]);

            // PARSE THE MESSAGE BODY
            String body = sms.getMessageBody().toString();
            String address = sms.getOriginatingAddress();
            long time = System.currentTimeMillis();

            // GET COORDINATES AND SEND A MESSAGE
            gps.getLocation();

            latitude = String.valueOf(Math.round(FIVE_DIGIT * gps.getLatitude()) / FIVE_DIGIT);
            longitude = String.valueOf(Math.round(FIVE_DIGIT * gps.getLongitude()) / FIVE_DIGIT);
            location = "Tag_ID:" + tagID + ":Location:" + latitude + "," + longitude;
            googleString = GOOGLE_STRING + latitude + "," + longitude + "(" + tagID + ")";

            if (body.equals(SECRET_LOCATION_A + secretCode)) {
                if (senderEnabled) {
                    if (latitude.equals("0.0") | longitude.equals("0.0")) {
                        SmsManager.getDefault().sendTextMessage(address, null, NO_COORDS + tagID, null, null);
                    } else {
                        SmsManager.getDefault().sendTextMessage(address, null, googleString, null, null);
                    }
                }

                this.abortBroadcast();
            } else if (body.equals(SECRET_LOCATION_B + secretCode)) {
                if (senderEnabled) {
                    if (latitude.equals("0.0") | longitude.equals("0.0")) {
                        SmsManager.getDefault().sendTextMessage(address, null, NO_COORDS + tagID, null, null);
                    } else {
                        SmsManager.getDefault().sendTextMessage(address, null, location, null, null);
                    }
                }

                this.abortBroadcast();
            } else if (body.contains("Tag_ID:")) {
                // ADD TO DATABASE
                MsgDatabaseHandler dbHandler = new MsgDatabaseHandler(context);

                // VERIFY IF THE TAG EXISTS IN THE ARRAY
                String addressExists = VerifyTagExist(address);

                String[] splitBody = body.split(":");
                String tag = splitBody[1];
                tag.trim();
                String coords = splitBody[3];
                String[] splitCoords = coords.split(",");
                String lat = splitCoords[0];
                lat.trim();
                String lon = splitCoords[1];
                lon.trim();
                String _time = String.valueOf(time);
                String toastMsg = null;

                // CHECK IF THE ADDRESS EXISTS FOR NAMING PURPOSES
                if (addressExists == null) {
                    dbHandler.Add_Message(new MessageData(tag, address, lat, lon, _time));
                    toastMsg = "Response Received: " + tag;
                } else {
                    dbHandler.Add_Message(new MessageData(addressExists, address, lat, lon, _time));
                    toastMsg = "Response Received: " + addressExists;
                }

                dbHandler.close();

                Toast.makeText(context, toastMsg, Toast.LENGTH_LONG).show();

                this.abortBroadcast();
            } else if (body.contains("Panic!")) {

                // OVERRIDE THE SILENT FEATURE
                AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
                int max = audio.getStreamMaxVolume(AudioManager.STREAM_NOTIFICATION);
                audio.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
                audio.setStreamVolume(AudioManager.STREAM_RING, max,
                        AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);

                // DEFINE THE NOTIFICATION MANAGER
                notificationManager = (NotificationManager) context
                        .getSystemService(Context.NOTIFICATION_SERVICE);

                // START A TIMER
                mytimer = new Timer(true);

                // SOUND LOCATION ALARM
                soundUri = Uri.parse(BEGIN_PATH + context.getPackageName() + FILE_PATH);

                // DISPLAY TAG ID FOR EMERGENCY
                String[] splitBody = body.split("\n");
                String fieldTag = splitBody[1];
                String[] splitTag = fieldTag.split(":");

                emergencyTag = splitTag[1].trim();

                // TIMER FOR NOTIFICATIONS
                mytask = new TimerTask() {
                    public void run() {
                        // RUN NOTIFICATION ON TIMER
                        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
                                .setSmallIcon(R.drawable.emergency).setContentTitle(PANIC_TXT)
                                .setContentText(emergencyTag + UNDER_DURRESS).setSound(soundUri); //This sets the sound to play

                        // DISPLAY THE NOTIFICATION
                        notificationManager.notify(0, mBuilder.build());
                    }
                };
                // START TIMER AFTER 5 SECONDS
                mytimer.schedule(mytask, FIVE_SECONDS);
            }
        }
    }

    // CLEAR THE CACHE ON RECEIVING A MESSAGE
    try {
        MyUpdateReceiver.trimCache(context);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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

private void finishActivity() {
    Log.d(TAG, "finishActivity()");
    runOnUiThread(new Runnable() {
        @Override/*from  www .j  a va 2  s.  co m*/
        public void run() {
            LauncherSettings.getInstance(getApplicationContext()).setCurrentPlayingBroadcastType(null);

            overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
            if (mText2Speech != null) {
                mText2Speech.shutdown();
            }
            mText2Speech = null;
            mText2SpeechHandler = null;
            mBroadcastPayloadIdx = -1;

            if (mWebView != null) {
                mWebView.removeAllViews();
                mWebView.destroy();
            }
            mWebViewClient = null;
            mWebView = null;
            LocalBroadcastManager.getInstance(getApplicationContext()).unregisterReceiver(mBroadcastReceiver);
            unregisterReceiver(mBroadcastReceiver);

            releaseCpuLock();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    showSystemUI();
                }
            });

            AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
            audio.setStreamVolume(AudioManager.STREAM_MUSIC, mStreamMusicVolume, AudioManager.FLAG_PLAY_SOUND);

            //finish();
            Log.e(TAG, "RealtimeBroadcastActivity.java call System.exit(0)");
            System.exit(0);
        }
    });
}

From source file:org.botlibre.sdk.activity.MicConfiguration.java

private void muteMicBeep(boolean mute) {
    AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    if (mute) {//from   ww w .  j  a  v  a  2 s. com
        //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);
    }
}

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

public void setAlarmVolume(int volume) {
    AudioManager audioMan = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    audioMan.setStreamVolume(AudioManager.STREAM_ALARM, volume, 0);

}

From source file:com.pixate.freestyle.fragment.ButtonsFragment.java

/** Set the volumn controling to seek bar */
private void setSeekBar(SeekBar seek) {
    AudioManager audioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
    seek.setMax(audioManager.getStreamMaxVolume(AudioManager.STREAM_RING));
    seek.setProgress(m_nAlarmVolum);/*  w  w  w.j a v a2  s .  co m*/
    seek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

        @Override
        public void onStopTrackingTouch(SeekBar arg0) {

        }

        @Override
        public void onStartTrackingTouch(SeekBar arg0) {
        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean arg2) {
            m_nAlarmVolum = progress;

            AudioManager audioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
            audioManager.setStreamVolume(AudioManager.STREAM_RING, m_nAlarmVolum,
                    AudioManager.FLAG_ALLOW_RINGER_MODES | AudioManager.FLAG_PLAY_SOUND);
        }
    });
}

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 ww  .  j  a v a 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:org.wso2.mdm.agent.services.Operation.java

/**
 * Mute the device.//www  .  ja  v  a  2s . c om
 * @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:com.intel.xdk.player.Player.java

public void setAudioVolume(String volume) {
    //Valid volumes 0.0 to 1.0
    double castVol = Float.parseFloat(volume);
    if (castVol > 1.0)
        castVol = 1.0;//ww w  .ja v  a 2  s  . c  o m
    // Get the AudioManager
    AudioManager audioManager = (AudioManager) activity.getSystemService(Context.AUDIO_SERVICE);
    int newVol = (int) (audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC) * castVol);
    // Set the volume of played media to maximum.
    audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, newVol, 0);

    String js = "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.player.audio.volume.set',true,true);document.dispatchEvent(e);";
    injectJS(js);
}

From source file:fm.feed.android.playersdk.view.PlayerView.java

private void initializeView() {
    RelativeLayout rootView = (RelativeLayout) inflate(getContext(), R.layout.view_player, this);
    mTitle = (TextView) rootView.findViewById(R.id.pu_title);
    mArtist = (TextView) rootView.findViewById(R.id.pu_artist);
    mAlbum = (TextView) rootView.findViewById(R.id.pu_album);
    mPrefix = (TextView) rootView.findViewById(R.id.pu_prefix);
    mSuffix = (TextView) rootView.findViewById(R.id.pu_suffix);
    mProgressBar = (ProgressBar) rootView.findViewById(R.id.pu_progress);

    LinearLayout topContainer = (LinearLayout) rootView.findViewById(R.id.pu_top_icons);
    LinearLayout bottomContainer = (LinearLayout) rootView.findViewById(R.id.pu_bottom_icons);

    // We need to create the SVGImageView instances and add them programmatically.
    mDislike = newSvgImage(1, ImageView.ScaleType.FIT_START);
    mLike = newSvgImage(2, ImageView.ScaleType.FIT_CENTER);
    mPlayPause = newSvgImage(2, ImageView.ScaleType.FIT_CENTER);
    mSkip = newSvgImage(1, ImageView.ScaleType.FIT_END);
    mVolume = newSvgImage(1, ImageView.ScaleType.FIT_START);
    mShare = newSvgImage(1, ImageView.ScaleType.FIT_END);

    // Set the SVG resource to the SVGImageView
    setSvgResource(mDislike, R.drawable.ic_thumbdown_faded, R.string.accessibility_dislike);
    setSvgResource(mLike, R.drawable.ic_thumbup_faded, R.string.accessibility_like);
    setSvgResource(mPlayPause, R.drawable.ic_play_faded, R.string.accessibility_play);
    setSvgResource(mSkip, R.drawable.ic_skip_disabled, R.string.accessibility_skip_disabled);
    setSvgResource(mVolume, R.drawable.ic_speakerhigh_faded, R.string.accessibility_volume_muted);
    setSvgResource(mShare, R.drawable.ic_share_faded, R.string.accessibility_share);

    // Add SVGImageViews to the layout.
    topContainer.addView(mDislike);/* w w  w  .j a v  a  2s  .  c  o m*/
    topContainer.addView(mLike);
    topContainer.addView(mPlayPause);
    topContainer.addView(mSkip);
    bottomContainer.addView(mVolume);
    bottomContainer.addView(mShare);

    mDislike.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!mPlayer.hasPlay()) {
                return;
            }

            Play.LikeState likeState = mPlayer.getPlay().getLikeState();
            switch (likeState) {
            case NONE:
                setSvgResource(mDislike, R.drawable.ic_thumbdown_normal, R.string.accessibility_disliked);
                mPlayer.dislike();
                break;
            case LIKED:
                setSvgResource(mLike, R.drawable.ic_thumbup_faded, R.string.accessibility_like);
                mPlayer.unlike();
                break;
            case DISLIKED:
                // Do nothing
                break;
            }
        }
    });

    mLike.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!mPlayer.hasPlay()) {
                return;
            }

            Play.LikeState likeState = mPlayer.getPlay().getLikeState();
            switch (likeState) {
            case NONE:
                setSvgResource(mLike, R.drawable.ic_thumbup_normal, R.string.accessibility_liked);
                mPlayer.like();
                break;
            case LIKED:
                // Do nothing
                break;
            case DISLIKED:
                setSvgResource(mDislike, R.drawable.ic_thumbdown_faded, R.string.accessibility_unlike);
                setSvgResource(mLike, R.drawable.ic_thumbup_normal, R.string.accessibility_liked);
                mPlayer.like();
                break;
            }
        }
    });
    mPlayPause.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mPlayer.getState() == PlayInfo.State.PLAYING) {
                mPlayer.pause();
            } else {
                mPlayer.play();
            }
        }
    });
    mSkip.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mPlayer.isSkippable()) {
                setSvgResource(mSkip, R.drawable.ic_skip_normal, R.string.accessibility_skipping);
                mPlayer.skip();
            }
        }
    });
    mShare.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mPlayer == null || !mPlayer.hasPlay()) {
                Log.i(TAG, "Cannot share if not playing");
                return;
            }

            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setType("text/plain");
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);

            String subject = mShareSubject;
            String body = mShareBody;
            if (subject == null) {
                subject = getContext().getString(R.string.share_subject_template);
            }
            if (body == null) {
                Play play = mPlayer.getPlay();
                String title = play.getAudioFile().getTrack().getTitle();
                String artist = play.getAudioFile().getArtist().getName();
                String album = play.getAudioFile().getRelease().getTitle();

                body = getContext().getString(R.string.share_body_template, title, artist, album);
            }

            // Add data to the intent, the receiving app will decide what to do with it.
            intent.putExtra(Intent.EXTRA_SUBJECT, subject);
            intent.putExtra(Intent.EXTRA_TEXT, body);

            getContext()
                    .startActivity(Intent.createChooser(intent, getContext().getString(R.string.share_via)));
        }
    });

    mVolume.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            AudioManager am = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
            int volume = mAudioSettingsContentObserver.getCurrentVolume();
            am.setStreamVolume(AudioManager.STREAM_MUSIC, volume, AudioManager.FLAG_SHOW_UI);
        }
    });

    updateSpeakerUI();
}

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

/**
 * Mute the device./*from w w  w.  ja va2  s .  c  o m*/
 *
 * @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");
    }
}