Example usage for android.support.v4.app NotificationManagerCompat from

List of usage examples for android.support.v4.app NotificationManagerCompat from

Introduction

In this page you can find the example usage for android.support.v4.app NotificationManagerCompat from.

Prototype

public static NotificationManagerCompat from(Context context) 

Source Link

Usage

From source file:com.secupwn.aimsicd.service.CellTracker.java

/**
 *  Description:    Set or update the Detection/Status Notification
 *                  TODO: Need to add status HIGH (Orange) and SKULL (Black)
 *
 *  Issues:/*from   w w  w  .jav a2 s.c  o  m*/
 *      See:  https://github.com/SecUpwN/Android-IMSI-Catcher-Detector/wiki/Status-Icons
 *      and:  https://github.com/SecUpwN/Android-IMSI-Catcher-Detector/issues/11#issuecomment-44670204
 *
 *  [ ] We need to standardize the "contentText" and "tickerText" format
 *
 *  [ ] From #91: https://github.com/SecUpwN/Android-IMSI-Catcher-Detector/issues/91
 *
 *      Problem:
 *          Having multiple notifications will cause an issue with
 *      notifications themselves AND tickerText.  It seems that the
 *      most recent notification raised would overwrite any previous,
 *      notification or tickerText.  This results in loss of information
 *      for any notification before the last one.
 *
 *      Possible Solution:
 *          Perhaps arranging a queue implementation to deal with text
 *      being passed into tickerText only when any previous text has
 *      been entirely displayed.
 *
 *  Dependencies:    Status.java, CellTracker.java, Icon.java ( + others?)
 *
 */
void setNotification() {
    String tickerText;
    String contentText = "Phone Type " + device.getPhoneType();

    if (femtoDetected || typeZeroSmsDetected) {
        getApplication().setCurrentStatus(Status.DANGER, vibrateEnabled, vibrateMinThreatLevel);
    } else if (changedLAC) {
        getApplication().setCurrentStatus(Status.MEDIUM, vibrateEnabled, vibrateMinThreatLevel);
        contentText = context.getString(R.string.hostile_service_area_changing_lac_detected);
    } else if (emptyNeighborCellsList) {
        getApplication().setCurrentStatus(Status.MEDIUM, vibrateEnabled, vibrateMinThreatLevel);
        contentText = context.getString(R.string.cell_doesnt_provide_any_neighbors);
    } else if (cellIdNotInOpenDb) {
        getApplication().setCurrentStatus(Status.MEDIUM, vibrateEnabled, vibrateMinThreatLevel);
        contentText = context.getString(R.string.cell_id_doesnt_exist_in_db);
    } else if (trackingFemtocell || trackingCell || monitoringCell) {
        getApplication().setCurrentStatus(Status.OK, vibrateEnabled, vibrateMinThreatLevel);
        if (trackingFemtocell) {
            contentText = context.getString(R.string.femtocell_detection_active);
        } else if (trackingCell) {
            contentText = context.getString(R.string.cell_tracking_active);
        }
        if (monitoringCell) {
            contentText = context.getString(R.string.cell_monitoring_active);
        } else {
            getApplication().setCurrentStatus(Status.IDLE, vibrateEnabled, vibrateMinThreatLevel);
        }
    } else {
        getApplication().setCurrentStatus(Status.IDLE, vibrateEnabled, vibrateMinThreatLevel);
    }

    Status status = getApplication().getStatus();
    switch (status) {
    case IDLE: // GRAY
        contentText = context.getString(R.string.phone_type) + device.getPhoneType();
        tickerText = context.getResources().getString(R.string.app_name_short) + " "
                + context.getString(R.string.status_idle_description);
        break;

    case OK: // GREEN
        tickerText = context.getResources().getString(R.string.app_name_short) + " "
                + context.getString(R.string.status_ok_description);
        break;

    case MEDIUM: // YELLOW
        // Initialize tickerText as the app name string
        // See multiple detection comments above.
        tickerText = context.getResources().getString(R.string.app_name_short);
        if (changedLAC) {
            //Append changing LAC text
            contentText = context.getString(R.string.hostile_service_area_changing_lac_detected);
            tickerText += " - " + contentText;
        } else if (emptyNeighborCellsList) {
            //According to #264
            contentText = context.getString(R.string.cell_doesnt_provide_any_neighbors);
            tickerText += " - " + contentText;
        } else if (cellIdNotInOpenDb) {
            //Append Cell ID not existing in external db text
            contentText = context.getString(R.string.cell_id_doesnt_exist_in_db);
            tickerText += " - " + contentText;
        }
        break;

    case DANGER: // RED
        tickerText = context.getResources().getString(R.string.app_name_short) + " - "
                + context.getString(R.string.alert_threat_detected); // Hmm, this is vague!
        if (femtoDetected) {
            contentText = context.getString(R.string.alert_femtocell_connection_detected);
        } else if (typeZeroSmsDetected) {
            contentText = context.getString(R.string.alert_silent_sms_detected);
        }

        break;
    default:
        tickerText = context.getResources().getString(R.string.main_app_name);
        break;
    }

    // TODO: Explanation (see above)
    Intent notificationIntent = new Intent(context, MainActivity.class);
    notificationIntent.putExtra("silent_sms", typeZeroSmsDetected);
    notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_FROM_BACKGROUND);
    PendingIntent contentIntent = PendingIntent.getActivity(context, NOTIFICATION_ID, notificationIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);
    String iconType = prefs.getString(context.getString(R.string.pref_ui_icons_key), "SENSE").toUpperCase();
    int iconResId = Icon.getIcon(Icon.Type.valueOf(iconType), status);
    Bitmap largeIcon = BitmapFactory.decodeResource(context.getResources(), iconResId);

    int color = context.getResources().getColor(status.getColor());

    Notification notification = new NotificationCompat.Builder(context).setSmallIcon(R.drawable.tower48)
            .setColor(color).setLargeIcon(largeIcon).setTicker(tickerText)
            .setContentTitle(context.getString(R.string.status) + " " + context.getString(status.getName()))
            .setContentInfo(context.getResources().getString(R.string.app_name_short))
            .setContentText(contentText).setOngoing(true).setAutoCancel(false).setContentIntent(contentIntent)
            .build();

    NotificationManagerCompat.from(context).notify(NOTIFICATION_ID, notification);

}

From source file:com.rks.musicx.services.MusicXService.java

private void removeNotification() {
    NotificationManagerCompat.from(this).cancel(notificationID);
}

From source file:com.android.mms.transaction.MessagingNotification.java

/**
 * updateNotification is *the* main function for building the actual notification handed to
 * the NotificationManager//from  w  w w . j a va2 s  .  com
 * @param context
 * @param newThreadId the new thread id
 * @param uniqueThreadCount
 * @param notificationSet the set of notifications to display
 */
private static void updateNotification(Context context, long newThreadId, int uniqueThreadCount,
        SortedSet<NotificationInfo> notificationSet) {
    boolean isNew = newThreadId != THREAD_NONE;
    CMConversationSettings conversationSettings = CMConversationSettings.getOrNew(context, newThreadId);

    // If the user has turned off notifications in settings, don't do any notifying.
    if ((isNew && !conversationSettings.getNotificationEnabled())
            || !MessagingPreferenceActivity.getNotificationEnabled(context)) {
        if (DEBUG) {
            Log.d(TAG, "updateNotification: notifications turned off in prefs, bailing");
        }
        return;
    }

    // Figure out what we've got -- whether all sms's, mms's, or a mixture of both.
    final int messageCount = notificationSet.size();
    NotificationInfo mostRecentNotification = notificationSet.first();

    final NotificationCompat.Builder noti = new NotificationCompat.Builder(context)
            .setWhen(mostRecentNotification.mTimeMillis);

    if (isNew) {
        noti.setTicker(mostRecentNotification.mTicker);
    }

    // If we have more than one unique thread, change the title (which would
    // normally be the contact who sent the message) to a generic one that
    // makes sense for multiple senders, and change the Intent to take the
    // user to the conversation list instead of the specific thread.

    // Cases:
    //   1) single message from single thread - intent goes to ComposeMessageActivity
    //   2) multiple messages from single thread - intent goes to ComposeMessageActivity
    //   3) messages from multiple threads - intent goes to ConversationList

    final Resources res = context.getResources();
    String title = null;
    Bitmap avatar = null;
    PendingIntent pendingIntent = null;
    boolean isMultiNewMessages = MessageUtils.isMailboxMode() ? messageCount > 1 : uniqueThreadCount > 1;
    if (isMultiNewMessages) { // messages from multiple threads
        Intent mainActivityIntent = getMultiThreadsViewIntent(context);
        pendingIntent = PendingIntent.getActivity(context, 0, mainActivityIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        title = context.getString(R.string.message_count_notification, messageCount);
    } else { // same thread, single or multiple messages
        title = mostRecentNotification.mTitle;
        avatar = mostRecentNotification.mSender.getAvatar(context);
        noti.setSubText(mostRecentNotification.mSimName); // no-op in single SIM case
        if (avatar != null) {
            // Show the sender's avatar as the big icon. Contact bitmaps are 96x96 so we
            // have to scale 'em up to 128x128 to fill the whole notification large icon.
            final int idealIconHeight = res
                    .getDimensionPixelSize(android.R.dimen.notification_large_icon_height);
            final int idealIconWidth = res.getDimensionPixelSize(android.R.dimen.notification_large_icon_width);
            noti.setLargeIcon(BitmapUtil.getRoundedBitmap(avatar, idealIconWidth, idealIconHeight));
        }

        pendingIntent = PendingIntent.getActivity(context, 0, mostRecentNotification.mClickIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
    }
    // Always have to set the small icon or the notification is ignored
    noti.setSmallIcon(R.drawable.stat_notify_sms);

    NotificationManagerCompat nm = NotificationManagerCompat.from(context);

    // Update the notification.
    noti.setContentTitle(title).setContentIntent(pendingIntent)
            .setColor(context.getResources().getColor(R.color.mms_theme_color))
            .setCategory(Notification.CATEGORY_MESSAGE).setPriority(Notification.PRIORITY_DEFAULT); // TODO: set based on contact coming
                                                                                                                                                                                                                                  // from a favorite.

    // Tag notification with all senders.
    for (NotificationInfo info : notificationSet) {
        Uri peopleReferenceUri = info.mSender.getPeopleReferenceUri();
        if (peopleReferenceUri != null) {
            noti.addPerson(peopleReferenceUri.toString());
        }
    }

    int defaults = 0;

    if (isNew) {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);

        if (conversationSettings.getVibrateEnabled()) {
            String pattern = conversationSettings.getVibratePattern();

            if (!TextUtils.isEmpty(pattern)) {
                noti.setVibrate(parseVibratePattern(pattern));
            } else {
                defaults |= Notification.DEFAULT_VIBRATE;
            }
        }

        String ringtoneStr = conversationSettings.getNotificationTone();
        noti.setSound(TextUtils.isEmpty(ringtoneStr) ? null : Uri.parse(ringtoneStr));
        Log.d(TAG, "updateNotification: new message, adding sound to the notification");
    }

    defaults |= Notification.DEFAULT_LIGHTS;

    noti.setDefaults(defaults);

    // set up delete intent
    noti.setDeleteIntent(PendingIntent.getBroadcast(context, 0, sNotificationOnDeleteIntent, 0));

    // See if QuickMessage pop-up support is enabled in preferences
    boolean qmPopupEnabled = MessagingPreferenceActivity.getQuickMessageEnabled(context);

    // Set up the QuickMessage intent
    Intent qmIntent = null;
    if (mostRecentNotification.mIsSms) {
        // QuickMessage support is only for SMS
        qmIntent = new Intent();
        qmIntent.setClass(context, QuickMessagePopup.class);
        qmIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP
                | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        qmIntent.putExtra(QuickMessagePopup.SMS_FROM_NAME_EXTRA, mostRecentNotification.mSender.getName());
        qmIntent.putExtra(QuickMessagePopup.SMS_FROM_NUMBER_EXTRA, mostRecentNotification.mSender.getNumber());
        qmIntent.putExtra(QuickMessagePopup.SMS_NOTIFICATION_OBJECT_EXTRA, mostRecentNotification);
    }

    // Start getting the notification ready
    final Notification notification;

    //Create a WearableExtender to add actions too
    WearableExtender wearableExtender = new WearableExtender();

    if (messageCount == 1 || uniqueThreadCount == 1) {
        // Add the Quick Reply action only if the pop-up won't be shown already
        if (!qmPopupEnabled && qmIntent != null) {

            // This is a QR, we should show the keyboard when the user taps to reply
            qmIntent.putExtra(QuickMessagePopup.QR_SHOW_KEYBOARD_EXTRA, true);

            // Create the pending intent and add it to the notification
            CharSequence qmText = context.getText(R.string.menu_reply);
            PendingIntent qmPendingIntent = PendingIntent.getActivity(context, 0, qmIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            noti.addAction(R.drawable.ic_reply, qmText, qmPendingIntent);

            //Wearable
            noti.extend(wearableExtender.addAction(
                    new NotificationCompat.Action.Builder(R.drawable.ic_reply, qmText, qmPendingIntent)
                            .build()));
        }

        // Add the 'Mark as read' action
        CharSequence markReadText = context.getText(R.string.qm_mark_read);
        Intent mrIntent = new Intent();
        mrIntent.setClass(context, QmMarkRead.class);
        mrIntent.putExtra(QmMarkRead.SMS_THREAD_ID, mostRecentNotification.mThreadId);
        PendingIntent mrPendingIntent = PendingIntent.getBroadcast(context, 0, mrIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        noti.addAction(R.drawable.ic_mark_read, markReadText, mrPendingIntent);

        // Add the Call action
        CharSequence callText = context.getText(R.string.menu_call);
        Intent callIntent = new Intent(Intent.ACTION_CALL);
        callIntent.setData(Uri.parse("tel:" + mostRecentNotification.mSender.getNumber()));
        PendingIntent callPendingIntent = PendingIntent.getActivity(context, 0, callIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        noti.addAction(R.drawable.ic_menu_call, callText, callPendingIntent);

        //Wearable
        noti.extend(wearableExtender.addAction(
                new NotificationCompat.Action.Builder(R.drawable.ic_menu_call, callText, callPendingIntent)
                        .build()));

        //Set up remote input
        String replyLabel = context.getString(R.string.qm_wear_voice_reply);
        RemoteInput remoteInput = new RemoteInput.Builder(QuickMessageWear.EXTRA_VOICE_REPLY)
                .setLabel(replyLabel).build();
        //Set up pending intent for voice reply
        Intent voiceReplyIntent = new Intent(context, QuickMessageWear.class);
        voiceReplyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP
                | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        voiceReplyIntent.putExtra(QuickMessageWear.SMS_CONATCT, mostRecentNotification.mSender.getName());
        voiceReplyIntent.putExtra(QuickMessageWear.SMS_SENDER, mostRecentNotification.mSender.getNumber());
        voiceReplyIntent.putExtra(QuickMessageWear.SMS_THEAD_ID, mostRecentNotification.mThreadId);
        PendingIntent voiceReplyPendingIntent = PendingIntent.getActivity(context, 0, voiceReplyIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        //Wearable voice reply action
        NotificationCompat.Action action = new NotificationCompat.Action.Builder(R.drawable.ic_reply,
                context.getString(R.string.qm_wear_reply_by_voice), voiceReplyPendingIntent)
                        .addRemoteInput(remoteInput).build();
        noti.extend(wearableExtender.addAction(action));
    }

    if (messageCount == 1) {
        // We've got a single message

        // This sets the text for the collapsed form:
        noti.setContentText(mostRecentNotification.formatBigMessage(context));

        if (mostRecentNotification.mAttachmentBitmap != null) {
            // The message has a picture, show that

            NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle(noti)
                    .bigPicture(mostRecentNotification.mAttachmentBitmap)
                    .setSummaryText(mostRecentNotification.formatPictureMessage(context));

            notification = noti.setStyle(bigPictureStyle).build();
        } else {
            // Show a single notification -- big style with the text of the whole message
            NotificationCompat.BigTextStyle bigTextStyle1 = new NotificationCompat.BigTextStyle(noti)
                    .bigText(mostRecentNotification.formatBigMessage(context));

            notification = noti.setStyle(bigTextStyle1).build();
        }
        if (DEBUG) {
            Log.d(TAG, "updateNotification: single message notification");
        }
    } else {
        // We've got multiple messages
        if (!isMultiNewMessages) {
            // We've got multiple messages for the same thread.
            // Starting with the oldest new message, display the full text of each message.
            // Begin a line for each subsequent message.
            SpannableStringBuilder buf = new SpannableStringBuilder();
            NotificationInfo infos[] = notificationSet.toArray(new NotificationInfo[messageCount]);
            int len = infos.length;
            for (int i = len - 1; i >= 0; i--) {
                NotificationInfo info = infos[i];

                buf.append(info.formatBigMessage(context));

                if (i != 0) {
                    buf.append('\n');
                }
            }

            noti.setContentText(context.getString(R.string.message_count_notification, messageCount));

            // Show a single notification -- big style with the text of all the messages
            NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
            bigTextStyle.bigText(buf)
                    // Forcibly show the last line, with the app's smallIcon in it, if we
                    // kicked the smallIcon out with an avatar bitmap
                    .setSummaryText((avatar == null) ? null : " ");
            notification = noti.setStyle(bigTextStyle).build();
            if (DEBUG) {
                Log.d(TAG, "updateNotification: multi messages for single thread");
            }
        } else {
            // Build a set of the most recent notification per threadId.
            HashSet<Long> uniqueThreads = new HashSet<Long>(messageCount);
            ArrayList<NotificationInfo> mostRecentNotifPerThread = new ArrayList<NotificationInfo>();
            Iterator<NotificationInfo> notifications = notificationSet.iterator();
            while (notifications.hasNext()) {
                NotificationInfo notificationInfo = notifications.next();
                if (!uniqueThreads.contains(notificationInfo.mThreadId)) {
                    uniqueThreads.add(notificationInfo.mThreadId);
                    mostRecentNotifPerThread.add(notificationInfo);
                }
            }
            // When collapsed, show all the senders like this:
            //     Fred Flinstone, Barry Manilow, Pete...
            noti.setContentText(formatSenders(context, mostRecentNotifPerThread));
            NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(noti);

            // We have to set the summary text to non-empty so the content text doesn't show
            // up when expanded.
            inboxStyle.setSummaryText(" ");

            // At this point we've got multiple messages in multiple threads. We only
            // want to show the most recent message per thread, which are in
            // mostRecentNotifPerThread.
            int uniqueThreadMessageCount = mostRecentNotifPerThread.size();
            int maxMessages = Math.min(MAX_MESSAGES_TO_SHOW, uniqueThreadMessageCount);

            for (int i = 0; i < maxMessages; i++) {
                NotificationInfo info = mostRecentNotifPerThread.get(i);
                inboxStyle.addLine(info.formatInboxMessage(context));
            }
            notification = inboxStyle.build();

            uniqueThreads.clear();
            mostRecentNotifPerThread.clear();

            if (DEBUG) {
                Log.d(TAG, "updateNotification: multi messages," + " showing inboxStyle notification");
            }
        }
    }

    notifyUserIfFullScreen(context, title);
    nm.notify(NOTIFICATION_ID, notification);

    // Trigger the QuickMessage pop-up activity if enabled
    // But don't show the QuickMessage if the user is in a call or the phone is ringing
    if (qmPopupEnabled && qmIntent != null) {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        if (tm.getCallState() == TelephonyManager.CALL_STATE_IDLE && !ConversationList.mIsRunning
                && !ComposeMessageActivity.mIsRunning) {
            context.startActivity(qmIntent);
        }
    }
}

From source file:com.daiv.android.twitter.utils.NotificationUtils.java

public static void newInteractions(User interactor, Context context, SharedPreferences sharedPrefs,
        String type) {//from   w  ww .ja  v  a2s  . c o  m
    String title = "";
    String text = "";
    String smallText = "";
    Bitmap icon = null;

    AppSettings settings = AppSettings.getInstance(context);

    int newFollowers = sharedPrefs.getInt("new_followers", 0);
    int newRetweets = sharedPrefs.getInt("new_retweets", 0);
    int newFavorites = sharedPrefs.getInt("new_favorites", 0);
    int newQuotes = sharedPrefs.getInt("new_quotes", 0);

    // set title
    if (newFavorites + newRetweets + newFollowers > 1) {
        title = context.getResources().getString(R.string.new_interactions);
    } else {
        title = context.getResources().getString(R.string.new_interaction_upper);
    }

    // set text
    String currText = sharedPrefs.getString("old_interaction_text", "");
    if (!currText.equals("")) {
        currText += "<br>";
    }
    if (settings.displayScreenName) {
        text = currText + "<b>" + interactor.getScreenName() + "</b> " + type;
    } else {
        text = currText + "<b>" + interactor.getName() + "</b> " + type;
    }
    sharedPrefs.edit().putString("old_interaction_text", text).commit();

    // set icon
    int types = 0;
    if (newFavorites > 0) {
        types++;
    }
    if (newFollowers > 0) {
        types++;
    }
    if (newRetweets > 0) {
        types++;
    }
    if (newQuotes > 0) {
        types++;
    }

    if (types > 1) {
        icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_stat_icon);
    } else {
        if (newFavorites > 0) {
            icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_action_important_dark);
        } else if (newRetweets > 0) {
            icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_action_repeat_dark);
        } else {
            icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.drawer_user_dark);
        }
    }

    // set shorter text
    int total = newFavorites + newFollowers + newRetweets + newQuotes;
    if (total > 1) {
        smallText = total + " " + context.getResources().getString(R.string.new_interactions_lower);
    } else {
        smallText = text;
    }

    Intent markRead = new Intent(context, ReadInteractionsService.class);
    PendingIntent readPending = PendingIntent.getService(context, 0, markRead, 0);

    Intent deleteIntent = new Intent(context, NotificationDeleteReceiverOne.class);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context).setContentTitle(title)
            .setContentText(Html.fromHtml(
                    settings.addonTheme ? smallText.replaceAll("FF8800", settings.accentColor) : smallText))
            .setSmallIcon(R.drawable.ic_stat_icon).setLargeIcon(icon).setTicker(title)
            .setDeleteIntent(PendingIntent.getBroadcast(context, 0, deleteIntent, 0))
            .setPriority(NotificationCompat.PRIORITY_HIGH).setAutoCancel(true);

    if (context.getResources().getBoolean(R.bool.expNotifications)) {
        mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(
                Html.fromHtml(settings.addonTheme ? text.replaceAll("FF8800", settings.accentColor) : text)));
    }

    if (settings.vibrate) {
        mBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
    }

    if (settings.sound) {
        try {
            mBuilder.setSound(Uri.parse(settings.ringtone));
        } catch (Exception e) {
            mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
        }
    }

    if (settings.led)
        mBuilder.setLights(0xFFFFFF, 1000, 1000);

    if (settings.notifications) {

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);

        notificationManager.notify(4, mBuilder.build());

        // if we want to wake the screen on a new message
        if (settings.wakeScreen) {
            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            final PowerManager.WakeLock wakeLock = pm.newWakeLock((PowerManager.SCREEN_BRIGHT_WAKE_LOCK
                    | PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP), "TAG");
            wakeLock.acquire(5000);
        }

        // Pebble notification
        if (sharedPrefs.getBoolean("pebble_notification", false)) {
            sendAlertToPebble(context, title, text);
        }

        // Light Flow notification
        sendToLightFlow(context, title, text);
    }
}

From source file:com.android.messaging.datamodel.MessageNotificationState.java

/**
 * Check for failed messages and post notifications as needed.
 * TODO: Rewrite this as a NotificationState.
 *///  w  ww . j  av a2 s. c  om
public static void checkFailedMessages() {
    final DatabaseWrapper db = DataModel.get().getDatabase();

    final Cursor messageDataCursor = db.query(DatabaseHelper.MESSAGES_TABLE, MessageData.getProjection(),
            FailedMessageQuery.FAILED_MESSAGES_WHERE_CLAUSE, null /*selectionArgs*/, null /*groupBy*/,
            null /*having*/, FailedMessageQuery.FAILED_ORDER_BY);

    try {
        final Context context = Factory.get().getApplicationContext();
        final Resources resources = context.getResources();
        final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
        if (messageDataCursor != null) {
            final MessageData messageData = new MessageData();

            final HashSet<String> conversationsWithFailedMessages = new HashSet<String>();

            // track row ids in case we want to display something that requires this
            // information
            final ArrayList<Integer> failedMessages = new ArrayList<Integer>();

            int cursorPosition = -1;
            final long when = 0;

            messageDataCursor.moveToPosition(-1);
            while (messageDataCursor.moveToNext()) {
                messageData.bind(messageDataCursor);

                final String conversationId = messageData.getConversationId();
                if (DataModel.get().isNewMessageObservable(conversationId)) {
                    // Don't post a system notification for an observable conversation
                    // because we already show an angry red annotation in the conversation
                    // itself or in the conversation preview snippet.
                    continue;
                }

                cursorPosition = messageDataCursor.getPosition();
                failedMessages.add(cursorPosition);
                conversationsWithFailedMessages.add(conversationId);
            }

            if (LogUtil.isLoggable(TAG, LogUtil.DEBUG)) {
                LogUtil.d(TAG, "Found " + failedMessages.size() + " failed messages");
            }
            if (failedMessages.size() > 0) {
                final NotificationCompat.Builder builder = new NotificationCompat.Builder(context);

                CharSequence line1;
                CharSequence line2;
                final boolean isRichContent = false;
                ConversationIdSet conversationIds = null;
                PendingIntent destinationIntent;
                if (failedMessages.size() == 1) {
                    messageDataCursor.moveToPosition(cursorPosition);
                    messageData.bind(messageDataCursor);
                    final String conversationId = messageData.getConversationId();

                    // We have a single conversation, go directly to that conversation.
                    destinationIntent = UIIntents.get().getPendingIntentForConversationActivity(context,
                            conversationId, null /*draft*/);

                    conversationIds = ConversationIdSet.createSet(conversationId);

                    final String failedMessgeSnippet = messageData.getMessageText();
                    int failureStringId;
                    if (messageData.getStatus() == MessageData.BUGLE_STATUS_INCOMING_DOWNLOAD_FAILED) {
                        failureStringId = R.string.notification_download_failures_line1_singular;
                    } else {
                        failureStringId = R.string.notification_send_failures_line1_singular;
                    }
                    line1 = resources.getString(failureStringId);
                    line2 = failedMessgeSnippet;
                    // Set rich text for non-SMS messages or MMS push notification messages
                    // which we generate locally with rich text
                    // TODO- fix this
                    //                        if (messageData.isMmsInd()) {
                    //                            isRichContent = true;
                    //                        }
                } else {
                    // We have notifications for multiple conversation, go to the conversation
                    // list.
                    destinationIntent = UIIntents.get().getPendingIntentForConversationListActivity(context);

                    int line1StringId;
                    int line2PluralsId;
                    if (messageData.getStatus() == MessageData.BUGLE_STATUS_INCOMING_DOWNLOAD_FAILED) {
                        line1StringId = R.string.notification_download_failures_line1_plural;
                        line2PluralsId = R.plurals.notification_download_failures;
                    } else {
                        line1StringId = R.string.notification_send_failures_line1_plural;
                        line2PluralsId = R.plurals.notification_send_failures;
                    }
                    line1 = resources.getString(line1StringId);
                    line2 = resources.getQuantityString(line2PluralsId, conversationsWithFailedMessages.size(),
                            failedMessages.size(), conversationsWithFailedMessages.size());
                }
                line1 = applyWarningTextColor(context, line1);
                line2 = applyWarningTextColor(context, line2);

                final PendingIntent pendingIntentForDelete = UIIntents.get()
                        .getPendingIntentForClearingNotifications(context, BugleNotifications.UPDATE_ERRORS,
                                conversationIds, 0);

                builder.setContentTitle(line1).setTicker(line1)
                        .setWhen(when > 0 ? when : System.currentTimeMillis())
                        .setSmallIcon(R.drawable.ic_failed_light).setDeleteIntent(pendingIntentForDelete)
                        .setContentIntent(destinationIntent)
                        .setSound(UriUtil.getUriForResourceId(context, R.raw.message_failure));
                if (isRichContent && !TextUtils.isEmpty(line2)) {
                    final NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(builder);
                    if (line2 != null) {
                        inboxStyle.addLine(Html.fromHtml(line2.toString()));
                    }
                    builder.setStyle(inboxStyle);
                } else {
                    builder.setContentText(line2);
                }

                if (builder != null) {
                    notificationManager.notify(BugleNotifications
                            .buildNotificationTag(PendingIntentConstants.MSG_SEND_ERROR, null),
                            PendingIntentConstants.MSG_SEND_ERROR, builder.build());
                }
            } else {
                notificationManager.cancel(
                        BugleNotifications.buildNotificationTag(PendingIntentConstants.MSG_SEND_ERROR, null),
                        PendingIntentConstants.MSG_SEND_ERROR);
            }
        }
    } finally {
        if (messageDataCursor != null) {
            messageDataCursor.close();
        }
    }
}

From source file:com.klinker.android.twitter.utils.NotificationUtils.java

public static void newInteractions(User interactor, Context context, SharedPreferences sharedPrefs,
        String type) {//w  w w . j  av a  2  s  .  co  m
    String title = "";
    String text = "";
    String smallText = "";
    Bitmap icon = null;

    AppSettings settings = AppSettings.getInstance(context);

    Intent resultIntent = new Intent(context, RedirectToDrawer.class);
    PendingIntent resultPendingIntent = PendingIntent.getActivity(context, 0, resultIntent, 0);

    int newFollowers = sharedPrefs.getInt("new_followers", 0);
    int newRetweets = sharedPrefs.getInt("new_retweets", 0);
    int newFavorites = sharedPrefs.getInt("new_favorites", 0);
    int newQuotes = sharedPrefs.getInt("new_quotes", 0);

    // set title
    if (newFavorites + newRetweets + newFollowers > 1) {
        title = context.getResources().getString(R.string.new_interactions);
    } else {
        title = context.getResources().getString(R.string.new_interaction_upper);
    }

    // set text
    String currText = sharedPrefs.getString("old_interaction_text", "");
    if (!currText.equals("")) {
        currText += "<br>";
    }
    if (settings.displayScreenName) {
        text = currText + "<b>" + interactor.getScreenName() + "</b> " + type;
    } else {
        text = currText + "<b>" + interactor.getName() + "</b> " + type;
    }
    sharedPrefs.edit().putString("old_interaction_text", text).commit();

    // set icon
    int types = 0;
    if (newFavorites > 0) {
        types++;
    }
    if (newFollowers > 0) {
        types++;
    }
    if (newRetweets > 0) {
        types++;
    }
    if (newQuotes > 0) {
        types++;
    }

    if (types > 1) {
        icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_stat_icon);
    } else {
        if (newFavorites > 0) {
            icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_heart_dark);
        } else if (newRetweets > 0) {
            icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_action_repeat_dark);
        } else {
            icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.drawer_user_dark);
        }
    }

    // set shorter text
    int total = newFavorites + newFollowers + newRetweets + newQuotes;
    if (total > 1) {
        smallText = total + " " + context.getResources().getString(R.string.new_interactions_lower);
    } else {
        smallText = text;
    }

    Intent markRead = new Intent(context, ReadInteractionsService.class);
    PendingIntent readPending = PendingIntent.getService(context, 0, markRead, 0);

    Intent deleteIntent = new Intent(context, NotificationDeleteReceiverOne.class);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context).setContentTitle(title)
            .setContentText(Html.fromHtml(
                    settings.addonTheme ? smallText.replaceAll("FF8800", settings.accentColor) : smallText))
            .setSmallIcon(R.drawable.ic_stat_icon).setLargeIcon(icon).setContentIntent(resultPendingIntent)
            .setTicker(title).setDeleteIntent(PendingIntent.getBroadcast(context, 0, deleteIntent, 0))
            .setPriority(NotificationCompat.PRIORITY_HIGH).setAutoCancel(true);

    if (context.getResources().getBoolean(R.bool.expNotifications)) {
        mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(
                Html.fromHtml(settings.addonTheme ? text.replaceAll("FF8800", settings.accentColor) : text)));
    }

    if (settings.vibrate) {
        mBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
    }

    if (settings.sound) {
        try {
            mBuilder.setSound(Uri.parse(settings.ringtone));
        } catch (Exception e) {
            mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
        }
    }

    if (settings.led)
        mBuilder.setLights(0xFFFFFF, 1000, 1000);

    if (settings.notifications) {

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);

        notificationManager.notify(4, mBuilder.build());

        // if we want to wake the screen on a new message
        if (settings.wakeScreen) {
            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            final PowerManager.WakeLock wakeLock = pm.newWakeLock((PowerManager.SCREEN_BRIGHT_WAKE_LOCK
                    | PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP), "TAG");
            wakeLock.acquire(5000);
        }

        // Pebble notification
        if (sharedPrefs.getBoolean("pebble_notification", false)) {
            sendAlertToPebble(context, title, text);
        }

        // Light Flow notification
        sendToLightFlow(context, title, text);
    }
}

From source file:com.irccloud.android.data.collection.NotificationsList.java

public NotificationCompat.Builder alert(int bid, String title, String body) {
    Crashlytics.log(Log.DEBUG, "IRCCloud", "Posting alert notification");
    NotificationCompat.Builder builder = new NotificationCompat.Builder(
            IRCCloudApplication.getInstance().getApplicationContext()).setContentTitle(title)
                    .setContentText(body).setTicker(body).setAutoCancel(true)
                    .setColor(IRCCloudApplication.getInstance().getApplicationContext().getResources()
                            .getColor(R.color.ic_background))
                    .setSmallIcon(R.drawable.ic_stat_notify);

    Intent i = new Intent();
    i.setComponent(new ComponentName(IRCCloudApplication.getInstance().getApplicationContext().getPackageName(),
            "com.irccloud.android.MainActivity"));
    i.putExtra("bid", bid);
    i.setData(Uri.parse("bid://" + bid));
    builder.setContentIntent(//from  w  w  w  .j  av a 2s. c  om
            PendingIntent.getActivity(IRCCloudApplication.getInstance().getApplicationContext(), 0, i,
                    PendingIntent.FLAG_UPDATE_CURRENT));

    NotificationManagerCompat.from(IRCCloudApplication.getInstance().getApplicationContext()).notify(bid,
            builder.build());

    return builder;
}

From source file:com.daiv.android.twitter.utils.NotificationUtils.java

public static void sendTestNotification(Context context) {

    if (!TEST_NOTIFICATION) {
        return;/*from w w  w. ja  v a2  s. c  o  m*/
    }

    AppSettings settings = AppSettings.getInstance(context);

    SharedPreferences sharedPrefs = context.getSharedPreferences("com.daiv.android.twitter_world_preferences",
            Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);

    Intent markRead = new Intent(context, MarkReadService.class);
    PendingIntent readPending = PendingIntent.getService(context, 0, markRead, 0);

    String shortText = "Test Test";
    String longText = "Here is a test for Test's notifications";

    Intent resultIntent = new Intent(context, RedirectToMentions.class);

    PendingIntent resultPendingIntent = PendingIntent.getActivity(context, 0, resultIntent, 0);

    NotificationCompat.Builder mBuilder;

    Intent deleteIntent = new Intent(context, NotificationDeleteReceiverOne.class);

    mBuilder = new NotificationCompat.Builder(context).setContentTitle(shortText).setContentText(longText)
            .setSmallIcon(R.drawable.ic_stat_icon)
            .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
            .setContentIntent(resultPendingIntent).setAutoCancel(true).setTicker(shortText)
            .setDeleteIntent(PendingIntent.getBroadcast(context, 0, deleteIntent, 0))
            .setPriority(NotificationCompat.PRIORITY_HIGH);

    // Pebble notification
    if (sharedPrefs.getBoolean("pebble_notification", false)) {
        sendAlertToPebble(context, shortText, shortText);
    }

    // Light Flow notification
    sendToLightFlow(context, shortText, shortText);

    if (settings.vibrate) {
        mBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
    }

    if (settings.sound) {
        try {
            mBuilder.setSound(Uri.parse(settings.ringtone));
        } catch (Exception e) {
            e.printStackTrace();
            mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
        }
    }

    if (settings.led)
        mBuilder.setLights(0xFFFFFF, 1000, 1000);

    // Get an instance of the NotificationManager service
    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);

    Intent reply = null;
    MentionsDataSource data = MentionsDataSource.getInstance(context);
    PendingIntent replyPending = PendingIntent.getActivity(context, 0, reply, 0);

    RemoteInput remoteInput = new RemoteInput.Builder(EXTRA_VOICE_REPLY).setLabel("@" + "daiv" + " ").build();

    // Create the notification action
    NotificationCompat.Action replyAction = new NotificationCompat.Action.Builder(
            R.drawable.ic_action_reply_dark, context.getResources().getString(R.string.noti_reply),
            replyPending).addRemoteInput(remoteInput).build();

    NotificationCompat.Action.Builder action = new NotificationCompat.Action.Builder(
            R.drawable.ic_action_read_dark, context.getResources().getString(R.string.mark_read), readPending);

    mBuilder.addAction(replyAction);
    mBuilder.addAction(action.build());

    // Build the notification and issues it with notification manager.
    notificationManager.notify(1, mBuilder.build());

    // if we want to wake the screen on a new message
    if (settings.wakeScreen) {
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        final PowerManager.WakeLock wakeLock = pm.newWakeLock((PowerManager.SCREEN_BRIGHT_WAKE_LOCK
                | PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP), "TAG");
        wakeLock.acquire(5000);
    }
}

From source file:com.android.messaging.datamodel.BugleNotifications.java

public static void notifyEmergencySmsFailed(final String emergencyNumber, final String conversationId) {
    final Context context = Factory.get().getApplicationContext();

    final CharSequence line1 = MessageNotificationState.applyWarningTextColor(context,
            context.getString(R.string.notification_emergency_send_failure_line1, emergencyNumber));
    final String line2 = context.getString(R.string.notification_emergency_send_failure_line2, emergencyNumber);
    final PendingIntent destinationIntent = UIIntents.get().getPendingIntentForConversationActivity(context,
            conversationId, null /* draft */);

    final NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
    builder.setTicker(line1).setContentTitle(line1).setContentText(line2)
            .setStyle(new NotificationCompat.BigTextStyle(builder).bigText(line2))
            .setSmallIcon(R.drawable.ic_failed_light).setContentIntent(destinationIntent)
            .setSound(UriUtil.getUriForResourceId(context, R.raw.message_failure));

    final String tag = context.getPackageName() + ":emergency_sms_error";
    NotificationManagerCompat.from(context).notify(tag, PendingIntentConstants.MSG_SEND_ERROR, builder.build());
}

From source file:com.klinker.android.twitter.utils.NotificationUtils.java

public static void sendTestNotification(Context context) {

    if (!TEST_NOTIFICATION) {
        return;/*from  ww w . j  a  va  2  s . com*/
    }

    AppSettings settings = AppSettings.getInstance(context);

    SharedPreferences sharedPrefs = context.getSharedPreferences(
            "com.klinker.android.twitter_world_preferences",
            Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);

    Intent markRead = new Intent(context, MarkReadService.class);
    PendingIntent readPending = PendingIntent.getService(context, 0, markRead, 0);

    String shortText = "Test Talon";
    String longText = "Here is a test for Talon's notifications";

    Intent resultIntent = new Intent(context, RedirectToMentions.class);

    PendingIntent resultPendingIntent = PendingIntent.getActivity(context, 0, resultIntent, 0);

    NotificationCompat.Builder mBuilder;

    Intent deleteIntent = new Intent(context, NotificationDeleteReceiverOne.class);

    mBuilder = new NotificationCompat.Builder(context).setContentTitle(shortText).setContentText(longText)
            .setSmallIcon(R.drawable.ic_stat_icon)
            .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
            .setContentIntent(resultPendingIntent).setAutoCancel(true).setTicker(shortText)
            .setDeleteIntent(PendingIntent.getBroadcast(context, 0, deleteIntent, 0))
            .setPriority(NotificationCompat.PRIORITY_HIGH);

    // Pebble notification
    if (sharedPrefs.getBoolean("pebble_notification", false)) {
        sendAlertToPebble(context, shortText, shortText);
    }

    // Light Flow notification
    sendToLightFlow(context, shortText, shortText);

    if (settings.vibrate) {
        mBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
    }

    if (settings.sound) {
        try {
            mBuilder.setSound(Uri.parse(settings.ringtone));
        } catch (Exception e) {
            e.printStackTrace();
            mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
        }
    }

    if (settings.led)
        mBuilder.setLights(0xFFFFFF, 1000, 1000);

    // Get an instance of the NotificationManager service
    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);

    Intent reply = new Intent(context, NotificationCompose.class);
    MentionsDataSource data = MentionsDataSource.getInstance(context);
    PendingIntent replyPending = PendingIntent.getActivity(context, 0, reply, 0);

    RemoteInput remoteInput = new RemoteInput.Builder(EXTRA_VOICE_REPLY).setLabel("@" + "lukeklinker" + " ")
            .build();

    // Create the notification action
    NotificationCompat.Action replyAction = new NotificationCompat.Action.Builder(
            R.drawable.ic_action_reply_dark, context.getResources().getString(R.string.noti_reply),
            replyPending).addRemoteInput(remoteInput).build();

    NotificationCompat.Action.Builder action = new NotificationCompat.Action.Builder(
            R.drawable.ic_action_read_dark, context.getResources().getString(R.string.mark_read), readPending);

    mBuilder.addAction(replyAction);
    mBuilder.addAction(action.build());

    // Build the notification and issues it with notification manager.
    notificationManager.notify(1, mBuilder.build());

    // if we want to wake the screen on a new message
    if (settings.wakeScreen) {
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        final PowerManager.WakeLock wakeLock = pm.newWakeLock((PowerManager.SCREEN_BRIGHT_WAKE_LOCK
                | PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP), "TAG");
        wakeLock.acquire(5000);
    }
}