Example usage for android.content Intent ACTION_MEDIA_BUTTON

List of usage examples for android.content Intent ACTION_MEDIA_BUTTON

Introduction

In this page you can find the example usage for android.content Intent ACTION_MEDIA_BUTTON.

Prototype

String ACTION_MEDIA_BUTTON

To view the source code for android.content Intent ACTION_MEDIA_BUTTON.

Click Source Link

Document

Broadcast Action: The "Media Button" was pressed.

Usage

From source file:singh.amandeep.musicplayer.MediaButtonIntentReceiver.java

/**
 * {@inheritDoc}//  www.jav a2s . c om
 */
@Override
public void onReceive(final Context context, final Intent intent) {
    final String intentAction = intent.getAction();
    if (AudioManager.ACTION_AUDIO_BECOMING_NOISY.equals(intentAction)) {
        startService(context, MusicService.CMDPAUSE);
    } else if (Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
        final KeyEvent event = intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
        if (event == null) {
            return;
        }

        final int keycode = event.getKeyCode();
        final int action = event.getAction();
        final long eventtime = event.getEventTime();

        String command = null;
        switch (keycode) {
        case KeyEvent.KEYCODE_MEDIA_STOP:
            command = MusicService.CMDSTOP;
            break;
        case KeyEvent.KEYCODE_HEADSETHOOK:
        case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
            command = MusicService.CMDTOGGLEPAUSE;
            break;
        case KeyEvent.KEYCODE_MEDIA_NEXT:
            command = MusicService.CMDNEXT;
            break;
        case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
            command = MusicService.CMDPREVIOUS;
            break;
        case KeyEvent.KEYCODE_MEDIA_PAUSE:
            command = MusicService.CMDPAUSE;
            break;
        case KeyEvent.KEYCODE_MEDIA_PLAY:
            command = MusicService.CMDPLAY;
            break;
        }
        if (command != null) {
            if (action == KeyEvent.ACTION_DOWN) {
                if (mDown) {
                    if (MusicService.CMDTOGGLEPAUSE.equals(command) || MusicService.CMDPLAY.equals(command)) {
                        if (mLastClickTime != 0 && eventtime - mLastClickTime > LONG_PRESS_DELAY) {
                            acquireWakeLockAndSendMessage(context,
                                    mHandler.obtainMessage(MSG_LONGPRESS_TIMEOUT, context), 0);
                        }
                    }
                } else if (event.getRepeatCount() == 0) {
                    // Only consider the first event in a sequence, not the repeat events,
                    // so that we don't trigger in cases where the first event went to
                    // a different app (e.g. when the user ends a phone call by
                    // long pressing the headset button)

                    // The service may or may not be running, but we need to send it
                    // a command.
                    if (keycode == KeyEvent.KEYCODE_HEADSETHOOK) {
                        if (eventtime - mLastClickTime >= DOUBLE_CLICK) {
                            mClickCounter = 0;
                        }

                        mClickCounter++;
                        mHandler.removeMessages(MSG_HEADSET_DOUBLE_CLICK_TIMEOUT);

                        Message msg = mHandler.obtainMessage(MSG_HEADSET_DOUBLE_CLICK_TIMEOUT, mClickCounter, 0,
                                context);

                        long delay = mClickCounter < 3 ? DOUBLE_CLICK : 0;
                        if (mClickCounter >= 3) {
                            mClickCounter = 0;
                        }
                        mLastClickTime = eventtime;
                        acquireWakeLockAndSendMessage(context, msg, delay);
                    } else {
                        startService(context, command);
                    }
                    mLaunched = false;
                    mDown = true;
                }
            } else {
                mHandler.removeMessages(MSG_LONGPRESS_TIMEOUT);
                mDown = false;
            }
            if (isOrderedBroadcast()) {
                abortBroadcast();
            }
            releaseWakeLockIfHandlerIdle();
        }
    }
}

From source file:com.doctoror.fuckoffmusicplayer.presentation.playback.PlaybackAndroidService.java

@Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        stopSelf();// w w w .  j ava2  s . c  o m
        return START_NOT_STICKY;
    }

    if (intent == null) {
        stopSelf(startId);
        return START_NOT_STICKY;
    }

    final String action = intent.getAction();
    if (action == null) {
        stopSelf(startId);
        return START_NOT_STICKY;
    }

    switch (intent.getAction()) {
    case ACTION_PLAY_PAUSE:
        onActionPlayPause();
        break;

    case ACTION_PLAY:
        onActionPlay(intent);
        break;

    case ACTION_PLAY_ANYTHING:
        onActionPlayAnything();
        break;

    case ACTION_PAUSE:
        onActionPause();
        break;

    case ACTION_STOP:
        onActionStop();
        break;

    case ACTION_STOP_WITH_ERROR:
        onActionStopWithError(intent.getCharSequenceExtra(EXTRA_ERROR_MESSAGE));
        break;

    case ACTION_PREV:
        onActionPrev();
        break;

    case ACTION_NEXT:
        onActionNext();
        break;

    case ACTION_SEEK:
        onActionSeek(intent);
        break;

    case Intent.ACTION_MEDIA_BUTTON:
        onActionMediaButton(intent);
        break;

    default:
        stopSelf(startId);
        return START_NOT_STICKY;
    }
    return START_STICKY;
}

From source file:com.av.remusic.receiver.MediaButtonIntentReceiver.java

@Override
public void onReceive(final Context context, final Intent intent) {
    final String intentAction = intent.getAction();
    if (AudioManager.ACTION_AUDIO_BECOMING_NOISY.equals(intentAction)) {
        if (true)
            startService(context, MediaService.CMDPAUSE);
    } else if (Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
        final KeyEvent event = intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
        if (event == null) {
            return;
        }// w  ww.  j  a  v a 2 s. co  m

        final int keycode = event.getKeyCode();
        final int action = event.getAction();
        final long eventtime = event.getEventTime();

        String command = null;
        switch (keycode) {
        case KeyEvent.KEYCODE_MEDIA_STOP:
            command = MediaService.CMDSTOP;
            break;
        case KeyEvent.KEYCODE_HEADSETHOOK:
        case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
            command = MediaService.CMDTOGGLEPAUSE;
            break;
        case KeyEvent.KEYCODE_MEDIA_NEXT:
            command = MediaService.CMDNEXT;
            break;
        case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
            command = MediaService.CMDPREVIOUS;
            break;
        case KeyEvent.KEYCODE_MEDIA_PAUSE:
            command = MediaService.CMDPAUSE;
            break;
        case KeyEvent.KEYCODE_MEDIA_PLAY:
            command = MediaService.CMDPLAY;
            break;
        }
        if (command != null) {
            if (action == KeyEvent.ACTION_DOWN) {
                if (mDown) {
                    if (MediaService.CMDTOGGLEPAUSE.equals(command) || MediaService.CMDPLAY.equals(command)) {
                        if (mLastClickTime != 0 && eventtime - mLastClickTime > LONG_PRESS_DELAY) {
                            acquireWakeLockAndSendMessage(context,
                                    mHandler.obtainMessage(MSG_LONGPRESS_TIMEOUT, context), 0);
                        }
                    }
                } else if (event.getRepeatCount() == 0) {

                    if (keycode == KeyEvent.KEYCODE_HEADSETHOOK) {
                        if (eventtime - mLastClickTime >= DOUBLE_CLICK) {
                            mClickCounter = 0;
                        }

                        mClickCounter++;
                        if (DEBUG)
                            Log.v(TAG, "Got headset click, count = " + mClickCounter);
                        mHandler.removeMessages(MSG_HEADSET_DOUBLE_CLICK_TIMEOUT);

                        Message msg = mHandler.obtainMessage(MSG_HEADSET_DOUBLE_CLICK_TIMEOUT, mClickCounter, 0,
                                context);

                        long delay = mClickCounter < 3 ? DOUBLE_CLICK : 0;
                        if (mClickCounter >= 3) {
                            mClickCounter = 0;
                        }
                        mLastClickTime = eventtime;
                        acquireWakeLockAndSendMessage(context, msg, delay);
                    } else {
                        startService(context, command);
                    }
                    mLaunched = false;
                    mDown = true;
                }
            } else {
                mHandler.removeMessages(MSG_LONGPRESS_TIMEOUT);
                mDown = false;
            }
            if (isOrderedBroadcast()) {
                abortBroadcast();
            }
            releaseWakeLockIfHandlerIdle();
        }
    }
}

From source file:com.bluros.music.helpers.MediaButtonIntentReceiver.java

@Override
public void onReceive(final Context context, final Intent intent) {
    final String intentAction = intent.getAction();
    if (AudioManager.ACTION_AUDIO_BECOMING_NOISY.equals(intentAction)) {
        if (PreferencesUtility.getInstance(context).pauseEnabledOnDetach())
            startService(context, MusicService.CMDPAUSE);
    } else if (Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
        final KeyEvent event = intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
        if (event == null) {
            return;
        }/*from   ww  w .j  a  v a2  s.c om*/

        final int keycode = event.getKeyCode();
        final int action = event.getAction();
        final long eventtime = event.getEventTime();

        String command = null;
        switch (keycode) {
        case KeyEvent.KEYCODE_MEDIA_STOP:
            command = MusicService.CMDSTOP;
            break;
        case KeyEvent.KEYCODE_HEADSETHOOK:
        case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
            command = MusicService.CMDTOGGLEPAUSE;
            break;
        case KeyEvent.KEYCODE_MEDIA_NEXT:
            command = MusicService.CMDNEXT;
            break;
        case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
            command = MusicService.CMDPREVIOUS;
            break;
        case KeyEvent.KEYCODE_MEDIA_PAUSE:
            command = MusicService.CMDPAUSE;
            break;
        case KeyEvent.KEYCODE_MEDIA_PLAY:
            command = MusicService.CMDPLAY;
            break;
        }
        if (command != null) {
            if (action == KeyEvent.ACTION_DOWN) {
                if (mDown) {
                    if (MusicService.CMDTOGGLEPAUSE.equals(command) || MusicService.CMDPLAY.equals(command)) {
                        if (mLastClickTime != 0 && eventtime - mLastClickTime > LONG_PRESS_DELAY) {
                            acquireWakeLockAndSendMessage(context,
                                    mHandler.obtainMessage(MSG_LONGPRESS_TIMEOUT, context), 0);
                        }
                    }
                } else if (event.getRepeatCount() == 0) {

                    if (keycode == KeyEvent.KEYCODE_HEADSETHOOK) {
                        if (eventtime - mLastClickTime >= DOUBLE_CLICK) {
                            mClickCounter = 0;
                        }

                        mClickCounter++;
                        if (DEBUG)
                            Log.v(TAG, "Got headset click, count = " + mClickCounter);
                        mHandler.removeMessages(MSG_HEADSET_DOUBLE_CLICK_TIMEOUT);

                        Message msg = mHandler.obtainMessage(MSG_HEADSET_DOUBLE_CLICK_TIMEOUT, mClickCounter, 0,
                                context);

                        long delay = mClickCounter < 3 ? DOUBLE_CLICK : 0;
                        if (mClickCounter >= 3) {
                            mClickCounter = 0;
                        }
                        mLastClickTime = eventtime;
                        acquireWakeLockAndSendMessage(context, msg, delay);
                    } else {
                        startService(context, command);
                    }
                    mLaunched = false;
                    mDown = true;
                }
            } else {
                mHandler.removeMessages(MSG_LONGPRESS_TIMEOUT);
                mDown = false;
            }
            if (isOrderedBroadcast()) {
                abortBroadcast();
            }
            releaseWakeLockIfHandlerIdle();
        }
    }
}

From source file:org.easyaccess.phonedialer.CallStateService.java

@Override
public void onCreate() {

    telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
    callStateListener = new CallStateListener();
    callState = telephonyManager.getCallState();
    telephonyManager.listen(callStateListener, PhoneStateListener.LISTEN_CALL_STATE);
    callState = telephonyManager.getCallState();
    broadcaster = LocalBroadcastManager.getInstance(this);

    tts = new TextToSpeech(this, this);

    this.bReceiver = new BroadcastReceiver() {
        @Override/*from w  w w .  j  a v  a2s  .co m*/
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Utils.INCOMING_CALL)) {

                /**
                 * Extentia : 
                 * As per the security guidelines third party apps can't receive/answer call programmatically 
                 * unless its a system app. So user must need to use default app to receive/answer call. 
                 * Hiding below piece of code to display default app to answer call.
                 * * */
                //               cxt = context;
                //               String number = intent.getStringExtra("message");
                //               callingDetails = new ContactManager(getBaseContext())
                //                     .getNameFromNumber(number);
                //               // play ringtone
                //               // get custom ringtone
                //               playRingtone(number);
                //               // announce number
                //               // Display Calling Activity in order to receive key events
                //               Utils.callingDetails = callingDetails;
                //               myIntent = new Intent(getBaseContext(), CallingScreen.class);
                //               myIntent.putExtra("type", Utils.INCOMING);
                //               myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                //               
                //               new Handler().postDelayed(new Runnable() {
                //                  @Override
                //                  public void run() {
                //                     startActivity(myIntent);
                //                  }
                //               }, 2000);

            } else if (Intent.ACTION_NEW_OUTGOING_CALL.equals(intent.getAction())) {
                // new outgoing call
                final String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
                callingDetails = new ContactManager(getBaseContext()).getNameFromNumber(number);
                Utils.callingDetails = callingDetails;
            }
        }
    };

    LocalBroadcastManager.getInstance(this).registerReceiver((this.bReceiver),
            new IntentFilter(Utils.INCOMING_CALL));
    LocalBroadcastManager.getInstance(this).registerReceiver((this.bReceiver),
            new IntentFilter("android.intent.action.PHONE_STATE"));
    if (Accelerometer.isSupported(this)) {
        // Start Accelerometer Listening
        Accelerometer.startListening(this);
    }

    MediaButton_Receiver mediaReceiver = new MediaButton_Receiver();
    IntentFilter filterVolume = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
    registerReceiver(mediaReceiver, filterVolume);

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

From source file:org.opensilk.music.playback.service.PlaybackService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent != null) {
        String action = intent.getAction();
        if (Intent.ACTION_MEDIA_BUTTON.equals(action)) {
            mMediaSession.getController()
                    .dispatchMediaButtonEvent(intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT));
        } else {//from   ww  w.ja  v  a2 s  .  co  m
            handleIntentCommand(intent);
        }
        if (intent.getBooleanExtra(FROM_MEDIA_BUTTON, false)) {
            MediaButtonIntentReceiver.completeWakefulIntent(intent);
        }
    }
    return START_STICKY;
}

From source file:com.devbrackets.android.exomedia.EMLockScreen.java

private PendingIntent getMediaButtonReceiverPendingIntent(ComponentName componentName) {
    Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
    mediaButtonIntent.setComponent(componentName);

    mediaButtonIntent.putExtra(RECEIVER_EXTRA_CLASS, mediaServiceClass.getName());
    return PendingIntent.getBroadcast(context, 0, mediaButtonIntent, PendingIntent.FLAG_CANCEL_CURRENT);
}

From source file:de.qspool.clementineremote.backend.ClementinePlayerConnection.java

/**
 * Try to connect to Clementine/*from   w w  w .  ja  va  2 s.co m*/
 *
 * @param message The Request Object. Stores the ip to connect to.
 */
@Override
public boolean createConnection(ClementineMessage message) {
    // Reset the connected flag
    mLastKeepAlive = 0;

    // Now try to connect and set the input and output streams
    boolean connected = super.createConnection(message);

    // Check if Clementine dropped the connection.
    // Is possible when we connect from a public ip and clementine rejects it
    if (connected && !mSocket.isClosed()) {
        // Now we are connected
        mLastSong = null;
        mLastState = App.mClementine.getState();

        // Setup the MediaButtonReceiver and the RemoteControlClient
        registerRemoteControlClient();

        // Register MediaButtonReceiver
        IntentFilter filter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
        App.mApp.registerReceiver(mMediaButtonBroadcastReceiver, filter);

        updateNotification();

        // The device shall be awake
        mWakeLock.acquire();

        // We can now reconnect MAX_RECONNECTS times when
        // we get a keep alive timeout
        mLeftReconnects = MAX_RECONNECTS;

        // Set the current time to last keep alive
        setLastKeepAlive(System.currentTimeMillis());

        // Until we get a new connection request from ui,
        // don't request the first data a second time
        mRequestConnect = ClementineMessageFactory.buildConnectMessage(message.getIp(), message.getPort(),
                message.getMessage().getRequestConnect().getAuthCode(), false,
                message.getMessage().getRequestConnect().getDownloader());

        // Save started transmitted bytes
        int uid = App.mApp.getApplicationInfo().uid;
        mStartTx = TrafficStats.getUidTxBytes(uid);
        mStartRx = TrafficStats.getUidRxBytes(uid);

        mStartTime = new Date().getTime();

        // Create a new thread for reading data from Clementine.
        // This is done blocking, so we receive the data directly instead of
        // waiting for the handler and still be able to send commands directly.
        mIncomingThread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (isConnected() && !mIncomingThread.isInterrupted()) {
                    checkKeepAlive();

                    ClementineMessage m = getProtoc();
                    if (!m.isErrorMessage() || m.getErrorMessage() != ErrorMessage.TIMEOUT) {
                        Message msg = Message.obtain();
                        msg.obj = m;
                        msg.arg1 = PROCESS_PROTOC;
                        mHandler.sendMessage(msg);
                    }
                }
                Log.d(TAG, "reading thread exit");
            }
        });
        mIncomingThread.start();

    } else {
        sendUiMessage(new ClementineMessage(ErrorMessage.NO_CONNECTION));
    }

    return connected;
}

From source file:com.teocci.utubinbg.BackgroundAudioService.java

/**
 * Initializes media sessions and receives media events
 *//* w  w w  .ja  va2 s  . c o m*/
private void initMediaSessions() {
    // Make sure the media player will acquire a wake-lock while playing. If we don't do
    // that, the CPU might go to sleep while the song is playing, causing playback to stop.
    //
    // Remember that to use this, we have to declare the android.permission.WAKE_LOCK
    // permission in AndroidManifest.xml.
    mMediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);

    ComponentName eventReceiver = new ComponentName(getApplicationContext().getPackageName(),
            MediaButtonIntentReceiver.class.getName());
    PendingIntent buttonReceiverIntent = PendingIntent.getBroadcast(getApplicationContext(), 0,
            new Intent(Intent.ACTION_MEDIA_BUTTON), PendingIntent.FLAG_UPDATE_CURRENT);

    mSession = new MediaSessionCompat(getApplicationContext(), "simple player session", eventReceiver,
            buttonReceiverIntent);

    try {
        mController = new MediaControllerCompat(getApplicationContext(), mSession.getSessionToken());

        mSession.setCallback(new MediaSessionCompat.Callback() {
            @Override
            public void onPlay() {
                super.onPlay();
                buildNotification(generateAction(android.R.drawable.ic_media_pause, "Pause", ACTION_PAUSE));
            }

            @Override
            public void onPause() {

                super.onPause();
                pauseVideo();
                buildNotification(generateAction(android.R.drawable.ic_media_play, "Play", ACTION_PLAY));
            }

            @Override
            public void onSkipToNext() {
                super.onSkipToNext();
                if (!isStarting) {
                    playNext();
                }
                buildNotification(generateAction(android.R.drawable.ic_media_pause, "Pause", ACTION_PAUSE));
            }

            @Override
            public void onSkipToPrevious() {
                super.onSkipToPrevious();
                if (!isStarting) {
                    playPrevious();
                }
                buildNotification(generateAction(android.R.drawable.ic_media_pause, "Pause", ACTION_PAUSE));
            }

            @Override
            public void onStop() {
                super.onStop();
                stopPlayer();
                //remove notification and stop service
                NotificationManager notificationManager = (NotificationManager) getApplicationContext()
                        .getSystemService(Context.NOTIFICATION_SERVICE);
                notificationManager.cancel(1);
                Intent intent = new Intent(getApplicationContext(), BackgroundAudioService.class);
                stopService(intent);
            }

            @Override
            public void onSetRating(RatingCompat rating) {
                super.onSetRating(rating);
            }
        });
    } catch (RemoteException re) {
        re.printStackTrace();
    }
}

From source file:com.andreadec.musicplayer.MusicService.java

/**
 * Called when the service is created./*w  w w  . j  a  va  2  s . c  om*/
 */
@Override
public void onCreate() {
    PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MusicServiceWakelock");

    // Initialize the telephony manager
    telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    phoneStateListener = new MusicPhoneStateListener();
    notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    // Initialize pending intents
    quitPendingIntent = PendingIntent.getBroadcast(this, 0, new Intent("com.andreadec.musicplayer.quit"), 0);
    previousPendingIntent = PendingIntent.getBroadcast(this, 0,
            new Intent("com.andreadec.musicplayer.previous"), 0);
    playpausePendingIntent = PendingIntent.getBroadcast(this, 0,
            new Intent("com.andreadec.musicplayer.playpause"), 0);
    nextPendingIntent = PendingIntent.getBroadcast(this, 0, new Intent("com.andreadec.musicplayer.next"), 0);
    pendingIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP),
            PendingIntent.FLAG_UPDATE_CURRENT);

    // Read saved user preferences
    preferences = PreferenceManager.getDefaultSharedPreferences(this);

    // Initialize the media player
    mediaPlayer = new MediaPlayer();
    mediaPlayer.setOnCompletionListener(this);
    mediaPlayer.setWakeMode(this, PowerManager.PARTIAL_WAKE_LOCK); // Enable the wake lock to keep CPU running when the screen is switched off

    shuffle = preferences.getBoolean(Constants.PREFERENCE_SHUFFLE, Constants.DEFAULT_SHUFFLE);
    repeat = preferences.getBoolean(Constants.PREFERENCE_REPEAT, Constants.DEFAULT_REPEAT);
    repeatAll = preferences.getBoolean(Constants.PREFERENCE_REPEATALL, Constants.DEFAULT_REPEATALL);
    try { // This may fail if the device doesn't support bass boost
        bassBoost = new BassBoost(1, mediaPlayer.getAudioSessionId());
        bassBoost.setEnabled(
                preferences.getBoolean(Constants.PREFERENCE_BASSBOOST, Constants.DEFAULT_BASSBOOST));
        setBassBoostStrength(preferences.getInt(Constants.PREFERENCE_BASSBOOSTSTRENGTH,
                Constants.DEFAULT_BASSBOOSTSTRENGTH));
        bassBoostAvailable = true;
    } catch (Exception e) {
        bassBoostAvailable = false;
    }
    try { // This may fail if the device doesn't support equalizer
        equalizer = new Equalizer(1, mediaPlayer.getAudioSessionId());
        equalizer.setEnabled(
                preferences.getBoolean(Constants.PREFERENCE_EQUALIZER, Constants.DEFAULT_EQUALIZER));
        setEqualizerPreset(
                preferences.getInt(Constants.PREFERENCE_EQUALIZERPRESET, Constants.DEFAULT_EQUALIZERPRESET));
        equalizerAvailable = true;
    } catch (Exception e) {
        equalizerAvailable = false;
    }
    random = new Random(System.nanoTime()); // Necessary for song shuffle

    shakeListener = new ShakeListener(this);
    if (preferences.getBoolean(Constants.PREFERENCE_SHAKEENABLED, Constants.DEFAULT_SHAKEENABLED)) {
        shakeListener.enable();
    }

    telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE); // Start listen for telephony events

    // Inizialize the audio manager
    audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    mediaButtonReceiverComponent = new ComponentName(getPackageName(), MediaButtonReceiver.class.getName());
    audioManager.registerMediaButtonEventReceiver(mediaButtonReceiverComponent);
    audioManager.requestAudioFocus(null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);

    // Initialize remote control client
    if (Build.VERSION.SDK_INT >= 14) {
        icon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
        Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
        mediaButtonIntent.setComponent(mediaButtonReceiverComponent);
        PendingIntent mediaPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0,
                mediaButtonIntent, 0);

        remoteControlClient = new RemoteControlClient(mediaPendingIntent);
        remoteControlClient.setTransportControlFlags(RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE
                | RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS | RemoteControlClient.FLAG_KEY_MEDIA_NEXT);
        audioManager.registerRemoteControlClient(remoteControlClient);
    }

    updateNotificationMessage();

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction("com.andreadec.musicplayer.quit");
    intentFilter.addAction("com.andreadec.musicplayer.previous");
    intentFilter.addAction("com.andreadec.musicplayer.previousNoRestart");
    intentFilter.addAction("com.andreadec.musicplayer.playpause");
    intentFilter.addAction("com.andreadec.musicplayer.next");
    intentFilter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
    broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals("com.andreadec.musicplayer.quit")) {
                sendBroadcast(new Intent("com.andreadec.musicplayer.quitactivity"));
                stopSelf();
                return;
            } else if (action.equals("com.andreadec.musicplayer.previous")) {
                previousItem(false);
            } else if (action.equals("com.andreadec.musicplayer.previousNoRestart")) {
                previousItem(true);
            } else if (action.equals("com.andreadec.musicplayer.playpause")) {
                playPause();
            } else if (action.equals("com.andreadec.musicplayer.next")) {
                nextItem();
            } else if (action.equals(AudioManager.ACTION_AUDIO_BECOMING_NOISY)) {
                if (preferences.getBoolean(Constants.PREFERENCE_STOPPLAYINGWHENHEADSETDISCONNECTED,
                        Constants.DEFAULT_STOPPLAYINGWHENHEADSETDISCONNECTED)) {
                    pause();
                }
            }
        }
    };
    registerReceiver(broadcastReceiver, intentFilter);

    if (!isPlaying()) {
        loadLastSong();
    }

    startForeground(Constants.NOTIFICATION_MAIN, notification);
}