Example usage for android.support.v4.app TaskStackBuilder getPendingIntent

List of usage examples for android.support.v4.app TaskStackBuilder getPendingIntent

Introduction

In this page you can find the example usage for android.support.v4.app TaskStackBuilder getPendingIntent.

Prototype

public PendingIntent getPendingIntent(int requestCode, int flags) 

Source Link

Document

Obtain a PendingIntent for launching the task constructed by this builder so far.

Usage

From source file:org.exfio.csyncdroid.syncadapter.WeaveSyncAdapter.java

protected void displayNotificationReceivedClientAuth(String accountName, ClientAuthRequestMessage msg) {
    Log.d(TAG, "displayNotificationApproveClientAuth()");

    int notificationId = 111;

    // Invoking the default notification service
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this.getContext());

    mBuilder.setContentTitle("Authentication request received");
    mBuilder.setContentText(String.format("'%s' is requesting authentication for CucumberSync account '%s'",
            msg.getClientName(), accountName));
    mBuilder.setTicker("Authentication request received");
    mBuilder.setSmallIcon(R.drawable.ic_launcher);

    // Increase notification number every time a new notification arrives 
    mBuilder.setNumber(1);/*from  w w w .j a v  a 2 s.c om*/

    // Creates an explicit intent for an Activity in your app 
    Intent resultIntent = new Intent(this.getContext(), ReceivedClientAuth.class);
    resultIntent.putExtra(ReceivedClientAuth.KEY_EXTRA_NOTIFICATIONID, notificationId);
    resultIntent.putExtra(ReceivedClientAuth.KEY_EXTRA_ACCOUNTNAME, accountName);
    resultIntent.putExtra(ReceivedClientAuth.KEY_EXTRA_SESSIONID, msg.getMessageSessionId());
    resultIntent.putExtra(ReceivedClientAuth.KEY_EXTRA_CLIENTNAME, msg.getClientName());

    //This ensures that navigating backward from the Activity leads out of the app to Home page
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this.getContext());

    // Adds the back stack for the Intent
    stackBuilder.addParentStack(ReceivedClientAuth.class);

    // Adds the Intent that starts the Activity to the top of the stack
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_ONE_SHOT //can only be used once
    );

    // start the activity when the user clicks the notification text
    mBuilder.setContentIntent(resultPendingIntent);

    NotificationManager nm = (NotificationManager) this.getContext()
            .getSystemService(Context.NOTIFICATION_SERVICE);

    // pass the Notification object to the system 
    nm.notify(notificationId, mBuilder.build());
}

From source file:com.mb.android.playbackmediator.notification.VideoCastNotificationService.java

private RemoteViews build(SessionInfoDto info, Bitmap bitmap, boolean isPlaying)
        throws CastException, TransientNetworkDisconnectionException, NoConnectionException {

    if (info.getNowPlayingItem() == null) {
        return null;
    }//from   w  w w .jav  a  2s.  c o  m

    if (mIsLollipopOrAbove) {
        buildForLollipopAndAbove(info, bitmap, isPlaying);
        return null;
    }

    Bundle mediaWrapper = Utils.fromMediaInfo(mCastManager.getRemoteMediaInformation());

    mTargetActivity = RemoteControlActivity.class;

    Intent contentIntent = new Intent(this, mTargetActivity);
    contentIntent.putExtra("LAUNCHED_BY_NOTIFICATION", true);

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);

    stackBuilder.addParentStack(mTargetActivity);

    stackBuilder.addNextIntent(contentIntent);
    if (stackBuilder.getIntentCount() > 1) {
        stackBuilder.editIntentAt(1).putExtra("media", mediaWrapper);
    }

    // Gets a PendingIntent containing the entire back stack
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(NOTIFICATION_ID,
            PendingIntent.FLAG_UPDATE_CURRENT);

    RemoteViews rv = new RemoteViews(getPackageName(), R.layout.custom_notification);
    if (mIsIcsOrAbove) {
        addPendingIntents(rv, isPlaying, info);
    }
    if (null != bitmap) {
        rv.setImageViewBitmap(R.id.iconView, bitmap);
    }
    rv.setTextViewText(R.id.titleView, info.getNowPlayingItem().getName());
    String castingTo = getResources().getString(R.string.casting_to_device, mCastManager.getDeviceName());
    rv.setTextViewText(R.id.subTitleView, castingTo);
    mNotification = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_stat_action_notification)
            .setContentIntent(resultPendingIntent).setContent(rv).setAutoCancel(false).setOngoing(true).build();

    // to get around a bug in GB version, we add the following line
    // see https://code.google.com/p/android/issues/detail?id=30495
    mNotification.contentView = rv;

    return rv;
}

From source file:org.yuttadhammo.BodhiTimer.TimerReceiver.java

@Override
public void onReceive(Context context, Intent pintent) {
    Log.v(TAG, "ALARM: received alarm");

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

    if (player != null) {
        Log.v(TAG, "Releasing media player...");
        try {//from   w w  w.j  a v a2 s .c o  m
            player.release();
            player = null;
        } catch (Exception e) {
            e.printStackTrace();
            player = null;
        } finally {
            // do nothing
        }
    }

    // Cancel notification and return...
    if (CANCEL_NOTIFICATION.equals(pintent.getAction())) {
        Log.v(TAG, "Cancelling notification...");

        mNM.cancelAll();
        return;
    }

    // ...or display a new one

    Log.v(TAG, "Showing notification...");

    player = new MediaPlayer();

    int setTime = pintent.getIntExtra("SetTime", 0);
    String setTimeStr = TimerUtils.time2humanStr(context, setTime);
    Log.v(TAG, "Time: " + setTime);

    CharSequence text = context.getText(R.string.Notification);
    CharSequence textLatest = String.format(context.getString(R.string.timer_for_x), setTimeStr);

    // Load the settings 
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    boolean led = prefs.getBoolean("LED", true);
    boolean vibrate = prefs.getBoolean("Vibrate", true);
    String notificationUri = "";

    boolean useAdvTime = prefs.getBoolean("useAdvTime", false);
    String advTimeString = prefs.getString("advTimeString", "");
    String[] advTime = null;
    int advTimeIndex = 1;

    if (useAdvTime && advTimeString.length() > 0) {
        advTime = advTimeString.split("\\^");
        advTimeIndex = prefs.getInt("advTimeIndex", 1);
        String[] thisAdvTime = advTime[advTimeIndex - 1].split("#"); // will be of format timeInMs#pathToSound

        if (thisAdvTime.length == 3)
            notificationUri = thisAdvTime[1];
        if (notificationUri.equals("sys_def"))
            notificationUri = prefs.getString("NotificationUri",
                    "android.resource://org.yuttadhammo.BodhiTimer/" + R.raw.bell);
    } else
        notificationUri = prefs.getString("NotificationUri",
                "android.resource://org.yuttadhammo.BodhiTimer/" + R.raw.bell);

    Log.v(TAG, "notification uri: " + notificationUri);

    if (notificationUri.equals("system"))
        notificationUri = prefs.getString("SystemUri", "");
    else if (notificationUri.equals("file"))
        notificationUri = prefs.getString("FileUri", "");
    else if (notificationUri.equals("tts")) {
        notificationUri = "";
        final String ttsString = prefs.getString("tts_string", context.getString(R.string.timer_done));
        Intent ttsIntent = new Intent(context, TTSService.class);
        ttsIntent.putExtra("spoken_text", ttsString);
        context.startService(ttsIntent);
    }

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context.getApplicationContext())
            .setSmallIcon(R.drawable.notification).setContentTitle(text).setContentText(textLatest);

    Uri uri = null;

    // Play a sound!
    if (!notificationUri.equals(""))
        uri = Uri.parse(notificationUri);

    // Vibrate
    if (vibrate && uri == null) {
        mBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
    }

    // Have a light
    if (led) {
        mBuilder.setLights(0xff00ff00, 300, 1000);
    }

    mBuilder.setAutoCancel(true);

    // Creates an explicit intent for an Activity in your app
    Intent resultIntent = new Intent(context, TimerActivity.class);

    // The stack builder object will contain an artificial back stack for the
    // started Activity.
    // This ensures that navigating backward from the Activity leads out of
    // your application to the Home screen.
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    // Adds the back stack for the Intent (but not the Intent itself)
    stackBuilder.addParentStack(TimerActivity.class);
    // Adds the Intent that starts the Activity to the top of the stack
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(resultPendingIntent);
    NotificationManager mNotificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);

    // Create intent for cancelling the notification
    Context appContext = context.getApplicationContext();
    Intent intent = new Intent(appContext, TimerReceiver.class);
    intent.setAction(CANCEL_NOTIFICATION);

    // Cancel the pending cancellation and create a new one
    PendingIntent pendingCancelIntent = PendingIntent.getBroadcast(appContext, 0, intent,
            PendingIntent.FLAG_CANCEL_CURRENT);

    if (uri != null) {

        //remove notification sound
        mBuilder.setSound(null);

        try {
            if (player != null && player.isPlaying()) {
                player.release();
                player = new MediaPlayer();
            }

            int currVolume = prefs.getInt("tone_volume", 0);
            if (currVolume != 0) {
                float log1 = (float) (Math.log(100 - currVolume) / Math.log(100));
                player.setVolume(1 - log1, 1 - log1);
            }
            player.setDataSource(context, uri);
            player.prepare();
            player.setLooping(false);
            player.setOnCompletionListener(new OnCompletionListener() {

                @Override
                public void onCompletion(MediaPlayer mp) {
                    // TODO Auto-generated method stub
                    mp.release();
                }

            });
            player.start();
            if (vibrate) {
                Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
                vibrator.vibrate(1000);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    if (prefs.getBoolean("AutoClear", false)) {
        // Determine duration of notification sound
        int duration = 5000;
        if (uri != null) {
            MediaPlayer cancelPlayer = new MediaPlayer();
            try {
                cancelPlayer.setDataSource(context, uri);
                cancelPlayer.prepare();
                duration = Math.max(duration, cancelPlayer.getDuration() + 2000);
            } catch (java.io.IOException ex) {
                Log.e(TAG, "Cannot get sound duration: " + ex);
                duration = 30000; // on error, default to 30 seconds
            } finally {
                cancelPlayer.release();
            }
            cancelPlayer.release();
        }
        Log.v(TAG, "Notification duration: " + duration + " ms");
        // Schedule cancellation
        AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmMgr.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + duration,
                pendingCancelIntent);
    }

    if (useAdvTime && advTimeString.length() > 0) {
        Intent broadcast = new Intent();

        SharedPreferences.Editor editor = prefs.edit();
        if (advTimeIndex < advTime.length) {
            editor.putInt("advTimeIndex", advTimeIndex + 1);

            String[] thisAdvTime = advTime[advTimeIndex].split("#"); // will be of format timeInMs#pathToSound

            int time = Integer.parseInt(thisAdvTime[0]);

            broadcast.putExtra("time", time);

            // Save new time
            editor.putLong("TimeStamp", new Date().getTime() + time);
            editor.putInt("LastTime", time);

            // editor.putString("NotificationUri", thisAdvTime[1]);

            mNM.cancelAll();
            Log.v(TAG, "Starting next iteration of the timer service ...");
            Intent rintent = new Intent(context, TimerReceiver.class);
            rintent.putExtra("SetTime", time);
            PendingIntent mPendingIntent = PendingIntent.getBroadcast(context, 0, rintent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            AlarmManager mAlarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            mAlarmMgr.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + time, mPendingIntent);
        } else {
            broadcast.putExtra("stop", true);
            editor.putInt("advTimeIndex", 1);

        }
        broadcast.setAction(BROADCAST_RESET);
        context.sendBroadcast(broadcast);

        editor.apply();

    } else if (prefs.getBoolean("AutoRestart", false)) {
        int time = pintent.getIntExtra("SetTime", 0);
        if (time != 0) {

            mNM.cancel(0);
            Log.v(TAG, "Restarting the timer service ...");
            Intent rintent = new Intent(context, TimerReceiver.class);
            rintent.putExtra("SetTime", time);
            PendingIntent mPendingIntent = PendingIntent.getBroadcast(context, 0, rintent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            AlarmManager mAlarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            mAlarmMgr.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + time, mPendingIntent);

            // Save new time
            SharedPreferences.Editor editor = prefs.edit();
            editor.putLong("TimeStamp", new Date().getTime() + time);
            editor.putInt("LastTime", time);
            editor.apply();

            Intent broadcast = new Intent();
            broadcast.putExtra("time", time);
            broadcast.setAction(BROADCAST_RESET);
            context.sendBroadcast(broadcast);

        }
    }

    mNotificationManager.notify(0, mBuilder.build());

    Log.d(TAG, "ALARM: alarm finished");

}

From source file:id.ridon.keude.UpdateService.java

private void showAppUpdatesNotification(int updates) {
    Log.d("Keude", "Notifying " + updates + " updates.");
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this).setAutoCancel(true)
            .setContentTitle(getString(R.string.fdroid_updates_available));
    if (Build.VERSION.SDK_INT >= 11) {
        builder.setSmallIcon(R.drawable.ic_stat_notify_updates);
    } else {/* www  . ja va 2s .c  o m*/
        builder.setSmallIcon(R.drawable.ic_launcher);
    }
    Intent notifyIntent = new Intent(this, Keude.class).putExtra(Keude.EXTRA_TAB_UPDATE, true);
    if (updates > 1) {
        builder.setContentText(getString(R.string.many_updates_available, updates));
    } else {
        builder.setContentText(getString(R.string.one_update_available));
    }
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this).addParentStack(Keude.class)
            .addNextIntent(notifyIntent);
    PendingIntent pi = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(pi);
    NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    nm.notify(1, builder.build());
}

From source file:samson.AndroidNotifications.java

@Override
protected Handle schedule(long when, Builder builder) {
    // pull the id of this notification based off the Builder's string id or an automatically
    // generated identifier
    final int id;
    try {/*from w  w  w.j a  va 2s  .  com*/
        id = builder._data.containsKey(Notifications.ID) ? builder._data.get(Notifications.ID).hashCode()
                : getAutomaticIdentifier();
    } catch (IllegalArgumentException exception) {
        log.error("Failed to find valid identifier to send notification with.");
        return null;
    }

    // build a simulated task stack so the back button works properly
    TaskStackBuilder stack = TaskStackBuilder.create(applicationContext).addParentStack(activityClass)
            .addNextIntent(new Intent(applicationContext, activityClass));

    // create the notification builder
    Notification notification = new NotificationCompat.Builder(applicationContext).setAutoCancel(true)
            .setSmallIcon(builder._icon).setLargeIcon(getLargeIcon(builder)).setContentTitle(builder._title)
            .setContentText(builder._message)
            .setVibrate(builder._vibrate ? new long[] { 100, 200, 200, 200 } : new long[] {})
            .setContentIntent(stack.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)).setWhen(when)
            .setStyle(new NotificationCompat.BigTextStyle().bigText(builder._message)).build();

    // build the pending intent to pass to the alarm receiver
    final PendingIntent pending = PendingIntent.getBroadcast(applicationContext, id,
            new NotificationIntent(applicationContext, id, notification), 0);

    // register the pending notification id
    addNotification(id);

    // pass the intent to the alarm receiver
    alarmManager.set(AlarmManager.RTC_WAKEUP, when, pending);

    return new Handle() {
        @Override
        public void cancel() {
            notificationManager.cancel(id);
            alarmManager.cancel(pending);
            removeNotification(id);
        }
    };
}

From source file:com.twofours.surespot.services.SurespotGcmListenerService.java

private void generateNotification(Context context, String type, String from, String to, String title,
        String message, String tag, int id) {
    SurespotLog.d(TAG, "generateNotification");
    // get shared prefs
    SharedPreferences pm = context.getSharedPreferences(to, Context.MODE_PRIVATE);
    if (!pm.getBoolean("pref_notifications_enabled", true)) {
        return;//from  w w  w . jav  a 2s  .c  o  m
    }

    int icon = R.drawable.surespot_logo;

    // need to use same builder for only alert once to work:
    // http://stackoverflow.com/questions/6406730/updating-an-ongoing-notification-quietly
    mBuilder.setSmallIcon(icon).setContentTitle(title).setAutoCancel(true).setOnlyAlertOnce(false)
            .setContentText(message);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);

    Intent mainIntent = null;
    mainIntent = new Intent(context, MainActivity.class);
    mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    mainIntent.putExtra(SurespotConstants.ExtraNames.MESSAGE_TO, to);
    mainIntent.putExtra(SurespotConstants.ExtraNames.MESSAGE_FROM, from);
    mainIntent.putExtra(SurespotConstants.ExtraNames.NOTIFICATION_TYPE, type);

    stackBuilder.addNextIntent(mainIntent);

    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent((int) new Date().getTime(),
            PendingIntent.FLAG_CANCEL_CURRENT);

    mBuilder.setContentIntent(resultPendingIntent);
    int defaults = 0;

    boolean showLights = pm.getBoolean("pref_notifications_led", true);
    boolean makeSound = pm.getBoolean("pref_notifications_sound", true);
    boolean vibrate = pm.getBoolean("pref_notifications_vibration", true);
    int color = pm.getInt("pref_notification_color", getResources().getColor(R.color.surespotBlue));

    if (showLights) {
        SurespotLog.v(TAG, "showing notification led");
        mBuilder.setLights(color, 500, 5000);
        defaults |= Notification.FLAG_SHOW_LIGHTS; // shouldn't need this - setLights does it.  Just to make sure though...
    } else {
        mBuilder.setLights(color, 0, 0);
    }

    if (makeSound) {
        SurespotLog.v(TAG, "making notification sound");
        defaults |= Notification.DEFAULT_SOUND;
    }

    if (vibrate) {
        SurespotLog.v(TAG, "vibrating notification");
        defaults |= Notification.DEFAULT_VIBRATE;
    }

    mBuilder.setDefaults(defaults);
    mNotificationManager.notify(tag, id, mBuilder.build());
}

From source file:com.z3r0byte.magistify.Services.OldBackgroundService.java

private void notifyAppointmentTimer() {
    Log.d(TAG, "notifyAppoinytmentTimer: Starting appointment timer");
    TimerTask notificationTask = new TimerTask() {
        @Override/*from   w  ww.  j  a  v a  2s.  com*/
        public void run() {

            Gson gson = new Gson();
            Appointment[] appointments = calendarDB.getNotificationAppointments();
            Log.d(TAG, "AppointmentNotifications: amount of appointments that should be shown: "
                    + appointments.length);
            previousAppointment = configUtil.getString("previous_appointment");
            if (appointments.length >= 1) {
                Appointment appointment = appointments[0];
                if (!gson.toJson(appointment).equals(previousAppointment) && isCandidate(appointment)) {
                    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                            getApplicationContext());
                    mBuilder.setSmallIcon(R.drawable.ic_appointment);

                    if (appointment.startDate != null) {
                        String time = DateUtils.formatDate(appointment.startDate, "HH:mm");
                        mBuilder.setContentTitle("Volgende afspraak (" + time + ")");
                    } else {
                        mBuilder.setContentTitle("Volgende afspraak:");
                    }
                    mBuilder.setContentText(appointment.description + " in " + appointment.location);
                    mBuilder.setAutoCancel(true);
                    mBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);

                    Intent resultIntent = new Intent(getApplicationContext(), AppointmentActivity.class);
                    TaskStackBuilder stackBuilder = TaskStackBuilder.create(getApplicationContext());
                    stackBuilder.addParentStack(AppointmentActivity.class);
                    stackBuilder.addNextIntent(resultIntent);
                    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
                            PendingIntent.FLAG_UPDATE_CURRENT);
                    mBuilder.setContentIntent(resultPendingIntent);

                    NotificationManager mNotificationManager = (NotificationManager) getSystemService(
                            Context.NOTIFICATION_SERVICE);
                    mNotificationManager.notify(9991, mBuilder.build());

                    previousAppointment = gson.toJson(appointment);
                    configUtil.setString("previous_appointment", previousAppointment);
                }
            } else {
                NotificationManager notifManager = (NotificationManager) getSystemService(
                        Context.NOTIFICATION_SERVICE);
                notifManager.cancel(9991);
            }
        }
    };
    timer.schedule(notificationTask, 20000, 30 * 1000);
}

From source file:com.z3r0byte.magistify.Services.OldBackgroundService.java

private void notifyAppointmentChangedTimer() {
    Log.d(TAG, "notifyAppoinytmentTimer: Starting notify appointmentchange timer");
    TimerTask notificationTask = new TimerTask() {
        @Override/*from  w w  w  .j  a v  a  2s . c  o  m*/
        public void run() {

            ScheduleChangeDB scheduleChangeDB = new ScheduleChangeDB(getApplicationContext());

            Appointment[] appointments = scheduleChangeDB.getNotificationAppointments();
            previousChangedAppointment = configUtil.getString("previous_changed_appointment");
            if (appointments.length > 0) {
                Appointment appointment = appointments[0];
                if (!appointment.startDateString.equals(previousChangedAppointment)) {
                    String content;
                    if (appointment.description != null && !appointment.description.equalsIgnoreCase("null")) {
                        content = appointment.description;
                    } else {
                        content = "De les is uitgevallen!";
                    }

                    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                            getApplicationContext());
                    mBuilder.setSmallIcon(R.drawable.ic_schedule_change);

                    mBuilder.setContentTitle("Let op! De volgende les is gewijzigd!");
                    mBuilder.setContentText(content);
                    mBuilder.setAutoCancel(true);
                    mBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
                    mBuilder.setDefaults(Notification.DEFAULT_ALL);

                    Intent resultIntent = new Intent(getApplicationContext(), ScheduleChangeActivity.class);
                    TaskStackBuilder stackBuilder = TaskStackBuilder.create(getApplicationContext());
                    stackBuilder.addParentStack(ScheduleChangeActivity.class);
                    stackBuilder.addNextIntent(resultIntent);
                    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
                            PendingIntent.FLAG_UPDATE_CURRENT);
                    mBuilder.setContentIntent(resultPendingIntent);

                    NotificationManager mNotificationManager = (NotificationManager) getSystemService(
                            Context.NOTIFICATION_SERVICE);
                    mNotificationManager.notify(9994, mBuilder.build());

                    previousChangedAppointment = appointment.startDateString;
                    configUtil.setString("previous_changed_appointment", appointment.startDateString);
                }
            } else {
                NotificationManager notifManager = (NotificationManager) getSystemService(
                        Context.NOTIFICATION_SERVICE);
                notifManager.cancel(9994);
            }
        }
    };
    timer.schedule(notificationTask, 20000, 30 * 1000);
}

From source file:fr.paug.droidcon.service.SessionAlarmService.java

private void notifySession(final long sessionStart, final long alarmOffset) {
    long currentTime = UIUtils.getCurrentTime(this);
    final long intervalEnd = sessionStart + MILLI_TEN_MINUTES;
    LOGD(TAG, "Considering notifying for time interval.");
    LOGD(TAG, "    Interval start: " + sessionStart + "=" + (new Date(sessionStart)).toString());
    LOGD(TAG, "    Interval end: " + intervalEnd + "=" + (new Date(intervalEnd)).toString());
    LOGD(TAG, "    Current time is: " + currentTime + "=" + (new Date(currentTime)).toString());
    if (sessionStart < currentTime) {
        LOGD(TAG, "Skipping session notification (too late -- time interval already started)");
        return;/*w ww . jav a  2  s . c om*/
    }

    if (!PrefUtils.shouldShowSessionReminders(this)) {
        // skip if disabled in settings
        LOGD(TAG, "Skipping session notification for sessions. Disabled in settings.");
        return;
    }

    // Avoid repeated notifications.
    if (alarmOffset == UNDEFINED_ALARM_OFFSET && UIUtils.isNotificationFiredForBlock(this,
            ScheduleContract.Blocks.generateBlockId(sessionStart, intervalEnd))) {
        LOGD(TAG, "Skipping session notification (already notified)");
        return;
    }

    final ContentResolver cr = getContentResolver();

    LOGD(TAG, "Looking for sessions in interval " + sessionStart + " - " + intervalEnd);
    Cursor c = cr.query(ScheduleContract.Sessions.CONTENT_MY_SCHEDULE_URI, SessionDetailQuery.PROJECTION,
            ScheduleContract.Sessions.STARTING_AT_TIME_INTERVAL_SELECTION,
            ScheduleContract.Sessions.buildAtTimeIntervalArgs(sessionStart, intervalEnd), null);
    int starredCount = c.getCount();
    LOGD(TAG, "# starred sessions in that interval: " + c.getCount());
    String singleSessionId = null;
    String singleSessionRoomId = null;
    ArrayList<String> starredSessionTitles = new ArrayList<String>();
    while (c.moveToNext()) {
        singleSessionId = c.getString(SessionDetailQuery.SESSION_ID);
        singleSessionRoomId = c.getString(SessionDetailQuery.ROOM_ID);
        starredSessionTitles.add(c.getString(SessionDetailQuery.SESSION_TITLE));
        LOGD(TAG, "-> Title: " + c.getString(SessionDetailQuery.SESSION_TITLE));
    }
    if (starredCount < 1) {
        return;
    }

    // Generates the pending intent which gets fired when the user taps on the notification.
    // NOTE: Use TaskStackBuilder to comply with Android's design guidelines
    // related to navigation from notifications.
    Intent baseIntent = new Intent(this, MyScheduleActivity.class);
    baseIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    TaskStackBuilder taskBuilder = TaskStackBuilder.create(this).addNextIntent(baseIntent);

    // For a single session, tapping the notification should open the session details (b/15350787)
    if (starredCount == 1) {
        taskBuilder.addNextIntent(
                new Intent(Intent.ACTION_VIEW, ScheduleContract.Sessions.buildSessionUri(singleSessionId)));
    }

    PendingIntent pi = taskBuilder.getPendingIntent(0, PendingIntent.FLAG_CANCEL_CURRENT);

    final Resources res = getResources();
    String contentText;
    int minutesLeft = (int) (sessionStart - currentTime + 59000) / 60000;
    if (minutesLeft < 1) {
        minutesLeft = 1;
    }

    if (starredCount == 1) {
        contentText = res.getString(R.string.session_notification_text_1, minutesLeft);
    } else {
        contentText = res.getQuantityString(R.plurals.session_notification_text, starredCount - 1, minutesLeft,
                starredCount - 1);
    }

    NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(this)
            .setContentTitle(starredSessionTitles.get(0)).setContentText(contentText)
            //.setColor(getResources().getColor(R.color.theme_primary))
            // Note: setColor() is available in the support lib v21+.
            // We commented it out because we want the source to compile 
            // against support lib v20. If you are using support lib
            // v21 or above on Android L, uncomment this line.
            .setTicker(res.getQuantityString(R.plurals.session_notification_ticker, starredCount, starredCount))
            .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
            .setLights(SessionAlarmService.NOTIFICATION_ARGB_COLOR, SessionAlarmService.NOTIFICATION_LED_ON_MS,
                    SessionAlarmService.NOTIFICATION_LED_OFF_MS)
            .setSmallIcon(R.drawable.ic_stat_notification).setContentIntent(pi)
            .setPriority(Notification.PRIORITY_MAX).setAutoCancel(true);
    if (minutesLeft > 5) {
        notifBuilder.addAction(R.drawable.ic_alarm_holo_dark,
                String.format(res.getString(R.string.snooze_x_min), 5),
                createSnoozeIntent(sessionStart, intervalEnd, 5));
    }
    String bigContentTitle;
    if (starredCount == 1 && starredSessionTitles.size() > 0) {
        bigContentTitle = starredSessionTitles.get(0);
    } else {
        bigContentTitle = res.getQuantityString(R.plurals.session_notification_title, starredCount, minutesLeft,
                starredCount);
    }
    NotificationCompat.InboxStyle richNotification = new NotificationCompat.InboxStyle(notifBuilder)
            .setBigContentTitle(bigContentTitle);

    // Adds starred sessions starting at this time block to the notification.
    for (int i = 0; i < starredCount; i++) {
        richNotification.addLine(starredSessionTitles.get(i));
    }
    NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    LOGD(TAG, "Now showing notification.");
    nm.notify(NOTIFICATION_ID, richNotification.build());
}

From source file:com.mplayer_remote.ServicePlayAFile.java

private void showNotyfications() {

    int positionOfLastDot = fileToPlayString.lastIndexOf(".");
    String filenameExtension = fileToPlayString.substring(positionOfLastDot + 1);

    int positionOfLastDashint = fileToPlayString.lastIndexOf("/");
    String secondLineOfNotification = fileToPlayString.substring(positionOfLastDashint + 1);

    // Creates an explicit intent for an Activity in your app
    Intent resultIntent = new Intent(this, RemoteControl.class);
    resultIntent.putExtra("file_to_play", fileToPlayString);
    resultIntent.putExtra("absolute_path", absolutePathString);

    // The stack builder object will contain an artificial back stack for the
    // started Activity.
    // This ensures that navigating backward from the Activity leads out of
    // your application to the Home screen.
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    // Adds the back stack for the Intent (but not the Intent itself)
    stackBuilder.addParentStack(RemoteControl.class);
    // Adds the Intent that starts the Activity to the top of the stack
    stackBuilder.addNextIntent(resultIntent);

    //for adding fileToPlayString and absolutePathString to intents form stackBuilder
    for (int i = 0; i < stackBuilder.getIntentCount(); i++) {
        Intent intentToEdit = stackBuilder.editIntentAt(i);
        intentToEdit.putExtra("file_to_play", fileToPlayString);
        intentToEdit.putExtra("absolute_path", absolutePathString);
    }//from w  ww.  ja  va  2 s. c  om

    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle(getString(R.string.text_for_first_line_of_notification_from_serviceplayafile))
            .setContentText(secondLineOfNotification);

    mBuilder.setContentIntent(resultPendingIntent);
    mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    // mId allows you to update the notification later on.
    mNotificationManager.notify(mId, mBuilder.build());

}