Example usage for android.app PendingIntent FLAG_UPDATE_CURRENT

List of usage examples for android.app PendingIntent FLAG_UPDATE_CURRENT

Introduction

In this page you can find the example usage for android.app PendingIntent FLAG_UPDATE_CURRENT.

Prototype

int FLAG_UPDATE_CURRENT

To view the source code for android.app PendingIntent FLAG_UPDATE_CURRENT.

Click Source Link

Document

Flag indicating that if the described PendingIntent already exists, then keep it but replace its extra data with what is in this new Intent.

Usage

From source file:com.benext.thibault.appsample.notification.builder.NotificationBuilder.java

private static ArrayList<android.support.v4.app.NotificationCompat.Action> getActionsSample(Context context) {
    ArrayList<NotificationCompat.Action> actions = new ArrayList<>();

    //User click on action triggers broadcast which is received by WearActionReceiver.class
    //Put notification id and flag WEAR_ACTION.
    //Using these parameters WearActionReceiver.class will know which action was clicked
    Intent notifyNextTimeIntent = new Intent(context, WearActionReceiver.class);
    notifyNextTimeIntent.putExtra(WearActionReceiver.NOTIFICATION_ID_STRING, NOTIFICATION_ID);
    notifyNextTimeIntent.putExtra(WearActionReceiver.WEAR_ACTION, WearActionReceiver.SNOOZE_NOTIFICATION);

    PendingIntent pendingIntentNotify = PendingIntent.getBroadcast(context, WEAR_REQUEST_CODE,
            notifyNextTimeIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    //text shown in notification
    String notifyAgainText = context.getString(R.string.notification_next_in_line);

    //Wear action - this action will be shown only on Android Wear devices
    //Set action icon, text and pending intent which will be executed on click
    //When user clicks on this icon he will "snooze" notification
    actions.add(//from  w ww.j  a va 2s.com
            new NotificationCompat.Action.Builder(R.drawable.resto_icn, notifyAgainText, pendingIntentNotify)
                    .build());

    return actions;
}

From source file:com.begentgroup.miniproject.gcm.MyGcmListenerService.java

private void sendNotification(ChatMessage m) {
    Intent intent = new Intent(this, SplashActivity.class);
    intent.putExtra(ChatActivity.EXTRA_USER, m.getSender());
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.ic_launcher).setTicker("Chat Message")
            .setContentTitle(m.getSender().getUserName()).setContentText(m.getMessage()).setAutoCancel(true)
            .setDefaults(NotificationCompat.DEFAULT_ALL).setContentIntent(pendingIntent);

    NotificationManager notificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);

    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());

}

From source file:com.procasy.dubarah_nocker.gcm.MyGcmPushReceiver.java

/**
 * Called when message is received./*from w  w  w .j av a2  s .c  o  m*/
 *
 * @param from   SenderID of the sender.
 * @param bundle Data bundle containing message data as key/value pairs.
 *               For Set of keys use data.keySet().
 */

@Override
public void onMessageReceived(String from, Bundle bundle) {

    MainActivity.getInstance().updateNotification();

    try {

        Log.e("notify_gcm", "success , type = " + bundle.toString());

        switch (bundle.getString(GCM_TAG)) {
        case "GENERAL": {
            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.hourly_logo).setContentTitle(bundle.getString(TITLE_TAG))
                    .setContentText(bundle.getString(DESC_TAG));
            Intent resultIntent = new Intent(this, MainActivity.class);
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
            stackBuilder.addParentStack(MainActivity.class);
            stackBuilder.addNextIntent(resultIntent);
            PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            mBuilder.setContentIntent(resultPendingIntent);
            mBuilder.setDefaults(
                    Notification.DEFAULT_SOUND | Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE);
            NotificationManager mNotificationManager = (NotificationManager) getSystemService(
                    Context.NOTIFICATION_SERVICE);
            mNotificationManager.notify(12, mBuilder.build());
            mNotification = new com.procasy.dubarah_nocker.Helper.Notification(getApplicationContext());
            mNotification.open();
            try {
                ContentValues contentValues = new ContentValues();
                contentValues.put(mNotification.COL_notification_type, GENERAL_TAG);
                contentValues.put(mNotification.COL_notfication_status, 0);
                contentValues.put(mNotification.COL_notfication_title, bundle.getString(TITLE_TAG));
                contentValues.put(mNotification.COL_notfication_desc, bundle.getString(DESC_TAG));
                contentValues.put(mNotification.COL_notfication_content, bundle.getString(CONTENT_TAG));
                mNotification.insertEntry(contentValues);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                mNotification.close();
            }
            break;
        }

        case "HELP": {
            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.hourly_logo).setContentTitle(bundle.getString(TITLE_TAG))
                    .setContentText(bundle.getString(DESC_TAG));
            Intent resultIntent = new Intent(this, MainActivity.class);
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
            stackBuilder.addParentStack(MainActivity.class);
            stackBuilder.addNextIntent(resultIntent);
            PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            mBuilder.setContentIntent(resultPendingIntent);
            mBuilder.setDefaults(
                    Notification.DEFAULT_SOUND | Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE);
            NotificationManager mNotificationManager = (NotificationManager) getSystemService(
                    Context.NOTIFICATION_SERVICE);
            mNotificationManager.notify(12, mBuilder.build());
            mNotification = new com.procasy.dubarah_nocker.Helper.Notification(getApplicationContext());
            mNotification.open();
            try {
                ContentValues contentValues = new ContentValues();
                contentValues.put(mNotification.COL_notification_type, HELP_TAG);
                contentValues.put(mNotification.COL_notfication_status, 0);
                contentValues.put(mNotification.COL_notfication_title, bundle.getString(TITLE_TAG));
                contentValues.put(mNotification.COL_notfication_desc, bundle.getString(DESC_TAG));
                contentValues.put(mNotification.COL_notfication_content, bundle.getString(CONTENT_TAG));
                mNotification.insertEntry(contentValues);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                mNotification.close();
            }
            JSONObject content = new JSONObject(bundle.getString("content"));
            JSONObject hr = content.getJSONObject("hr");
            JSONArray album = content.getJSONArray("album");
            System.out.println(content.getInt("hr_id"));
            System.out.println(content.toString());
            Bundle bundle1 = new Bundle();
            bundle1.putString("hr_id", hr.getString("hr_id"));
            bundle1.putString("hr_user_id", hr.getString("hr_user_id"));
            bundle1.putString("hr_description", hr.getString("hr_description"));
            bundle1.putString("hr_est_date", hr.getString("hr_est_date"));
            bundle1.putString("hr_est_time", hr.getString("hr_est_time"));
            bundle1.putString("hr_skill_id", hr.getString("hr_skill_id"));
            bundle1.putString("hr_ua_id", hr.getString("hr_ua_id"));
            bundle1.putString("hr_voice_record", hr.getString("hr_voice_record"));
            bundle1.putString("hr_language", hr.getString("hr_language"));
            bundle1.putString("hr_lat", hr.getString("hr_lat"));
            bundle1.putString("hr_lon", hr.getString("hr_lon"));
            bundle1.putString("hr_address", hr.getString("hr_address"));
            ArrayList<String> array = new ArrayList<>();
            for (int i = 0; i < album.length(); i++) {
                JSONObject object = album.getJSONObject(i);
                array.add(object.getString("ahr_img"));
            }
            bundle1.putStringArrayList("album", array);

            Intent intent = (new Intent(getApplicationContext(), JobRequestActivity.class));
            intent.putExtras(bundle1);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            getApplicationContext().startActivity(intent);

            break;
        }

        case "APPOINTEMENT": {
            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.hourly_logo).setContentTitle(bundle.getString(TITLE_TAG))
                    .setContentText(bundle.getString(DESC_TAG));
            Intent resultIntent = new Intent(this, MainActivity.class);
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
            stackBuilder.addParentStack(MainActivity.class);
            stackBuilder.addNextIntent(resultIntent);
            PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            mBuilder.setContentIntent(resultPendingIntent);
            mBuilder.setDefaults(
                    Notification.DEFAULT_SOUND | Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE);
            NotificationManager mNotificationManager = (NotificationManager) getSystemService(
                    Context.NOTIFICATION_SERVICE);
            mNotificationManager.notify(12, mBuilder.build());
            mNotification = new com.procasy.dubarah_nocker.Helper.Notification(getApplicationContext());
            mNotification.open();
            try {
                ContentValues contentValues = new ContentValues();
                contentValues.put(mNotification.COL_notification_type, APPOINTEMENT_TAG);
                contentValues.put(mNotification.COL_notfication_status, 0);
                contentValues.put(mNotification.COL_notfication_title, bundle.getString(TITLE_TAG));
                contentValues.put(mNotification.COL_notfication_desc, bundle.getString(DESC_TAG));
                contentValues.put(mNotification.COL_notfication_content, bundle.getString(CONTENT_TAG));
                mNotification.insertEntry(contentValues);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                mNotification.close();
            }
            break;
        }

        case "QOUTA_USER": {
            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.hourly_logo).setContentTitle(bundle.getString(TITLE_TAG))
                    .setContentText(bundle.getString(DESC_TAG));
            Intent resultIntent = new Intent(this, MainActivity.class);
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
            stackBuilder.addParentStack(MainActivity.class);
            stackBuilder.addNextIntent(resultIntent);
            PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            mBuilder.setContentIntent(resultPendingIntent);
            mBuilder.setDefaults(
                    Notification.DEFAULT_SOUND | Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE);
            NotificationManager mNotificationManager = (NotificationManager) getSystemService(
                    Context.NOTIFICATION_SERVICE);
            mNotificationManager.notify(12, mBuilder.build());
            mNotification = new com.procasy.dubarah_nocker.Helper.Notification(getApplicationContext());
            mNotification.open();
            try {
                ContentValues contentValues = new ContentValues();
                contentValues.put(mNotification.COL_notification_type, USER_Qouta_TAG);
                contentValues.put(mNotification.COL_notfication_status, 0);
                contentValues.put(mNotification.COL_notfication_title, bundle.getString(TITLE_TAG));
                contentValues.put(mNotification.COL_notfication_desc, bundle.getString(DESC_TAG));
                contentValues.put(mNotification.COL_notfication_content, bundle.getString(CONTENT_TAG));
                mNotification.insertEntry(contentValues);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                mNotification.close();
            }
            break;
        }

        case "QOUTA_NOCKER": {
            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.hourly_logo).setContentTitle(bundle.getString(TITLE_TAG))
                    .setContentText(bundle.getString(DESC_TAG));
            Intent resultIntent = new Intent(this, MainActivity.class);
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
            stackBuilder.addParentStack(MainActivity.class);
            stackBuilder.addNextIntent(resultIntent);
            PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            mBuilder.setContentIntent(resultPendingIntent);
            mBuilder.setDefaults(
                    Notification.DEFAULT_SOUND | Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE);
            NotificationManager mNotificationManager = (NotificationManager) getSystemService(
                    Context.NOTIFICATION_SERVICE);
            mNotificationManager.notify(12, mBuilder.build());
            mNotification = new com.procasy.dubarah_nocker.Helper.Notification(getApplicationContext());
            mNotification.open();
            try {
                ContentValues contentValues = new ContentValues();
                contentValues.put(mNotification.COL_notification_type, Nocker_Qouta_TAG);
                contentValues.put(mNotification.COL_notfication_status, 0);
                contentValues.put(mNotification.COL_notfication_title, bundle.getString(TITLE_TAG));
                contentValues.put(mNotification.COL_notfication_desc, bundle.getString(DESC_TAG));
                contentValues.put(mNotification.COL_notfication_content, bundle.getString(CONTENT_TAG));
                mNotification.insertEntry(contentValues);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                mNotification.close();
            }
            break;
        }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:charlyn23.c4q.nyc.projectx.map.GeofenceIntentService.java

/**
 * Posts a notification in the notification bar when a fade_transition is detected.
 * If the user clicks the notification, control goes to the MainActivity.
 *///www . ja v  a 2s  . c  o m
private void sendNotification(String notificationDetails) {
    // Create an explicit content Intent that starts the main Activity.
    Intent notificationIntent = new Intent(this, MainActivity.class);

    // Get a PendingIntent containing the entire back stack.
    PendingIntent notificationPendingIntent = PendingIntent.getActivity(this, 0, notificationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

    // Define the notification settings.
    builder.setSmallIcon(R.mipmap.ic_launcher).setColor(Color.RED).setContentTitle(notificationDetails)
            .setContentText(getString(R.string.geofence_transition_notification_text))
            .setContentIntent(notificationPendingIntent);
    builder.setAutoCancel(true);
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(0, builder.build());
}

From source file:com.asb.spandan2014.GcmIntentService.java

private void sendNotification(String msg) {
    mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

    Intent resultIntent = new Intent(this, AlertsActivity.class);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    // Adds the back stack
    stackBuilder.addParentStack(AlertsActivity.class);
    // Adds the Intent to the top of the stack
    stackBuilder.addNextIntent(resultIntent);
    // Gets a PendingIntent containing the entire back stack
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.alerts)
            .setContentTitle(getString(R.string.spandan_update))
            .setDefaults(Notification.DEFAULT_VIBRATE | Notification.FLAG_SHOW_LIGHTS
                    | Notification.FLAG_AUTO_CANCEL | Notification.DEFAULT_LIGHTS)
            .setStyle(new NotificationCompat.BigTextStyle().bigText(msg)).setContentText(msg);

    mBuilder.setContentIntent(resultPendingIntent);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}

From source file:com.bobomee.android.common.util.NotificationUtil.java

public static NotificationCompat.Builder setActivityIntent(NotificationCompat.Builder mBuilder, Context context,
        Intent intent) {//from w  w w.j  a  va  2s. c o  m
    // ?ACTIONIntent
    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(pendingIntent);
    return mBuilder;
}

From source file:com.arellomobile.android.push.PushGCMIntentService.java

private static void generateNotification(Context context, Intent intent, Handler handler) {
    Bundle extras = intent.getExtras();//from  ww  w  . jav  a 2s  .  c o  m
    if (extras == null) {
        return;
    }

    extras.putBoolean("foregroud", GeneralUtils.isAppOnForeground(context));

    String title = (String) extras.get("title");
    String link = (String) extras.get("l");

    // empty message with no data
    Intent notifyIntent;
    if (link != null) {
        // we want main app class to be launched
        notifyIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
        notifyIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    } else {
        notifyIntent = new Intent(context, PushHandlerActivity.class);
        notifyIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);

        // pass all bundle
        notifyIntent.putExtra("pushBundle", extras);
    }

    // first string will appear on the status bar once when message is added
    CharSequence appName = context.getPackageManager().getApplicationLabel(context.getApplicationInfo());
    if (null == appName) {
        appName = "";
    }

    NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    NotificationFactory notificationFactory;

    //is this banner notification?
    String bannerUrl = (String) extras.get("b");

    //also check that notification layout has been placed in layout folder
    int layoutId = context.getResources().getIdentifier(BannerNotificationFactory.sNotificationLayout, "layout",
            context.getPackageName());

    if (layoutId != 0 && bannerUrl != null) {
        notificationFactory = new BannerNotificationFactory(context, extras, appName.toString(), title,
                PushManager.sSoundType, PushManager.sVibrateType);
    } else {
        notificationFactory = new SimpleNotificationFactory(context, extras, appName.toString(), title,
                PushManager.sSoundType, PushManager.sVibrateType);
    }
    notificationFactory.generateNotification();
    notificationFactory.addSoundAndVibrate();
    notificationFactory.addCancel();

    Notification notification = notificationFactory.getNotification();

    notification.contentIntent = PendingIntent.getActivity(context, 0, notifyIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    if (mSimpleNotification) {
        manager.notify(PushManager.MESSAGE_ID, notification);
    } else {
        manager.notify(PushManager.MESSAGE_ID++, notification);
    }

    generateBroadcast(context, extras);
}

From source file:hk.edu.cityu.appslab.calmessenger.gcm.GcmIntentService.java

protected void sendNotification(String title, String msg, Intent intent) {
    mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

    PendingIntent contentIntent;// w w  w  .ja v  a  2  s  .c  o  m
    if (intent == null) {
        contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, ConversationActivity.class), 0);
    } else {
        contentIntent = TaskStackBuilder.create(this).addNextIntentWithParentStack(intent).getPendingIntent(0,
                PendingIntent.FLAG_UPDATE_CURRENT);
        // contentIntent = PendingIntent.getActivity(this, 0, intent,
        // PendingIntent.FLAG_CANCEL_CURRENT);
    }

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher).setContentTitle(title)
            .setStyle(new NotificationCompat.BigTextStyle().bigText(msg)).setContentText(msg)
            .setAutoCancel(true);

    mBuilder.setContentIntent(contentIntent);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}

From source file:can.yrt.onebusaway.tripservice.NotifierTask.java

private Notification createNotification(Uri alertUri) {
    //Log.d(TAG, "Creating notification for alert: " + alertUri);
    Intent deleteIntent = new Intent(mContext, TripService.class);
    deleteIntent.setAction(TripService.ACTION_CANCEL);
    deleteIntent.setData(alertUri);//from www  . j  a  v  a  2  s . co  m

    return new NotificationCompat.Builder(mContext).setSmallIcon(R.drawable.ic_stat_notification)
            .setDefaults(Notification.DEFAULT_ALL).setOnlyAlertOnce(true)
            //.setLights(0xFF00FF00, 1000, 1000)
            //.setVibrate(VIBRATE_PATTERN)
            .setDeleteIntent(
                    PendingIntent.getService(mContext, 0, deleteIntent, PendingIntent.FLAG_UPDATE_CURRENT))
            .getNotification();
}

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

/**
 * Called when the service is created./*from ww  w  . j  av a 2  s.c o m*/
 */
@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);
}