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.googlecode.mindbell.accessors.ContextAccessor.java

public boolean isAudioStreamMuted() {
    final AudioManager audioMan = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    return audioMan.getStreamVolume(prefs.getAudioStream()) == 0;
}

From source file:com.mobilis.android.nfc.activities.MagTekFragment.java

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

    // Set up the window layout
    //        if (mShowTitle) {
    //            getActivity().requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
    //        }// if(mShowTitle)
    //        else {
    //            getWindow().requestFeature(Window.FEATURE_NO_TITLE);
    //        }//ww  w .  ja  v a 2s  . c o m
    //        setContentView(R.layout.main);
    //
    //        if (mShowTitle)
    //        {
    //            getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
    //                    R.layout.custom_title);
    //        }// if(mShowTitle)

    //        // Set up the custom title
    //        if (mShowTitle)
    //        {
    //            mTitleLeftTextView = (TextView) findViewById(R.id.title_left_text);
    //            mTitleLeftTextView.setText(R.string.app_title);
    //            mTitleLayout = (RelativeLayout) findViewById(R.id.relative_layout_title);
    //            mTitleLayout.setVisibility(View.INVISIBLE);
    //        }// if(mShowTitle)
    //
    //        mAppStatusTextView = (TextView) findViewById(R.id.textview_app_status);
    //        mInfoTextView = (TextView) findViewById(R.id.textview_info);
    //        mCardDataEditText= (EditText) findViewById(R.id.edittext_carddata);
    //        mGetConfigFromWeb=(CheckBox) findViewById(R.id.checkbox_getconfig);
    //        mClearImageButton = (ImageButton) findViewById(R.id.imagebutton_clear);
    //        mSubmitImageButton= (ImageButton) findViewById(R.id.imagebutton_submit);

    mMTSCRA = new MagTekSCRA(mSCRADataHandler);
    mAudioMgr = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
    //        setStatus(R.string.status_default, Color.RED);
    InitializeData();

    mIntCurrentVolume = mAudioMgr.getStreamVolume(AudioManager.STREAM_MUSIC);

    //        mClearImageButton.setOnClickListener(new View.OnClickListener() {
    //            public void onClick(View v)
    //            {
    //                clearAll();
    //            }
    //        });
    //
    //        mSubmitImageButton.setOnClickListener(new View.OnClickListener() {
    //            public void onClick(View v)
    //            {
    //                debugMsg("Android.Model=" + android.os.Build.MODEL);
    //                debugMsg("Android.Device=" + android.os.Build.DEVICE);
    //                debugMsg("Android.Product=" + android.os.Build.PRODUCT);
    //
    //                String mStringBody="";
    //                try
    //                {
    //                    String strVersion = "";
    //                    PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
    //                    strVersion =  pInfo.versionName;
    //                    mStringBody = "App.Version=" + strVersion + "\nSDK.Version=" + mMTSCRA.getSDKVersion() + "\n");
    //
    //                }
    //                catch(Exception ex)
    //                {
    //
    //                }
    //                mStringBody += "Android.Model=" + android.os.Build.MODEL + "\n");
    //                mStringBody += "Android.Device=" + android.os.Build.DEVICE + "\n");
    //                mStringBody += "Android.Product=" + android.os.Build.PRODUCT + "\n");
    //                mStringBody += mStringDebugData;
    //                mCardDataEditText.setText(mStringBody);
    //
    //            /*
    //            Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
    //            String[] recipients = new String[]{"softeng@magtek.com"};
    //                emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, recipients);
    //                emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "MagTek Audio Debug Info");
    //                emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, mStringBody);
    //                emailIntent.setType("text/plain");
    //                startActivity(Intent.createChooser(emailIntent, "Send mail..."));
    //                */
    //            }
    //        });

    Timer tTimer = new Timer();

    TimerTask tTimerTask = new TimerTask() {
        public void run() {
            if (mMTSCRA.isDeviceConnected()) {
                if (mLongTimerInterval >= 2) {
                    if (mMTSCRA.isDeviceConnected()) {
                        if (mIntCurrentStatus == STATUS_IDLE) {
                            //                                setStatus(R.string.status_default, Color.GREEN);
                        }
                    } // if(mDeviceStatus==BluetoothChatService.STATE_CONNECTED)
                    else {
                        //                            setStatus(R.string.status_default, Color.RED);
                    }
                    mLongTimerInterval = 0;
                } // if(mTimerInterval >= 2)

            } // if(mDeviceStatus==BluetoothChatService.STATE_CONNECTED)
            else {

                if ((mIntCurrentStatus == STATUS_IDLE)
                        && (mIntCurrentDeviceStatus == MagTekSCRA.DEVICE_STATE_DISCONNECTED)) {
                    //                        setStatus(R.string.status_default, Color.RED);
                }
            }
            mLongTimerInterval++;
        }
    };
    tTimer.scheduleAtFixedRate(tTimerTask, 0, 1000);
    displayInfo();

}

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

public static void onState(int state, String caller) {
    if (ccCall == null) {
        ccCall = new Call();
        ccConn = new Connection();
        ccCall.setConn(ccConn);//  w ww . j  a  v a2  s.  co m
        ccConn.setCall(ccCall);
    }
    if (call_state != state) {
        if (state != UserAgent.UA_STATE_IDLE)
            call_end_reason = -1;
        call_state = state;
        switch (call_state) {
        case UserAgent.UA_STATE_INCOMING_CALL:
            enable_wifi(true);
            RtpStreamReceiver.good = RtpStreamReceiver.lost = RtpStreamReceiver.loss = RtpStreamReceiver.late = 0;
            RtpStreamReceiver.speakermode = speakermode();
            bluetooth = -1;
            String text = caller.toString();
            if (text.indexOf("<sip:") >= 0 && text.indexOf("@") >= 0)
                text = text.substring(text.indexOf("<sip:") + 5, text.indexOf("@"));
            String text2 = caller.toString();
            if (text2.indexOf("\"") >= 0)
                text2 = text2.substring(text2.indexOf("\"") + 1, text2.lastIndexOf("\""));
            broadcastCallStateChanged("RINGING", caller);
            mContext.sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
            ccCall.setState(Call.State.INCOMING);
            ccConn.setUserData(null);
            ccConn.setAddress(text, text2);
            ccConn.setIncoming(true);
            ccConn.date = System.currentTimeMillis();
            ccCall.base = 0;
            AudioManager am = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
            int rm = am.getRingerMode();
            int vs = am.getVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER);
            KeyguardManager mKeyguardManager = (KeyguardManager) mContext
                    .getSystemService(Context.KEYGUARD_SERVICE);
            if (v == null)
                v = (Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE);
            if ((pstn_state == null || pstn_state.equals("IDLE"))
                    && PreferenceManager.getDefaultSharedPreferences(mContext).getBoolean(
                            org.sipdroid.sipua.ui.Settings.PREF_AUTO_ON,
                            org.sipdroid.sipua.ui.Settings.DEFAULT_AUTO_ON)
                    && !mKeyguardManager.inKeyguardRestrictedInputMode())
                v.vibrate(vibratePattern, 1);
            else {
                if ((pstn_state == null || pstn_state.equals("IDLE")) && (rm == AudioManager.RINGER_MODE_VIBRATE
                        || (rm == AudioManager.RINGER_MODE_NORMAL && vs == AudioManager.VIBRATE_SETTING_ON)))
                    v.vibrate(vibratePattern, 1);
                if (am.getStreamVolume(AudioManager.STREAM_RING) > 0) {
                    String sUriSipRingtone = PreferenceManager.getDefaultSharedPreferences(mContext).getString(
                            org.sipdroid.sipua.ui.Settings.PREF_SIPRINGTONE,
                            Settings.System.DEFAULT_RINGTONE_URI.toString());
                    if (!TextUtils.isEmpty(sUriSipRingtone)) {
                        oRingtone = RingtoneManager.getRingtone(mContext, Uri.parse(sUriSipRingtone));
                        if (oRingtone != null)
                            oRingtone.play();
                    }
                }
            }
            moveTop();
            if (wl == null) {
                PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
                wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP,
                        "Sipdroid.onState");
            }
            wl.acquire();
            Checkin.checkin(true);
            break;
        case UserAgent.UA_STATE_OUTGOING_CALL:
            RtpStreamReceiver.good = RtpStreamReceiver.lost = RtpStreamReceiver.loss = RtpStreamReceiver.late = 0;
            RtpStreamReceiver.speakermode = speakermode();
            bluetooth = -1;
            onText(MISSED_CALL_NOTIFICATION, null, 0, 0);
            engine(mContext).register();
            broadcastCallStateChanged("OFFHOOK", caller);
            ccCall.setState(Call.State.DIALING);
            ccConn.setUserData(null);
            ccConn.setAddress(caller, caller);
            ccConn.setIncoming(false);
            ccConn.date = System.currentTimeMillis();
            ccCall.base = 0;
            moveTop();
            Checkin.checkin(true);
            break;
        case UserAgent.UA_STATE_IDLE:
            broadcastCallStateChanged("IDLE", null);
            onText(CALL_NOTIFICATION, null, 0, 0);
            ccCall.setState(Call.State.DISCONNECTED);
            if (listener_video != null)
                listener_video.onHangup();
            stopRingtone();
            if (wl != null && wl.isHeld())
                wl.release();
            mContext.startActivity(createIntent(InCallScreen.class));
            ccConn.log(ccCall.base);
            ccConn.date = 0;
            engine(mContext).listen();
            break;
        case UserAgent.UA_STATE_INCALL:
            broadcastCallStateChanged("OFFHOOK", null);
            if (ccCall.base == 0) {
                ccCall.base = SystemClock.elapsedRealtime();
            }
            progress();
            ccCall.setState(Call.State.ACTIVE);
            stopRingtone();
            if (wl != null && wl.isHeld())
                wl.release();
            mContext.startActivity(createIntent(InCallScreen.class));
            break;
        case UserAgent.UA_STATE_HOLD:
            onText(CALL_NOTIFICATION, mContext.getString(R.string.card_title_on_hold),
                    android.R.drawable.stat_sys_phone_call_on_hold, ccCall.base);
            ccCall.setState(Call.State.HOLDING);
            if (InCallScreen.started && (pstn_state == null || !pstn_state.equals("RINGING")))
                mContext.startActivity(createIntent(InCallScreen.class));
            break;
        }
        pos(true);
        RtpStreamReceiver.ringback(false);
    }
}

From source file:com.kaltura.playersdk.PlayerViewController.java

private void setVolumeLevel(double percent) {//Itay
    AudioManager mgr = (AudioManager) mActivity.getSystemService(Context.AUDIO_SERVICE);
    if (percent > 0.01) {
        while (percent < 1.0) {
            percent *= 10;/*from   w ww .j a va 2s .com*/
        }
    }
    mgr.setStreamVolume(AudioManager.STREAM_MUSIC, (int) percent, 0);
}

From source file:de.dcja.prettygreatmusicplayer.MusicPlaybackService.java

@Override
public synchronized void onCreate() {
    Log.i(TAG, "Music Playback Service Created!");
    isRunning = true;/*from w w  w  . j ava 2  s . c  om*/
    sharedPref = PreferenceManager.getDefaultSharedPreferences(this);

    powerManager = (PowerManager) getSystemService(POWER_SERVICE);
    wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "PGMPWakeLock");

    random = new Random();

    mp = new MediaPlayer();
    mReadaheadThread = new ReadaheadThread();

    mp.setOnCompletionListener(new OnCompletionListener() {

        @Override
        public void onCompletion(MediaPlayer mp) {
            Log.i(TAG, "Song complete");
            next();
        }

    });

    onDemandMediaMetadataRetriever = new OnDemandMediaMetadataRetriever();

    // https://developer.android.com/training/managing-audio/audio-focus.html
    audioFocusListener = new PrettyGoodAudioFocusChangeListener();

    // Get permission to play audio
    am = (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);

    HandlerThread thread = new HandlerThread("ServiceStartArguments");
    thread.start();

    // Get the HandlerThread's Looper and use it for our Handler
    mServiceLooper = thread.getLooper();
    mServiceHandler = new ServiceHandler(mServiceLooper);

    // https://stackoverflow.com/questions/19474116/the-constructor-notification-is-deprecated
    // https://stackoverflow.com/questions/6406730/updating-an-ongoing-notification-quietly/15538209#15538209
    Intent resultIntent = new Intent(this, NowPlaying.class);
    resultIntent.putExtra("From_Notification", true);

    // Use the FLAG_ACTIVITY_CLEAR_TOP to prevent launching a second
    // NowPlaying if one already exists.
    resultIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, resultIntent, 0);

    Builder builder = new NotificationCompat.Builder(this.getApplicationContext());

    String contentText = getResources().getString(R.string.ticker_text);
    if (songFile != null) {
        contentText = Utils.getPrettySongName(songFile);
    }

    Notification notification = builder.setContentText(contentText).setSmallIcon(R.drawable.ic_pgmp_launcher)
            .setWhen(System.currentTimeMillis()).setContentIntent(pendingIntent)
            .setContentTitle(getResources().getString(R.string.notification_title)).build();

    startForeground(uniqueid, notification);

    timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            onTimerTick();
        }
    }, 0, 500L);

    Log.i(TAG, "Registering event receiver");
    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    // Apparently audio registration is persistent across lots of things...
    // restarts, installs, etc.
    mAudioManager.registerMediaButtonEventReceiver(cn);
    // I tried to register this in the manifest, but it doesn't seen to
    // accept it, so I'll do it this way.
    getApplicationContext().registerReceiver(receiver, filter);

    headphoneReceiver = new HeadphoneBroadcastReceiver();
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction("android.intent.action.HEADSET_PLUG");
    registerReceiver(headphoneReceiver, filter);
}

From source file:com.phonegap.AudioHandler.java

/**
 * Set the audio device to be used for playback.
 * //from  w w w .j av  a 2 s  .  co m
 * @param output         1=earpiece, 2=speaker
 */
public void setAudioOutputDevice(int output) {
    AudioManager audiMgr = (AudioManager) this.ctx.getSystemService(Context.AUDIO_SERVICE);
    if (output == 2) {
        audiMgr.setRouting(AudioManager.MODE_NORMAL, AudioManager.ROUTE_SPEAKER, AudioManager.ROUTE_ALL);
    } else if (output == 1) {
        audiMgr.setRouting(AudioManager.MODE_NORMAL, AudioManager.ROUTE_EARPIECE, AudioManager.ROUTE_ALL);
    } else {
        System.out.println("AudioHandler.setAudioOutputDevice() Error: Unknown output device.");
    }
}

From source file:pct.droid.fragments.VideoPlayerFragment.java

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override//from   w  ww . j  a  v a2s . c om
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    setRetainInstance(true);

    getAppCompatActivity().setSupportActionBar(mToolbar);

    videoSurface.setVisibility(View.VISIBLE);

    mToolbar.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            onTouchEvent(event);
            return true;
        }
    });

    /* Services and miscellaneous */
    mAudioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
    mAudioMax = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);

    mDisplayHandler = new Handler(Looper.getMainLooper());

    mDecorView = getActivity().getWindow().getDecorView();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        mDecorView.setOnSystemUiVisibilityChangeListener(this);
    }

    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2) {
        getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        mToolbar.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
                getResources().getDimensionPixelSize(R.dimen.abc_action_bar_default_height_material)
                        + PixelUtils.getStatusBarHeight(getActivity())));
        mToolbar.setPadding(mToolbar.getPaddingLeft(), PixelUtils.getStatusBarHeight(getActivity()),
                mToolbar.getPaddingRight(), mToolbar.getPaddingBottom());
    }

    if (getAppCompatActivity().getSupportActionBar() != null) {
        if (null != mCallback.getInfo()) {
            if (mMedia != null && mMedia.title != null) {
                if (null != mCallback.getInfo().getQuality()) {
                    getAppCompatActivity().getSupportActionBar().setTitle(getString(R.string.now_playing) + ": "
                            + mMedia.title + " (" + mCallback.getInfo().getQuality() + ")");
                } else {
                    getAppCompatActivity().getSupportActionBar()
                            .setTitle(getString(R.string.now_playing) + ": " + mMedia.title);
                }
            } else {
                getAppCompatActivity().getSupportActionBar().setTitle(getString(R.string.now_playing));
            }
        } else {
            getAppCompatActivity().getSupportActionBar().setTitle(getString(R.string.now_playing));
        }
        getAppCompatActivity().getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    mSubtitleText.setTextColor(PrefUtils.get(getActivity(), Prefs.SUBTITLE_COLOR, Color.WHITE));
    mSubtitleText.setTextSize(TypedValue.COMPLEX_UNIT_DIP,
            PrefUtils.get(getActivity(), Prefs.SUBTITLE_SIZE, 16));
    mSubtitleText.setStrokeColor(PrefUtils.get(getActivity(), Prefs.SUBTITLE_STROKE_COLOR, Color.BLACK));
    mSubtitleText.setStrokeWidth(TypedValue.COMPLEX_UNIT_DIP,
            PrefUtils.get(getActivity(), Prefs.SUBTITLE_STROKE_WIDTH, 2));

    mControlBar.setOnSeekBarChangeListener(mOnControlBarListener);

    getAppCompatActivity().setVolumeControlStream(AudioManager.STREAM_MUSIC);
}

From source file:com.mattprecious.prioritysms.receiver.AlarmReceiver.java

private void doNotify(Context context, BaseProfile profile) {
    AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    MediaPlayer mediaPlayer = new MediaPlayer();

    try {//from  w w w .ja va2  s .com
        if (audioManager.getRingerMode() == AudioManager.RINGER_MODE_NORMAL || profile.isOverrideSilent()) {
            mediaPlayer.setWakeMode(context, PowerManager.PARTIAL_WAKE_LOCK);
            mediaPlayer.setAudioStreamType(
                    profile.isOverrideSilent() ? AudioManager.STREAM_ALARM : AudioManager.STREAM_NOTIFICATION);
            mediaPlayer.setDataSource(context, profile.getRingtone());
            mediaPlayer.prepare();
            mediaPlayer.start();

            if (profile.isVibrate()) {
                Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
                vibrator.vibrate(VIBRATE_PATTERN, -1);
            }
        }
    } catch (IllegalArgumentException e) {
        Log.e(TAG, "failed to play audio", e);
    } catch (IOException e) {
        Log.e(TAG, "failed to play audio", e);
    }
}

From source file:com.marvin.rocklock.RockLockActivity.java

/** Called when the activity is first created. */
@Override/*from w w w. j  a v a 2 s. c o  m*/
public void onCreate(Bundle savedInstanceState) {

    mSelf = this;

    sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
            Uri.parse("file://" + Environment.getExternalStorageDirectory())));

    mPlayer = new RockLockMusicPlayer(this);

    super.onCreate(savedInstanceState);

    requestWindowFeature(android.view.Window.FEATURE_NO_TITLE);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);

    setContentView(R.layout.main);
    mIconDisplay = (ImageView) findViewById(R.id.gestureIcon);
    mCurrentTrack = (TextView) findViewById(R.id.current_track);
    mCurrentInfo = (TextView) findViewById(R.id.current_info);
    mUpcomingText = (TextView) findViewById(R.id.upcoming);
    mModeText = (TextView) findViewById(R.id.mode_text);

    mGestureOverlay = (MusicGestureOverlay) findViewById(R.id.gestureLayer);
    mGestureOverlay.setGestureListener(new PlayerGestureListener(), true);
    updateDisplayText(null, null, false);

    mTts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {

        @Override
        public void onInit(int status) {
            mTts.setOnUtteranceCompletedListener(new OnUtteranceCompletedListener() {
                @Override
                public void onUtteranceCompleted(String utteranceId) {
                    if (mCurrentUtteranceId != null && mCurrentUtteranceId.equals(utteranceId)) {
                        mPlayer.restoreMusic();
                    }
                }
            });
        }
    });
    mTts.addEarcon(TOCK_EARCON, RockLockActivity.class.getPackage().getName(), R.raw.tock_snd);
    mTts.addEarcon(TICK_EARCON, RockLockActivity.class.getPackage().getName(), R.raw.tick_snd);

    mVibe = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

    mWasStartedByService = getIntent().getBooleanExtra(EXTRA_STARTED_BY_SERVICE, false);

    mPhoneListener = new RockLockPhoneListener();
    final TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    tm.listen(mPhoneListener, PhoneStateListener.LISTEN_CALL_STATE);
    mPausedForCall = false;

    // Start the service in case it is not already running
    startService(new Intent(this, ScreenOnHandlerService.class));

    // Get notification manager
    mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    loadBookmarks();

    // Browsing preference
    mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    mBrowsingPref = mPrefs.getBoolean(getString(R.string.browse_mode), true);
}

From source file:com.metinkale.prayerapp.vakit.AlarmReceiver.java

public void fireAlarm(Intent intent) throws InterruptedException {

    Context c = App.getContext();

    if ((intent == null) || !intent.hasExtra("json")) {

        return;/*from w  w  w . j av  a  2s .  c  o m*/
    }
    Alarm next = Alarm.fromString(intent.getStringExtra("json"));
    intent.removeExtra("json");

    if (next.city == 0) {
        return;
    }

    Times t = Times.getTimes(next.city);
    if (t == null)
        return;
    boolean active;
    if (next.cuma) {
        active = t.isCumaActive();
    } else if (next.early) {
        active = t.isEarlyNotificationActive(next.vakit);
    } else {
        active = t.isNotificationActive(next.vakit);
    }
    if (!active) {
        return;
    }

    boolean vibrate;
    String sound;
    String dua;
    long silenter;
    if (next.cuma) {
        vibrate = t.hasCumaVibration();
        sound = t.getCumaSound();
        dua = "silent";
        silenter = t.getCumaSilenterDuration();
    } else if (next.early) {
        vibrate = t.hasEarlyVibration(next.vakit);
        sound = t.getEarlySound(next.vakit);
        dua = "silent";
        silenter = t.getEarlySilenterDuration(next.vakit);
    } else {
        vibrate = t.hasVibration(next.vakit);
        sound = t.getSound(next.vakit);
        dua = t.getDua(next.vakit);
        silenter = t.getSilenterDuration(next.vakit);
    }

    NotificationManager nm = (NotificationManager) c.getSystemService(Context.NOTIFICATION_SERVICE);

    nm.cancel(next.city + "", NotIds.ALARM);
    String text;

    text = t.getName() + " (" + t.getSource() + ")";

    String txt = "";
    if (next.early) {
        String[] left_part = App.getContext().getResources().getStringArray(R.array.lefttext_part);
        txt = App.getContext().getString(R.string.earlyText, left_part[next.vakit.index],
                "" + t.getEarlyTime(next.vakit));
    } else if (next.cuma) {
        String[] left_part = App.getContext().getResources().getStringArray(R.array.lefttext_part);
        txt = App.getContext().getString(R.string.earlyText, left_part[next.vakit.index], "" + t.getCumaTime());
    } else if (next.vakit != null) {
        txt = next.vakit.getString();
    }

    NotificationCompat.Builder builder = new NotificationCompat.Builder(c).setContentTitle(text)
            .setContentText(txt).setContentIntent(Main.getPendingIntent(t)).setSmallIcon(R.drawable.ic_abicon);
    Notification not = builder.build();

    if (vibrate) {
        not.vibrate = VibrationPreference.getPattern(c, "vibration");
    }

    AudioManager am = (AudioManager) c.getSystemService(Context.AUDIO_SERVICE);

    class MPHolder {
        MediaPlayer mp;
    }
    not.deleteIntent = PendingIntent.getBroadcast(c, 0, new Intent(c, Audio.class),
            PendingIntent.FLAG_UPDATE_CURRENT);

    nm.notify(next.city + "", NotIds.ALARM, not);

    final MPHolder mp = new MPHolder();

    if (Prefs.showNotificationScreen() && (sound != null) && !sound.startsWith("silent")) {
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        if (!pm.isScreenOn()) {
            Intent i = new Intent(c, NotificationPopup.class);
            i.putExtra("city", next.city);
            i.putExtra("name", text);
            i.putExtra("vakit", txt);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP
                    | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
            c.startActivity(i);

            Thread.sleep(1000);
        }
    }

    sInterrupt = false;
    boolean hasSound = false;
    while ((sound != null) && !sound.startsWith("silent") && !sInterrupt) {
        int volume = -2;
        hasSound = true;

        if (!sound.startsWith("silent") && !sound.startsWith("picker")) {

            if (sound.contains("$volume")) {
                volume = Integer.parseInt(sound.substring(sound.indexOf("$volume") + 7));
                sound = sound.substring(0, sound.indexOf("$volume"));
            }
            if (volume != -2) {
                int oldvalue = am.getStreamVolume(getStreamType(c));
                am.setStreamVolume(getStreamType(c), volume, 0);
                volume = oldvalue;
            }

            try {
                mp.mp = play(c, sound);
            } catch (IOException e) {
                e.printStackTrace();
                if (next.cuma) {
                    t.setCumaSound("silent");
                } else if (next.early) {
                    t.setEarlySound(next.vakit, "silent");
                } else {
                    if ("sound".equals(t.getSound(next.vakit))) {
                        t.setSound(next.vakit, "silent");
                    } else {
                        t.setDua(next.vakit, "silent");
                    }
                }
                mp.mp = null;
            }

            if (mp.mp != null) {

                mp.mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mediaPlayer) {
                        if (mp.mp == null) {
                            return;
                        }
                        mp.mp.stop();
                        mp.mp.release();
                        mp.mp = null;
                    }
                });

                mp.mp.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {
                    @Override
                    public void onSeekComplete(MediaPlayer mediaPlayer) {
                        if (mp.mp == null) {
                            return;
                        }
                        mp.mp.stop();
                        mp.mp.release();
                        mp.mp = null;
                    }
                });

            }

            sInterrupt = false;

            while ((mp.mp != null) && mp.mp.isPlaying()) {
                if (sInterrupt) {
                    mp.mp.stop();
                    mp.mp.release();
                    mp.mp = null;

                    dua = null;
                } else {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException ignore) {
                    }
                }
            }
            sInterrupt = false;

        }

        if (volume != -2) {
            am.setStreamVolume(getStreamType(c), volume, 0);
        }
        sound = dua;
        dua = null;
    }

    if (hasSound && Prefs.autoRemoveNotification()) {
        nm.cancel(next.city + "", NotIds.ALARM);
    }
    if (silenter != 0) {
        silenter(c, silenter);
    }

}