Example usage for android.app PendingIntent FLAG_CANCEL_CURRENT

List of usage examples for android.app PendingIntent FLAG_CANCEL_CURRENT

Introduction

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

Prototype

int FLAG_CANCEL_CURRENT

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

Click Source Link

Document

Flag indicating that if the described PendingIntent already exists, the current one should be canceled before generating a new one.

Usage

From source file:org.ohmage.triggers.types.location.LocTrigService.java

private void setKeepAliveAlarm() {
    Intent i = new Intent(ACTION_ALRM_SRV_KEEP_ALIVE);

    //set the alarm if not already existing
    PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, PendingIntent.FLAG_NO_CREATE);

    AlarmManager alarmMan = (AlarmManager) getSystemService(ALARM_SERVICE);
    if (pi != null) {
        alarmMan.cancel(pi);//from w  w  w  .  jav a2s .  c  o m
        pi.cancel();
    }

    pi = PendingIntent.getBroadcast(this, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);

    alarmMan.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
            SystemClock.elapsedRealtime() + SERV_KEEP_ALIVE_TIME, SERV_KEEP_ALIVE_TIME, pi);
}

From source file:com.numberx.kkmctimer.DeskClock.java

private boolean processMenuClick(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.menu_item_settings:
        startActivity(new Intent(DeskClock.this, SettingsActivity.class));
        return true;
    case R.id.menu_item_help:
        Intent i = item.getIntent();// w  w  w.j a  v a  2  s  .co  m
        if (i != null) {
            try {
                startActivity(i);
            } catch (ActivityNotFoundException e) {
                // No activity found to match the intent - ignore
            }
        }
        return true;
    case R.id.menu_item_night_mode:
        startActivity(new Intent(DeskClock.this, ScreensaverActivity.class));
    case R.id.menu_item_sync_kkmctimer:
        // TODO: update KKMCTimerSync to actually sync alarms and then update this bit
        return true;
    case R.id.menu_item_push_to_kkmctimer:
        // TODO: update KKMCTimerSync to actually push alarms and then update this bit
        return true;
    case R.id.menu_item_push_to_phone:
        // TODO: update KKMCTimerSync to actually push alarms and then update this bit
        String correctString = "android:switcher:" + mViewPager.getId() + ":" + ALARM_TAB_INDEX;
        new KKMCTimerSync(this, correctString).syncPushToPhone();
        return true;
    case R.id.menu_item_reset_db:
        // Delete the database
        ContentResolver cr = this.getContentResolver();
        cr.call(Uri.parse("content://" + ClockContract.AUTHORITY), "resetAlarmTables", null, null);

        // Restart the app to repopulate db with default and recreate activities.
        Intent mStartActivity = new Intent(this, DeskClock.class);
        int mPendingIntentId = 123456;
        PendingIntent mPendingIntent = PendingIntent.getActivity(this, mPendingIntentId, mStartActivity,
                PendingIntent.FLAG_CANCEL_CURRENT);
        AlarmManager mgr = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
        System.exit(0);
        return true;
    default:
        break;
    }
    return true;
}

From source file:com.google.samples.apps.sergio.service.SessionAlarmService.java

private void notifySessionFeedback(boolean debug) {
    LOGD(TAG, "Considering firing notification for session feedback.");

    if (debug) {/*from w  ww .j  a va  2  s . c o m*/
        LOGD(TAG, "Note: this is a debug notification.");
    }

    // Don't fire notification if this feature is disabled in settings
    if (!PrefUtils.shouldShowSessionFeedbackReminders(this)) {
        LOGD(TAG, "Skipping session feedback notification. Disabled in settings.");
        return;
    }

    final Cursor c = getContentResolver().query(ScheduleContract.Sessions.CONTENT_MY_SCHEDULE_URI,
            SessionsNeedingFeedbackQuery.PROJECTION, SessionsNeedingFeedbackQuery.WHERE_CLAUSE, null, null);
    if (c == null) {
        return;
    }

    List<String> needFeedbackIds = new ArrayList<String>();
    List<String> needFeedbackTitles = new ArrayList<String>();
    while (c.moveToNext()) {
        String sessionId = c.getString(SessionsNeedingFeedbackQuery.SESSION_ID);
        String sessionTitle = c.getString(SessionsNeedingFeedbackQuery.SESSION_TITLE);

        // Avoid repeated notifications.
        if (UIUtils.isFeedbackNotificationFiredForSession(this, sessionId)) {
            LOGD(TAG, "Skipping repeated session feedback notification for session '" + sessionTitle + "'");
            continue;
        }

        needFeedbackIds.add(sessionId);
        needFeedbackTitles.add(sessionTitle);
    }

    if (needFeedbackIds.size() == 0) {
        // the user has already been notified of all sessions needing feedback
        return;
    }

    LOGD(TAG,
            "Going forward with session feedback notification for " + needFeedbackIds.size() + " session(s).");

    final Resources res = getResources();

    // this is used to synchronize deletion of notifications on phone and wear
    Intent dismissalIntent = new Intent(ACTION_NOTIFICATION_DISMISSAL);
    // TODO: fix Wear dismiss integration
    //dismissalIntent.putExtra(KEY_SESSION_ID, sessionId);
    PendingIntent dismissalPendingIntent = PendingIntent.getService(this, (int) new Date().getTime(),
            dismissalIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    String provideFeedbackTicker = res.getString(R.string.session_feedback_notification_ticker);
    NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(this)
            .setColor(getResources().getColor(R.color.theme_primary)).setContentText(provideFeedbackTicker)
            .setTicker(provideFeedbackTicker)
            .setLights(SessionAlarmService.NOTIFICATION_ARGB_COLOR, SessionAlarmService.NOTIFICATION_LED_ON_MS,
                    SessionAlarmService.NOTIFICATION_LED_OFF_MS)
            .setSmallIcon(R.drawable.ic_stat_notification).setPriority(Notification.PRIORITY_LOW)
            .setLocalOnly(true) // make it local to the phone
            .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
            .setDeleteIntent(dismissalPendingIntent).setAutoCancel(true);

    if (needFeedbackIds.size() == 1) {
        // Only 1 session needs feedback
        Uri sessionUri = ScheduleContract.Sessions.buildSessionUri(needFeedbackIds.get(0));
        PendingIntent pi = TaskStackBuilder.create(this)
                .addNextIntent(new Intent(this, MyScheduleActivity.class))
                .addNextIntent(new Intent(Intent.ACTION_VIEW, sessionUri, this, SessionFeedbackActivity.class))
                .getPendingIntent(1, PendingIntent.FLAG_CANCEL_CURRENT);

        notifBuilder.setContentTitle(needFeedbackTitles.get(0)).setContentIntent(pi);
    } else {
        // Show information about several sessions that need feedback
        PendingIntent pi = TaskStackBuilder.create(this)
                .addNextIntent(new Intent(this, MyScheduleActivity.class))
                .getPendingIntent(1, PendingIntent.FLAG_CANCEL_CURRENT);

        NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
        inboxStyle.setBigContentTitle(provideFeedbackTicker);
        for (String title : needFeedbackTitles) {
            inboxStyle.addLine(title);
        }

        notifBuilder
                .setContentTitle(getResources().getQuantityString(R.plurals.session_plurals,
                        needFeedbackIds.size(), needFeedbackIds.size()))
                .setStyle(inboxStyle).setContentIntent(pi);
    }

    NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    LOGD(TAG, "Now showing session feedback notification!");
    nm.notify(FEEDBACK_NOTIFICATION_ID, notifBuilder.build());

    for (int i = 0; i < needFeedbackIds.size(); i++) {
        setupNotificationOnWear(needFeedbackIds.get(i), null, needFeedbackTitles.get(i), null);
    }
}

From source file:com.jjcamera.apps.iosched.service.SessionAlarmService.java

/**
 *  A starred session is about to end. Notify the user to provide session feedback.
 *  Constructs and triggers a system notification. Does nothing if the session has already
 *  concluded./*  w ww. j a  v  a  2s .  c  o m*/
 */
private void notifySessionFeedback(boolean debug) {
    LOGD(TAG, "Considering firing notification for session feedback.");

    if (debug) {
        LOGW(TAG, "Note: this is a debug notification.");
    }

    // Don't fire notification if this feature is disabled in settings
    if (!SettingsUtils.shouldShowSessionFeedbackReminders(this)) {
        LOGD(TAG, "Skipping session feedback notification. Disabled in settings.");
        return;
    }

    Cursor c = null;
    try {
        c = getContentResolver().query(ScheduleContract.Sessions.CONTENT_MY_SCHEDULE_URI,
                SessionsNeedingFeedbackQuery.PROJECTION, SessionsNeedingFeedbackQuery.WHERE_CLAUSE, null, null);
        if (c == null) {
            return;
        }

        FeedbackHelper feedbackHelper = new FeedbackHelper(this);

        List<String> needFeedbackIds = new ArrayList<String>();
        List<String> needFeedbackTitles = new ArrayList<String>();
        while (c.moveToNext()) {
            String sessionId = c.getString(SessionsNeedingFeedbackQuery.SESSION_ID);
            String sessionTitle = c.getString(SessionsNeedingFeedbackQuery.SESSION_TITLE);

            // Avoid repeated notifications.
            if (feedbackHelper.isFeedbackNotificationFiredForSession(sessionId)) {
                LOGD(TAG, "Skipping repeated session feedback notification for session '" + sessionTitle + "'");
                continue;
            }

            needFeedbackIds.add(sessionId);
            needFeedbackTitles.add(sessionTitle);
        }

        if (needFeedbackIds.size() == 0) {
            // the user has already been notified of all sessions needing feedback
            return;
        }

        LOGD(TAG, "Going forward with session feedback notification for " + needFeedbackIds.size()
                + " session(s).");

        final Resources res = getResources();

        // this is used to synchronize deletion of notifications on phone and wear
        Intent dismissalIntent = new Intent(ACTION_NOTIFICATION_DISMISSAL);
        // TODO: fix Wear dismiss integration
        //dismissalIntent.putExtra(KEY_SESSION_ID, sessionId);
        PendingIntent dismissalPendingIntent = PendingIntent.getService(this, (int) new Date().getTime(),
                dismissalIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        String provideFeedbackTicker = res.getString(R.string.session_feedback_notification_ticker);
        NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(this)
                .setColor(getResources().getColor(R.color.theme_primary)).setContentText(provideFeedbackTicker)
                .setTicker(provideFeedbackTicker)
                .setLights(SessionAlarmService.NOTIFICATION_ARGB_COLOR,
                        SessionAlarmService.NOTIFICATION_LED_ON_MS, SessionAlarmService.NOTIFICATION_LED_OFF_MS)
                .setSmallIcon(R.drawable.ic_stat_notification).setPriority(Notification.PRIORITY_LOW)
                .setLocalOnly(true) // make it local to the phone
                .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
                .setDeleteIntent(dismissalPendingIntent).setAutoCancel(true);

        if (needFeedbackIds.size() == 1) {
            // Only 1 session needs feedback
            Uri sessionUri = ScheduleContract.Sessions.buildSessionUri(needFeedbackIds.get(0));
            PendingIntent pi = TaskStackBuilder.create(this)
                    .addNextIntent(new Intent(this, MyScheduleActivity.class))
                    .addNextIntent(
                            new Intent(Intent.ACTION_VIEW, sessionUri, this, SessionFeedbackActivity.class))
                    .getPendingIntent(1, PendingIntent.FLAG_CANCEL_CURRENT);

            notifBuilder.setContentTitle(needFeedbackTitles.get(0)).setContentIntent(pi);
        } else {
            // Show information about several sessions that need feedback
            PendingIntent pi = TaskStackBuilder.create(this)
                    .addNextIntent(new Intent(this, MyScheduleActivity.class))
                    .getPendingIntent(1, PendingIntent.FLAG_CANCEL_CURRENT);

            NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
            inboxStyle.setBigContentTitle(provideFeedbackTicker);
            for (String title : needFeedbackTitles) {
                inboxStyle.addLine(title);
            }

            notifBuilder
                    .setContentTitle(getResources().getQuantityString(R.plurals.session_plurals,
                            needFeedbackIds.size(), needFeedbackIds.size()))
                    .setStyle(inboxStyle).setContentIntent(pi);
        }

        NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        LOGD(TAG, "Now showing session feedback notification!");
        nm.notify(FEEDBACK_NOTIFICATION_ID, notifBuilder.build());

        /*for (int i = 0; i < needFeedbackIds.size(); i++) {
        setupNotificationOnWear(needFeedbackIds.get(i), null, needFeedbackTitles.get(i), null);
        feedbackHelper.setFeedbackNotificationAsFiredForSession(needFeedbackIds.get(i));
        }*/
    } finally {
        if (c != null) {
            try {
                c.close();
            } catch (Exception ignored) {
            }
        }
    }
}

From source file:com.fututel.service.SipNotifications.java

public void showNotificationForMessage(SipMessage msg) {
    if (!CustomDistribution.supportMessaging()) {
        return;/*from  w w w. j  a  v a  2  s  . c o  m*/
    }
    // CharSequence tickerText = context.getText(R.string.instance_message);
    if (!msg.getFrom().equalsIgnoreCase(viewingRemoteFrom)) {
        String from = formatRemoteContactString(msg.getFullFrom());
        if (from.equalsIgnoreCase(msg.getFullFrom())) {
            from = msg.getDisplayName() + " " + from;
        }
        CharSequence tickerText = buildTickerMessage(context, from, msg.getBody());

        if (messageNotification == null) {
            messageNotification = new NotificationCompat.Builder(context);
            messageNotification.setSmallIcon(SipUri.isPhoneNumber(from) ? R.drawable.stat_notify_sms
                    : android.R.drawable.stat_notify_chat);
            messageNotification.setTicker(tickerText);
            messageNotification.setWhen(System.currentTimeMillis());
            messageNotification.setDefaults(Notification.DEFAULT_ALL);
            messageNotification.setAutoCancel(true);
            messageNotification.setOnlyAlertOnce(true);
        }

        Intent notificationIntent = new Intent(SipManager.ACTION_SIP_MESSAGES);
        notificationIntent.putExtra(SipMessage.FIELD_FROM, msg.getFrom());
        notificationIntent.putExtra(SipMessage.FIELD_BODY, msg.getBody());
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        messageNotification.setContentTitle(from);
        messageNotification.setContentText(msg.getBody());
        messageNotification.setContentIntent(contentIntent);

        notificationManager.notify(MESSAGE_NOTIF_ID, messageNotification.build());
    }
}

From source file:com.mobiperf.MeasurementScheduler.java

private void handleMeasurement() {
    if (!userConsented()) {
        Logger.i("Skipping measurement - User has not consented");
        return;//  ww  w  .java 2 s.co  m
    }

    try {
        MeasurementTask task = taskQueue.peek();
        // Process the head of the queue.
        if (task != null && task.timeFromExecution() <= 0) {
            taskQueue.poll();
            Future<MeasurementResult> future;
            Logger.i("Processing task " + task.toString());
            // Run the head task using the executor
            if (task.getDescription().priority == MeasurementTask.USER_PRIORITY) {
                sendStringMsg("Scheduling user task:\n" + task);
                // User task can override the power policy. So a different task wrapper is used.
                future = measurementExecutor.submit(new UserMeasurementTask(task));
            } else {
                sendStringMsg("Scheduling task:\n" + task);
                future = measurementExecutor.submit(new PowerAwareTask(task, resourceCapManager, this));
            }
            synchronized (pendingTasks) {
                pendingTasks.put(task, future);
            }

            MeasurementDesc desc = task.getDescription();

            long newStartTime = desc.startTime.getTime() + (long) desc.intervalSec * 1000;

            // Add a clone of the task if it's still valid.
            if (newStartTime < desc.endTime.getTime()
                    && (desc.count == MeasurementTask.INFINITE_COUNT || desc.count > 1)) {
                MeasurementTask newTask = task.clone();
                if (desc.count != MeasurementTask.INFINITE_COUNT) {
                    newTask.getDescription().count--;
                }
                newTask.getDescription().startTime.setTime(newStartTime);
                submitTask(newTask);
            }
        }
        // Schedule the next measurement in the taskQueue
        task = taskQueue.peek();
        if (task != null) {
            long timeFromExecution = Math.max(task.timeFromExecution(),
                    Config.MIN_TIME_BETWEEN_MEASUREMENT_ALARM_MSEC);
            measurementIntentSender = PendingIntent.getBroadcast(this, 0,
                    new UpdateIntent("", UpdateIntent.MEASUREMENT_ACTION), PendingIntent.FLAG_CANCEL_CURRENT);
            alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + timeFromExecution,
                    measurementIntentSender);
        }
    } catch (IllegalArgumentException e) {
        // Task creation in clone can create this exception
        Logger.e("Exception when cloning task");
        sendStringMsg("Exception when cloning task: " + e);
    } catch (Exception e) {
        // We don't want any unexpected exception to crash the process
        Logger.e("Exception when handling measurements", e);
        sendStringMsg("Exception running task: " + e);
    }
    persistState();
}

From source file:com.csipsimple.service.SipNotifications.java

public void showNotificationForMessage(SipMessage msg) {
    if (!CustomDistribution.supportMessaging()) {
        return;/*from  www .  j a  va  2  s. c o m*/
    }
    // CharSequence tickerText = context.getText(R.string.instance_message);
    if (!msg.getFrom().equalsIgnoreCase(viewingRemoteFrom)) {
        String from = formatRemoteContactString(msg.getFullFrom());
        if (from.equalsIgnoreCase(msg.getFullFrom()) && !from.equals(msg.getDisplayName())) {
            from = msg.getDisplayName() + " " + from;
        }
        CharSequence tickerText = buildTickerMessage(context, from, msg.getBody());

        if (messageNotification == null) {
            messageNotification = new NotificationCompat.Builder(context);
            messageNotification.setSmallIcon(SipUri.isPhoneNumber(from) ? R.drawable.stat_notify_sms
                    : android.R.drawable.stat_notify_chat);
            messageNotification.setTicker(tickerText);
            messageNotification.setWhen(System.currentTimeMillis());
            messageNotification.setDefaults(Notification.DEFAULT_ALL);
            messageNotification.setAutoCancel(true);
            messageNotification.setOnlyAlertOnce(true);
        }

        Intent notificationIntent = new Intent(SipManager.ACTION_SIP_MESSAGES);
        notificationIntent.putExtra(SipMessage.FIELD_FROM, msg.getFrom());
        notificationIntent.putExtra(SipMessage.FIELD_BODY, msg.getBody());
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        messageNotification.setContentTitle(from);
        messageNotification.setContentText(msg.getBody());
        messageNotification.setContentIntent(contentIntent);

        notificationManager.notify(MESSAGE_NOTIF_ID, messageNotification.build());
    }
}

From source file:de.ub0r.android.smsdroid.SmsReceiver.java

/**
 * Update new message {@link Notification}.
 *
 * @param context {@link Context}/*  w  w  w.  j  a v  a  2s  .com*/
 * @param text    text of the last assumed unread message
 * @return number of unread messages
 */
static int updateNewMessageNotification(final Context context, final String text) {
    Log.d(TAG, "updNewMsgNoti(", context, ",", text, ")");
    final NotificationManager mNotificationMgr = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    final boolean enableNotifications = prefs.getBoolean(PreferencesActivity.PREFS_NOTIFICATION_ENABLE, true);
    final boolean privateNotification = prefs.getBoolean(PreferencesActivity.PREFS_NOTIFICATION_PRIVACY, false);
    final boolean showPhoto = !privateNotification
            && prefs.getBoolean(PreferencesActivity.PREFS_CONTACT_PHOTO, true);
    if (!enableNotifications) {
        mNotificationMgr.cancelAll();
        Log.d(TAG, "no notification needed!");
    }
    final int[] status = getUnread(context.getContentResolver(), text);
    final int l = status[ID_COUNT];
    final int tid = status[ID_TID];

    // FIXME l is always -1..
    Log.d(TAG, "l: ", l);
    if (l < 0) {
        return l;
    }

    if (enableNotifications && (text != null || l == 0)) {
        mNotificationMgr.cancel(NOTIFICATION_ID_NEW);
    }
    Uri uri;
    PendingIntent pIntent;
    if (l == 0) {
        final Intent i = new Intent(context, ConversationListActivity.class);
        // add pending intent
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        pIntent = PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
    } else {
        final NotificationCompat.Builder nb = new NotificationCompat.Builder(context);
        boolean showNotification = true;
        Intent i;
        if (tid >= 0) {
            uri = Uri.parse(MessageListActivity.URI + tid);
            i = new Intent(Intent.ACTION_VIEW, uri, context, MessageListActivity.class);
            pIntent = PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);

            if (enableNotifications) {
                final Conversation conv = Conversation.getConversation(context, tid, true);
                if (conv != null) {
                    String a;
                    if (privateNotification) {
                        if (l == 1) {
                            a = context.getString(R.string.new_message_);
                        } else {
                            a = context.getString(R.string.new_messages_);
                        }
                    } else {
                        a = conv.getContact().getDisplayName();
                    }
                    showNotification = true;
                    nb.setSmallIcon(PreferencesActivity.getNotificationIcon(context));
                    nb.setTicker(a);
                    nb.setWhen(lastUnreadDate);
                    if (l == 1) {
                        String body;
                        if (privateNotification) {
                            body = context.getString(R.string.new_message);
                        } else {
                            body = lastUnreadBody;
                        }
                        if (body == null) {
                            body = context.getString(R.string.mms_conversation);
                        }
                        nb.setContentTitle(a);
                        nb.setContentText(body);
                        nb.setContentIntent(pIntent);
                        // add long text
                        nb.setStyle(new NotificationCompat.BigTextStyle().bigText(body));

                        // add actions
                        Intent nextIntent = new Intent(NotificationBroadcastReceiver.ACTION_MARK_READ);
                        nextIntent.putExtra(NotificationBroadcastReceiver.EXTRA_MURI, uri.toString());
                        PendingIntent nextPendingIntent = PendingIntent.getBroadcast(context, 0, nextIntent,
                                PendingIntent.FLAG_UPDATE_CURRENT);

                        nb.addAction(R.drawable.ic_menu_mark, context.getString(R.string.mark_read_),
                                nextPendingIntent);
                        nb.addAction(R.drawable.ic_menu_compose, context.getString(R.string.reply), pIntent);
                    } else {
                        nb.setContentTitle(a);
                        nb.setContentText(context.getString(R.string.new_messages, l));
                        nb.setContentIntent(pIntent);
                    }
                    if (showPhoto // just for the speeeeed
                            && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                        try {
                            conv.getContact().update(context, false, true);
                        } catch (NullPointerException e) {
                            Log.e(TAG, "updating contact failed", e);
                        }
                        Drawable d = conv.getContact().getAvatar(context, null);
                        if (d instanceof BitmapDrawable) {
                            Bitmap bitmap = ((BitmapDrawable) d).getBitmap();
                            // 24x24 dp according to android iconography  ->
                            // http://developer.android.com/design/style/iconography.html#notification
                            int px = Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 64,
                                    context.getResources().getDisplayMetrics()));
                            nb.setLargeIcon(Bitmap.createScaledBitmap(bitmap, px, px, false));
                        }
                    }
                }
            }
        } else {
            uri = Uri.parse(MessageListActivity.URI);
            i = new Intent(Intent.ACTION_VIEW, uri, context, ConversationListActivity.class);
            pIntent = PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);

            if (enableNotifications) {
                showNotification = true;
                nb.setSmallIcon(PreferencesActivity.getNotificationIcon(context));
                nb.setTicker(context.getString(R.string.new_messages_));
                nb.setWhen(lastUnreadDate);
                nb.setContentTitle(context.getString(R.string.new_messages_));
                nb.setContentText(context.getString(R.string.new_messages, l));
                nb.setContentIntent(pIntent);
                nb.setNumber(l);
            }
        }
        // add pending intent
        i.setFlags(i.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);

        if (enableNotifications && showNotification) {
            int[] ledFlash = PreferencesActivity.getLEDflash(context);
            nb.setLights(PreferencesActivity.getLEDcolor(context), ledFlash[0], ledFlash[1]);
            final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(context);
            if (text != null) {
                final boolean vibrate = p.getBoolean(PreferencesActivity.PREFS_VIBRATE, false);
                final String s = p.getString(PreferencesActivity.PREFS_SOUND, null);
                Uri sound;
                if (s == null || s.length() <= 0) {
                    sound = null;
                } else {
                    sound = Uri.parse(s);
                }
                if (vibrate) {
                    final long[] pattern = PreferencesActivity.getVibratorPattern(context);
                    if (pattern.length == 1 && pattern[0] == 0) {
                        nb.setDefaults(Notification.DEFAULT_VIBRATE);
                    } else {
                        nb.setVibrate(pattern);
                    }
                }
                nb.setSound(sound);
            }
        }
        Log.d(TAG, "uri: ", uri);
        mNotificationMgr.cancel(NOTIFICATION_ID_NEW);
        if (enableNotifications && showNotification) {
            try {
                mNotificationMgr.notify(NOTIFICATION_ID_NEW, nb.getNotification());
            } catch (IllegalArgumentException e) {
                Log.e(TAG, "illegal notification: ", nb, e);
            }
        }
    }
    Log.d(TAG, "return ", l, " (2)");
    //noinspection ConstantConditions
    AppWidgetManager.getInstance(context).updateAppWidget(new ComponentName(context, WidgetProvider.class),
            WidgetProvider.getRemoteViews(context, l, pIntent));
    return l;
}

From source file:com.sip.pwc.sipphone.service.SipNotifications.java

public void showNotificationForMessage(SipMessage msg) {
    if (!CustomDistribution.supportMessaging()) {
        return;/*from  w  w w.  j av a 2 s. co m*/
    }
    // CharSequence tickerText = context.getText(R.string.instance_message);
    if (!msg.getFrom().equalsIgnoreCase(viewingRemoteFrom)) {
        String from = formatRemoteContactString(msg.getFullFrom());
        if (from.equalsIgnoreCase(msg.getFullFrom()) && !from.equals(msg.getDisplayName())) {
            from = msg.getDisplayName() + " " + from;
        }
        CharSequence tickerText = buildTickerMessage(context, from, msg.getBody());

        if (messageNotification == null) {
            messageNotification = new NotificationCompat.Builder(context);
            messageNotification.setSmallIcon(SipUri.isPhoneNumber(from) ? R.mipmap.stat_notify_sms
                    : android.R.drawable.stat_notify_chat);
            messageNotification.setTicker(tickerText);
            messageNotification.setWhen(System.currentTimeMillis());
            messageNotification.setDefaults(Notification.DEFAULT_ALL);
            messageNotification.setAutoCancel(true);
            messageNotification.setOnlyAlertOnce(true);
        }

        Intent notificationIntent = new Intent(SipManager.ACTION_SIP_MESSAGES);
        notificationIntent.putExtra(SipMessage.FIELD_FROM, msg.getFrom());
        notificationIntent.putExtra(SipMessage.FIELD_BODY, msg.getBody());
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        messageNotification.setContentTitle(from);
        messageNotification.setContentText(msg.getBody());
        messageNotification.setContentIntent(contentIntent);

        notificationManager.notify(MESSAGE_NOTIF_ID, messageNotification.build());
    }
}

From source file:com.android.launcher3.widget.DigitalAppWidgetProvider.java

/**
 * Create the pending intent that is broadcast on the quarter hour.
 *
 * @param context The Context in which this PendingIntent should perform the broadcast.
 * @return a pending intent with an intent unique to DigitalAppWidgetProvider
 *///from   ww w . java  2s.c  o  m
private PendingIntent getOnQuarterHourPendingIntent(Context context) {
    if (mPendingIntent == null) {
        mPendingIntent = PendingIntent.getBroadcast(context, 0, new Intent(ACTION_ON_QUARTER_HOUR),
                PendingIntent.FLAG_CANCEL_CURRENT);
    }
    return mPendingIntent;
}