Example usage for android.app TaskStackBuilder getPendingIntent

List of usage examples for android.app TaskStackBuilder getPendingIntent

Introduction

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

Prototype

public PendingIntent getPendingIntent(int requestCode, @PendingIntent.Flags int flags) 

Source Link

Document

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

Usage

From source file:com.fairphone.updater.UpdaterService.java

private void setNotification() {

    Context context = getApplicationContext();

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

    NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.fairphone_updater_tray_icon_small)
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.fairphone_updater_tray_icon))
            .setContentTitle(context.getResources().getString(R.string.app_name))
            .setContentText(getResources().getString(R.string.fairphoneUpdateMessage));

    Intent resultIntent = new Intent(context, FairphoneUpdater.class);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);

    stackBuilder.addParentStack(FairphoneUpdater.class);

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

    builder.setContentIntent(resultPendingIntent);

    Notification notificationWhileRunnig = builder.build();

    // Add notification
    manager.notify(0, notificationWhileRunnig);

}

From source file:com.hkm.taxicallandroid.schema.ConfirmCall.java

private void generate_notification(final CallPanel ctx) {

    final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(ctx)
            .setSmallIcon(R.drawable.ic_talkrequirements).setContentTitle("Incoming Taxi").setContentText(String
                    .format(content_f, incoming_driver_data.getLicense(), incoming_driver_data.getEstTime()));
    // Creates an explicit intent for an Activity in your app
    final Intent resultIntent = new Intent(ctx, CallPanel.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(ctx);
    // Adds the back stack for the Intent (but not the Intent itself)
    stackBuilder.addParentStack(CallPanel.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) ctx
            .getSystemService(Context.NOTIFICATION_SERVICE);
    // mId allows you to update the notification later on.
    mNotificationManager.notify(39939, mBuilder.build());

}

From source file:com.raspi.chatapp.util.Notification.java

public void createNotification(String buddyId, String name, String message, String type) {
    SharedPreferences defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);

    if (defaultSharedPreferences
            .getBoolean(context.getResources().getString(R.string.pref_key_new_message_notifications), true)) {
        int index = buddyId.indexOf("@");
        if (index != -1)
            buddyId = buddyId.substring(0, index);
        if (name == null)
            name = buddyId;/*from  w w w  .  j  a  va  2  s  .c  om*/
        Log.d("DEBUG", "creating notification: " + buddyId + "|" + name + "|" + message);
        Intent resultIntent = new Intent(context, ChatActivity.class);
        resultIntent.setAction(NOTIFICATION_CLICK);
        String oldBuddyId = getOldBuddyId();
        Log.d("DEBUG",
                (oldBuddyId == null) ? ("oldBuddy is null (later " + buddyId) : ("oldBuddy: " + oldBuddyId));
        if (oldBuddyId == null || oldBuddyId.equals("")) {
            oldBuddyId = buddyId;
            setOldBuddyId(buddyId);
        }
        if (oldBuddyId.equals(buddyId)) {
            resultIntent.putExtra(Constants.BUDDY_ID, buddyId);
            resultIntent.putExtra(Constants.CHAT_NAME, name);
        }

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
        stackBuilder.addParentStack(ChatActivity.class);
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationManager nm = ((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE));
        NotificationCompat.Style style;

        String[] previousNotifications = readJSONArray(CURRENT_NOTIFICATIONS);
        String title;
        String[] currentNotifications = Arrays.copyOf(previousNotifications, previousNotifications.length + 1);
        currentNotifications[currentNotifications.length - 1] = name + ": " + message;
        if (previousNotifications.length == 0) {
            style = new NotificationCompat.BigTextStyle();
            NotificationCompat.BigTextStyle bigTextStyle = ((NotificationCompat.BigTextStyle) style);
            title = context.getResources().getString(R.string.new_message) + " "
                    + context.getResources().getString(R.string.from) + " " + name;
            bigTextStyle.bigText(currentNotifications[0]);
            bigTextStyle.setBigContentTitle(title);
        } else {
            style = new NotificationCompat.InboxStyle();
            NotificationCompat.InboxStyle inboxStyle = (NotificationCompat.InboxStyle) style;
            title = (previousNotifications.length + 1) + " "
                    + context.getResources().getString(R.string.new_messages);
            for (String s : currentNotifications)
                if (s != null && !"".equals(s))
                    inboxStyle.addLine(s);
            inboxStyle.setSummaryText(
                    (currentNotifications.length > 2) ? ("+" + (currentNotifications.length - 2) + " more")
                            : null);
            inboxStyle.setBigContentTitle(title);
        }
        writeJSONArray(currentNotifications, CURRENT_NOTIFICATIONS);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context).setContentTitle(title)
                .setContentText(currentNotifications[currentNotifications.length - 1])
                .setSmallIcon(MessageHistory.TYPE_TEXT.equals(type) ? R.drawable.ic_forum_white_48dp
                        : R.drawable.ic_photo_camera_white_48dp)
                .setLargeIcon(getLargeIcon(Character.toUpperCase(name.toCharArray()[0]))).setStyle(style)
                .setAutoCancel(true).setPriority(5).setContentIntent(resultPendingIntent);

        String str = context.getResources().getString(R.string.pref_key_privacy);
        mBuilder.setVisibility(context.getResources().getString(R.string.pref_value1_privacy).equals(str)
                ? NotificationCompat.VISIBILITY_SECRET
                : context.getResources().getString(R.string.pref_value2_privacy).equals(str)
                        ? NotificationCompat.VISIBILITY_PRIVATE
                        : NotificationCompat.VISIBILITY_PUBLIC);

        str = context.getResources().getString(R.string.pref_key_vibrate);
        if (defaultSharedPreferences.getBoolean(str, true))
            mBuilder.setVibrate(new long[] { 800, 500, 800, 500 });

        str = context.getResources().getString(R.string.pref_key_led);
        if (defaultSharedPreferences.getBoolean(str, true))
            mBuilder.setLights(Color.BLUE, 500, 500);

        str = defaultSharedPreferences.getString(context.getResources().getString(R.string.pref_key_ringtone),
                "");
        mBuilder.setSound("".equals(str) ? RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
                : Uri.parse(str));

        nm.notify(NOTIFICATION_ID, mBuilder.build());
        str = context.getResources().getString(R.string.pref_key_banner);
        if (!defaultSharedPreferences.getBoolean(str, true)) {
            try {
                Thread.sleep(1500);
            } catch (InterruptedException e) {
            }
            reset();
        }
    }
}

From source file:alaindc.crowdroid.GeofenceTransitionsIntentService.java

/**
 * Posts a notification in the notification bar when a transition is detected.
 * If the user clicks the notification, control goes to the MainActivity.
 *///from  w  w w  . j  a va 2 s.co  m
private void sendNotification(String nameofsensor) {
    // Create an explicit content Intent that starts the main Activity.
    Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);

    // Construct a task stack.
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);

    // Add the main Activity to the task stack as the parent.
    stackBuilder.addParentStack(MainActivity.class);

    // Push the content Intent onto the stack.
    stackBuilder.addNextIntent(notificationIntent);

    // Get a PendingIntent containing the entire back stack.
    PendingIntent notificationPendingIntent = stackBuilder.getPendingIntent(0,
            PendingIntent.FLAG_UPDATE_CURRENT);

    // Get a notification builder that's compatible with platform versions >= 4
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

    // Define the notification settings.
    builder.setSmallIcon(R.drawable.icon)
            // In a real app, you may want to use a library like Volley
            // to decode the Bitmap.
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.icon)).setColor(Color.RED)
            .setContentTitle("Geofence Crowdroid").setContentText("Geofence Trigger: " + nameofsensor)
            .setContentIntent(notificationPendingIntent);

    // Dismiss notification once the user touches it.
    builder.setAutoCancel(true);

    // Get an instance of the Notification manager
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);

    // Issue the notification
    mNotificationManager.notify(0, builder.build());
}

From source file:io.github.protino.codewatch.sync.WakatimeDataSyncJob.java

public void updateNotifications() {
    //Notify goals
    final CountDownLatch firebaseLatch = new CountDownLatch(1);
    final List<GoalItem> goalItemList = new ArrayList<>();
    Context context = getApplicationContext();
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);

    boolean notifyGoals = sharedPreferences.getBoolean(context.getString(R.string.pref_goal_reminders_key),
            true);/* w  ww  .ja  v  a 2s .c  om*/
    boolean notifyRank = sharedPreferences.getBoolean(context.getString(R.string.pref_leaderboard_changes_key),
            true);
    String firebaseUid = sharedPreferences.getString(Constants.PREF_FIREBASE_USER_ID, null);

    String title = context.getString(R.string.app_name);
    Intent resultIntent = new Intent(context, NavigationDrawerActivity.class);
    TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context);
    taskStackBuilder.addNextIntent(resultIntent);
    PendingIntent pendingIntent = taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    if (notifyGoals && firebaseUid != null) {
        FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
        DatabaseReference databaseReference = firebaseDatabase.getReference().child("goals").child(firebaseUid);
        databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                    goalItemList.add(snapshot.getValue(GoalItem.class));
                }
                firebaseLatch.countDown();
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                firebaseLatch.countDown();
            }
        });
        try {
            //Build the notification
            NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
                    .setColor(context.getResources().getColor(R.color.colorPrimaryDark))
                    .setSmallIcon(R.mipmap.ic_launcher).setContentTitle(title)
                    .setContentText(context.getString(R.string.goals_reminder));

            firebaseLatch.await();
            NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();

            for (GoalItem goalItem : goalItemList) {
                String goalText = null;
                switch (goalItem.getType()) {
                case LANGUAGE_GOAL:
                    goalText = context.getString(R.string.language_goal, goalItem.getName(),
                            goalItem.getData());
                    break;
                case PROJECT_DAILY_GOAL:
                    goalText = context.getString(R.string.project_daily_goal, goalItem.getData(),
                            goalItem.getName());
                    break;
                case PROJECT_DEADLINE_GOAL:
                    long deadline = goalItem.getData();
                    long currentDate = System.currentTimeMillis();
                    int remainingDays = Days.daysBetween(new DateTime(currentDate), new DateTime(deadline))
                            .getDays();

                    if (remainingDays > 0) {
                        if (currentDate < deadline) {
                            goalText = context.getString(R.string.finish_project_today, goalItem.getName());
                        }
                    } else {
                        goalText = context.getString(R.string.finish_project_within, goalItem.getName(),
                                remainingDays);
                    }
                    break;
                default:
                    break;
                }
                if (goalText != null) {
                    inboxStyle.addLine(goalText);
                }
            }
            builder.setStyle(inboxStyle);
            builder.setContentIntent(pendingIntent);

            NotificationManager notificationManager = (NotificationManager) context
                    .getSystemService(NOTIFICATION_SERVICE);
            notificationManager.notify(GOAL_NOTIFICATION_ID, builder.build());
        } catch (InterruptedException e) {
            Timber.e(e);
        }
    }

    if (notifyRank) {
        String wakatimeUid = sharedPreferences.getString(PREF_WAKATIME_USER_ID, null);
        Cursor cursor = getContentResolver().query(LeaderContract.LeaderEntry.buildProfileUri(wakatimeUid),
                null, null, null, null);
        if (cursor == null || !cursor.moveToFirst()) {
            return;
        }
        int rank = cursor.getInt(cursor.getColumnIndex(LeaderContract.LeaderEntry.COLUMN_RANK));
        int dailyAverage = cursor
                .getInt(cursor.getColumnIndex(LeaderContract.LeaderEntry.COLUMN_DAILY_AVERAGE));

        String text = context.getString(R.string.leaderboard_notification_text, rank,
                FormatUtils.getFormattedTime(context, dailyAverage));
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setColor(context.getResources().getColor(R.color.colorPrimaryDark)).setContentTitle(title)
                .setContentText(text).setStyle(new NotificationCompat.BigTextStyle().bigText(text))
                .setContentIntent(pendingIntent);
        NotificationManager notificationManager = (NotificationManager) context
                .getSystemService(NOTIFICATION_SERVICE);
        notificationManager.notify(LEADERBOARD_NOTIFICATION_ID, builder.build());
        cursor.close();
    }

}

From source file:de.aw.awlib.AWNotification.java

/**
 * Erstellt einen NotificationBuilder mit Ticker {@link AWNotification#ticker}, hasProgressBar
 * und setzt (wenn gesetzt) startActivity als StartActivity.
 *
 * @return NotificationBuilder/*from w  ww .  j  a va 2s  . co  m*/
 */
protected NotificationCompat.Builder getNotification() {
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, mChannelID);
    mBuilder.setSmallIcon(getIconResID()).setAutoCancel(true);
    if (ticker != null) {
        mBuilder.setTicker(ticker);
    }
    if (number != NOID) {
        mBuilder.setNumber(number);
    }
    mBuilder.setProgress(0, 0, hasProgressBar);
    Intent intent;
    if (startActivity != null) {
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
        intent = new Intent(context, startActivity);
        intent.putExtras(extras);
        stackBuilder.addNextIntent(intent);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(resultPendingIntent);
    }
    return mBuilder;
}

From source file:com.kdb.ledcontrol.LEDManager.java

public void setOnBoot() {
    String cmd = prefs.getString("last_cmd", null);
    int brightness = prefs.getInt("last_brightness", -1);
    if (brightness != -1 && devicePathToBrightness != null) {
        brightness /= 25;// ww w .  ja v  a 2 s. c  om
        ApplyBrightness(brightness);
    }
    if (cmd != null && devicePathToLED != null) {
        try {
            deviceInput.writeBytes("echo " + cmd + " > " + devicePathToLED + "\n");
            deviceInput.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    if (checkState() != -1 && prefs.getBoolean("show_notif", true)) {
        Log.i(TAG, "LED trigger applied on boot");
        Bitmap largeIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
                .setSmallIcon(R.drawable.ic_stat_notification).setLargeIcon(largeIcon)
                .setContentTitle(context.getString(R.string.app_name_full))
                .setContentText(context.getString(R.string.notification_content));
        Intent resultIntent = new Intent(context, MainActivity.class);
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
        stackBuilder.addParentStack(MainActivity.class);
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(resultPendingIntent);
        NotificationManager mNotificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(0, builder.build());
    }
}

From source file:com.radiusnetworks.museumguide.MuseumGuideApplication.java

private void sendNotification() {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this).setContentTitle("Museum Guide")
            .setContentText("An exhibit item is nearby.").setSmallIcon(R.drawable.launcher);

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    stackBuilder.addNextIntent(new Intent(this, MuseumItemsActivity.class));
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(resultPendingIntent);
    NotificationManager notificationManager = (NotificationManager) this
            .getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(1, builder.build());
}

From source file:org.travey.travey.LocationIntentService.java

public void createNotification() {
    //create a notification that prompts the user to fill out a form about the trip
    Log.i("**************", "Notifying");
    if (travey.LOG_TO_DATABASE) {
        logToDatabase("notifying");
    }//www  .  j  av a2s. c  om
    Resources res = getResources();

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
    mBuilder.setContentTitle(res.getString(R.string.trip_notification_title));
    mBuilder.setContentText(res.getString(R.string.trip_notification_body));
    mBuilder.setTicker(res.getString(R.string.trip_notification_ticker));
    mBuilder.setSmallIcon(R.drawable.ic_traveyd);
    mBuilder.setAutoCancel(true);

    //make intent for launching survey if they click on the notification
    Intent mainIntent = new Intent(this, MainActivity.class);
    //Pass along trip data (maybe can do this better with Parcelable)
    mainIntent.putExtra("tab", "surveys");
    mainIntent.putExtra("fromNotify", "true");
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    stackBuilder.addParentStack(MainActivity.class);
    stackBuilder.addNextIntent(mainIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_ONE_SHOT);
    mBuilder.setContentIntent(resultPendingIntent);

    //TESTING TO SEE IF FOLLOWING CAN BE REMOVED ALONG WITH RECEIVER CLASS
    //make intent for cleaning up if they dismiss the notification
    Intent dismissIntent = new Intent(this, NotificationDismissedReceiver.class);
    dismissIntent.putExtra("com.my.app.notificationId", travey.NOTIFY_ID);
    PendingIntent dismissPendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(),
            travey.NOTIFY_ID, dismissIntent, 0);
    mBuilder.setDeleteIntent(dismissPendingIntent);

    //launch the notification
    NotificationManager myNotificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);
    myNotificationManager.notify(0, mBuilder.build());

    //handle preferences
    Log.i("**************", "Setting notification pref to true");
    //reset the trip
    myPrefs = this.getSharedPreferences("myPrefs", MODE_PRIVATE);
    myPrefsEditor = myPrefs.edit();
    currentTrip = null;
    myPrefsEditor.putBoolean("isNotified", true);
    myPrefsEditor.commit();
}

From source file:org.secuso.privacyfriendlynetmonitor.ConnectionAnalysis.PassiveService.java

private void showAppNotification() {
    mBuilder.setSmallIcon(R.drawable.ic_notification);
    mBuilder.setLargeIcon(mIcon);/*from   w ww .j a v  a2 s . c o  m*/
    Intent resultIntent = new Intent(this, MainActivity.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(this);

    // Adds the back stack for the Intent (but not the Intent itself)
    stackBuilder.addParentStack(MainActivity.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) getSystemService(
            Context.NOTIFICATION_SERVICE);

    // mId allows you to update the notification later on.
    mNotificationManager.notify(Const.LOG_TAG, 1, mBuilder.build());
}