Example usage for android.app PendingIntent getService

List of usage examples for android.app PendingIntent getService

Introduction

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

Prototype

public static PendingIntent getService(Context context, int requestCode, @NonNull Intent intent,
        @Flags int flags) 

Source Link

Document

Retrieve a PendingIntent that will start a service, like calling Context#startService Context.startService() .

Usage

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

public static void notifySecondDMs(Context context, int secondAccount) {
    DMDataSource data = DMDataSource.getInstance(context);

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

    int numberNew = sharedPrefs.getInt("dm_unread_" + secondAccount, 0);

    int smallIcon = R.drawable.ic_stat_icon;
    Bitmap largeIcon;/*from  w ww. j  a  v a2s .c o m*/

    NotificationCompat.Builder mBuilder;

    String title = context.getResources().getString(R.string.app_name) + " - "
            + context.getResources().getString(R.string.sec_acc);
    String name;
    String message;
    String messageLong;

    NotificationCompat.InboxStyle inbox = null;
    if (numberNew == 1) {
        name = data.getNewestName(secondAccount);

        // if they are muted, and you don't want them to show muted mentions
        // then just quit
        if (sharedPrefs.getString("muted_users", "").contains(name)
                && !sharedPrefs.getBoolean("show_muted_mentions", false)) {
            return;
        }

        message = context.getResources().getString(R.string.mentioned_by) + " @" + name;
        messageLong = "<b>@" + name + "</b>: " + data.getNewestMessage(secondAccount);
        largeIcon = getImage(context, name);
    } else { // more than one dm
        message = numberNew + " " + context.getResources().getString(R.string.new_mentions);
        messageLong = "<b>" + context.getResources().getString(R.string.mentions) + "</b>: " + numberNew + " "
                + context.getResources().getString(R.string.new_mentions);
        largeIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.drawer_user_dark);

        inbox = getDMInboxStyle(numberNew, secondAccount, context, message);
    }

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

    AppSettings settings = AppSettings.getInstance(context);

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

    mBuilder = new NotificationCompat.Builder(context).setContentTitle(title)
            .setContentText(TweetLinkUtils.removeColorHtml(message, settings)).setSmallIcon(smallIcon)
            .setLargeIcon(largeIcon).setDeleteIntent(PendingIntent.getBroadcast(context, 0, deleteIntent, 0))
            .setAutoCancel(true).setPriority(NotificationCompat.PRIORITY_HIGH);

    if (inbox == null) {
        mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(Html.fromHtml(
                settings.addonTheme ? messageLong.replaceAll("FF8800", settings.accentColor) : messageLong)));
    } else {
        mBuilder.setStyle(inbox);
    }

    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(9, 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, messageLong);
        }

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

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

@SuppressLint("NewApi")
private android.app.Notification buildNotification(String ticker, int cid, int bid, long[] eids, String title,
        String text, int count, Intent replyIntent, String network, ArrayList<Notification> messages,
        NotificationCompat.Action otherAction, Bitmap largeIcon, Bitmap wearBackground) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel c = new NotificationChannel(String.valueOf(bid), title,
                NotificationManager.IMPORTANCE_HIGH);
        c.setGroup(String.valueOf(cid));
        ((NotificationManager) IRCCloudApplication.getInstance().getApplicationContext()
                .getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(c);
    }//w  w w  .  j a  v  a  2 s  . c o  m
    SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext());
    int defaults = 0;
    NotificationCompat.Builder builder = new NotificationCompat.Builder(
            IRCCloudApplication.getInstance().getApplicationContext(), String.valueOf(bid))
                    .setContentTitle(
                            title + ((network != null && !network.equals(title)) ? (" (" + network + ")") : ""))
                    .setContentText(Html.fromHtml(text)).setAutoCancel(true).setTicker(ticker)
                    .setWhen(eids[0] / 1000).setSmallIcon(R.drawable.ic_stat_notify).setLargeIcon(largeIcon)
                    .setColor(IRCCloudApplication.getInstance().getApplicationContext().getResources()
                            .getColor(R.color.ic_background))
                    .setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
                    .setCategory(NotificationCompat.CATEGORY_MESSAGE)
                    .setPriority(hasTouchWiz() ? NotificationCompat.PRIORITY_DEFAULT
                            : NotificationCompat.PRIORITY_HIGH)
                    .setOnlyAlertOnce(false);

    if (ticker != null && (System.currentTimeMillis() - prefs.getLong("lastNotificationTime", 0)) > 2000) {
        String ringtone = prefs.getString("notify_ringtone",
                "android.resource://"
                        + IRCCloudApplication.getInstance().getApplicationContext().getPackageName() + "/"
                        + R.raw.digit);
        if (ringtone.length() > 0)
            builder.setSound(Uri.parse(ringtone));
    }

    int led_color = Integer.parseInt(prefs.getString("notify_led_color", "1"));
    if (led_color == 1) {
        defaults = android.app.Notification.DEFAULT_LIGHTS;
    } else if (led_color == 2) {
        builder.setLights(0xFF0000FF, 500, 500);
    }

    if (prefs.getBoolean("notify_vibrate", true) && ticker != null
            && (System.currentTimeMillis() - prefs.getLong("lastNotificationTime", 0)) > 2000)
        defaults |= android.app.Notification.DEFAULT_VIBRATE;
    else
        builder.setVibrate(new long[] { 0L });

    builder.setDefaults(defaults);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putLong("lastNotificationTime", System.currentTimeMillis());
    editor.commit();

    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));
    Intent dismiss = new Intent(IRCCloudApplication.getInstance().getApplicationContext().getResources()
            .getString(R.string.DISMISS_NOTIFICATION));
    dismiss.setData(Uri.parse("irccloud-dismiss://" + bid));
    dismiss.putExtra("bid", bid);
    dismiss.putExtra("eids", eids);

    PendingIntent dismissPendingIntent = PendingIntent.getBroadcast(
            IRCCloudApplication.getInstance().getApplicationContext(), 0, dismiss,
            PendingIntent.FLAG_UPDATE_CURRENT);

    builder.setContentIntent(
            PendingIntent.getActivity(IRCCloudApplication.getInstance().getApplicationContext(), 0, i,
                    PendingIntent.FLAG_UPDATE_CURRENT));
    builder.setDeleteIntent(dismissPendingIntent);

    WearableExtender wearableExtender = new WearableExtender();
    wearableExtender.setBackground(wearBackground);
    if (messages != null && messages.size() > 0) {
        StringBuilder weartext = new StringBuilder();
        String servernick = getServerNick(messages.get(0).cid);
        NotificationCompat.MessagingStyle style = new NotificationCompat.MessagingStyle(servernick);
        style.setConversationTitle(title + ((network != null) ? (" (" + network + ")") : ""));
        for (Notification n : messages) {
            if (n != null && n.message != null && n.message.length() > 0) {
                if (weartext.length() > 0)
                    weartext.append("<br/>");
                if (n.message_type.equals("buffer_me_msg")) {
                    style.addMessage(Html.fromHtml(n.message).toString(), n.eid / 1000,
                            " " + ((n.nick == null) ? servernick : n.nick));
                    weartext.append("<b> ").append((n.nick == null) ? servernick : n.nick).append("</b> ")
                            .append(n.message);
                } else {
                    style.addMessage(Html.fromHtml(n.message).toString(), n.eid / 1000, n.nick);
                    weartext.append("<b>&lt;").append((n.nick == null) ? servernick : n.nick)
                            .append("&gt;</b> ").append(n.message);
                }
            }
        }

        ArrayList<String> history = new ArrayList<>(messages.size());
        for (int j = messages.size() - 1; j >= 0; j--) {
            Notification n = messages.get(j);
            if (n != null) {
                if (n.nick == null)
                    history.add(Html.fromHtml(n.message).toString());
                else
                    break;
            }
        }
        builder.setRemoteInputHistory(history.toArray(new String[history.size()]));
        builder.setStyle(style);

        if (messages.size() > 1) {
            wearableExtender.addPage(
                    new NotificationCompat.Builder(IRCCloudApplication.getInstance().getApplicationContext())
                            .setContentText(Html.fromHtml(weartext.toString()))
                            .extend(new WearableExtender().setStartScrollBottom(true)).build());
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN
                && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            weartext.setLength(0);
            int j = 0;
            for (Notification n : messages) {
                if (messages.size() - ++j < 3) {
                    if (n != null && n.message != null && n.message.length() > 0) {
                        if (weartext.length() > 0)
                            weartext.append("<br/>");
                        if (n.message_type.equals("buffer_me_msg")) {
                            weartext.append("<b> ").append((n.nick == null) ? servernick : n.nick)
                                    .append("</b> ").append(n.message);
                        } else {
                            weartext.append("<b>&lt;").append((n.nick == null) ? servernick : n.nick)
                                    .append("&gt;</b> ").append(n.message);
                        }
                    }
                }
            }

            RemoteViews bigContentView = new RemoteViews(
                    IRCCloudApplication.getInstance().getApplicationContext().getPackageName(),
                    R.layout.notification_expanded);
            bigContentView.setTextViewText(R.id.title,
                    title + (!title.equals(network) ? (" (" + network + ")") : ""));
            bigContentView.setTextViewText(R.id.text, Html.fromHtml(weartext.toString()));
            bigContentView.setImageViewBitmap(R.id.image, largeIcon);
            bigContentView.setLong(R.id.time, "setTime", eids[0] / 1000);
            if (count > 3) {
                bigContentView.setViewVisibility(R.id.more, View.VISIBLE);
                bigContentView.setTextViewText(R.id.more, "+" + (count - 3) + " more");
            } else {
                bigContentView.setViewVisibility(R.id.more, View.GONE);
            }
            if (replyIntent != null && prefs.getBoolean("notify_quickreply", true)) {
                bigContentView.setViewVisibility(R.id.actions, View.VISIBLE);
                bigContentView.setViewVisibility(R.id.action_divider, View.VISIBLE);
                i = new Intent(IRCCloudApplication.getInstance().getApplicationContext(),
                        QuickReplyActivity.class);
                i.setData(Uri.parse("irccloud-bid://" + bid));
                i.putExtras(replyIntent);
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                PendingIntent quickReplyIntent = PendingIntent.getActivity(
                        IRCCloudApplication.getInstance().getApplicationContext(), 0, i,
                        PendingIntent.FLAG_UPDATE_CURRENT);
                bigContentView.setOnClickPendingIntent(R.id.action_reply, quickReplyIntent);
            }
            builder.setCustomBigContentView(bigContentView);
        }
    }

    if (replyIntent != null) {
        PendingIntent replyPendingIntent = PendingIntent.getService(
                IRCCloudApplication.getInstance().getApplicationContext(), bid + 1, replyIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            builder.addAction(new NotificationCompat.Action.Builder(0, "Reply", replyPendingIntent)
                    .setAllowGeneratedReplies(true)
                    .addRemoteInput(
                            new RemoteInput.Builder("extra_reply").setLabel("Reply to " + title).build())
                    .build());
        }

        NotificationCompat.Action.Builder actionBuilder = new NotificationCompat.Action.Builder(
                R.drawable.ic_wearable_reply, "Reply", replyPendingIntent).setAllowGeneratedReplies(true)
                        .addRemoteInput(
                                new RemoteInput.Builder("extra_reply").setLabel("Reply to " + title).build());

        NotificationCompat.Action.WearableExtender actionExtender = new NotificationCompat.Action.WearableExtender()
                .setHintLaunchesActivity(true).setHintDisplayActionInline(true);

        wearableExtender.addAction(actionBuilder.extend(actionExtender).build());

        NotificationCompat.CarExtender.UnreadConversation.Builder unreadConvBuilder = new NotificationCompat.CarExtender.UnreadConversation.Builder(
                title + ((network != null) ? (" (" + network + ")") : ""))
                        .setReadPendingIntent(dismissPendingIntent).setReplyAction(replyPendingIntent,
                                new RemoteInput.Builder("extra_reply").setLabel("Reply to " + title).build());

        if (messages != null) {
            for (Notification n : messages) {
                if (n != null && n.nick != null && n.message != null && n.message.length() > 0) {
                    if (n.buffer_type.equals("conversation")) {
                        if (n.message_type.equals("buffer_me_msg"))
                            unreadConvBuilder
                                    .addMessage(" " + n.nick + " " + Html.fromHtml(n.message).toString());
                        else
                            unreadConvBuilder.addMessage(Html.fromHtml(n.message).toString());
                    } else {
                        if (n.message_type.equals("buffer_me_msg"))
                            unreadConvBuilder
                                    .addMessage(" " + n.nick + " " + Html.fromHtml(n.message).toString());
                        else
                            unreadConvBuilder
                                    .addMessage(n.nick + " said: " + Html.fromHtml(n.message).toString());
                    }
                }
            }
        } else {
            unreadConvBuilder.addMessage(text);
        }
        unreadConvBuilder.setLatestTimestamp(eids[count - 1] / 1000);

        builder.extend(new NotificationCompat.CarExtender().setUnreadConversation(unreadConvBuilder.build()));
    }

    if (replyIntent != null && prefs.getBoolean("notify_quickreply", true)
            && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
        i = new Intent(IRCCloudApplication.getInstance().getApplicationContext(), QuickReplyActivity.class);
        i.setData(Uri.parse("irccloud-bid://" + bid));
        i.putExtras(replyIntent);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent quickReplyIntent = PendingIntent.getActivity(
                IRCCloudApplication.getInstance().getApplicationContext(), 0, i,
                PendingIntent.FLAG_UPDATE_CURRENT);
        builder.addAction(R.drawable.ic_action_reply, "Quick Reply", quickReplyIntent);
    }

    if (otherAction != null) {
        int drawable = 0;
        if (otherAction.getIcon() == R.drawable.ic_wearable_add)
            drawable = R.drawable.ic_action_add;
        else if (otherAction.getIcon() == R.drawable.ic_wearable_reply)
            drawable = R.drawable.ic_action_reply;
        builder.addAction(
                new NotificationCompat.Action(drawable, otherAction.getTitle(), otherAction.getActionIntent()));
        wearableExtender.addAction(otherAction);
    }

    builder.extend(wearableExtender);

    return builder.build();
}

From source file:com.tct.mail.utils.NotificationUtils.java

/**
 * Validate the notifications notification.
 */// w  ww.j  av a2  s .  c o  m
private static void validateNotifications(Context context, final Folder folder, final Account account,
        boolean getAttention, boolean ignoreUnobtrusiveSetting, NotificationKey key,
        final ContactPhotoFetcher photoFetcher) {

    NotificationManagerCompat nm = NotificationManagerCompat.from(context);

    final NotificationMap notificationMap = getNotificationMap(context);
    if (LogUtils.isLoggable(LOG_TAG, LogUtils.VERBOSE)) {
        LogUtils.i(LOG_TAG,
                "Validating Notification: %s mapSize: %d "
                        + "folder: %s getAttention: %b ignoreUnobtrusive: %b",
                createNotificationString(notificationMap), notificationMap.size(), folder.name, getAttention,
                ignoreUnobtrusiveSetting);
    } else {
        LogUtils.i(LOG_TAG, "Validating Notification, mapSize: %d " + "getAttention: %b ignoreUnobtrusive: %b",
                notificationMap.size(), getAttention, ignoreUnobtrusiveSetting);
    }
    // The number of unread messages for this account and label.
    final Integer unread = notificationMap.getUnread(key);
    final int unreadCount = unread != null ? unread.intValue() : 0;
    final Integer unseen = notificationMap.getUnseen(key);
    int unseenCount = unseen != null ? unseen.intValue() : 0;

    Cursor cursor = null;

    try {
        final Uri.Builder uriBuilder = folder.conversationListUri.buildUpon();
        uriBuilder.appendQueryParameter(UIProvider.SEEN_QUERY_PARAMETER, Boolean.FALSE.toString());
        // Do not allow this quick check to disrupt any active network-enabled conversation
        // cursor.
        uriBuilder.appendQueryParameter(UIProvider.ConversationListQueryParameters.USE_NETWORK,
                Boolean.FALSE.toString());
        cursor = context.getContentResolver().query(uriBuilder.build(), UIProvider.CONVERSATION_PROJECTION,
                null, null, null);
        if (cursor == null) {
            // This folder doesn't exist.
            LogUtils.i(LOG_TAG, "The cursor is null, so the specified folder probably does not exist");
            clearFolderNotification(context, account, folder, false);
            return;
        }
        final int cursorUnseenCount = cursor.getCount();

        // Make sure the unseen count matches the number of items in the cursor.  But, we don't
        // want to overwrite a 0 unseen count that was specified in the intent
        if (unseenCount != 0 && unseenCount != cursorUnseenCount) {
            LogUtils.i(LOG_TAG, "Unseen count doesn't match cursor count.  unseen: %d cursor count: %d",
                    unseenCount, cursorUnseenCount);
            unseenCount = cursorUnseenCount;
        }

        // For the purpose of the notifications, the unseen count should be capped at the num of
        // unread conversations.
        if (unseenCount > unreadCount) {
            unseenCount = unreadCount;
        }

        final int notificationId = getNotificationId(account.getAccountManagerAccount(), folder);

        NotificationKey notificationKey = new NotificationKey(account, folder);

        if (unseenCount == 0) {
            LogUtils.i(LOG_TAG, "validateNotifications - cancelling account %s / folder %s",
                    LogUtils.sanitizeName(LOG_TAG, account.getEmailAddress()),
                    LogUtils.sanitizeName(LOG_TAG, folder.persistentId));
            //TS: Gantao 2015-08-25 EMAIL BUGFIX_1073998 MOD_S
            //May happen SecurityException while cancle notification,only catch it.
            try {
                nm.cancel(notificationId);
            } catch (SecurityException se) {
                LogUtils.e(LOG_TAG, "Can not find the pacakage while cancle the notification: %d",
                        notificationId);
            }
            //TS: Gantao 2015-08-25 EMAIL BUGFIX_1073998 MOD_E
            cancelConversationNotifications(notificationKey, nm);

            return;
        }

        // We now have all we need to create the notification and the pending intent
        PendingIntent clickIntent = null;

        NotificationCompat.Builder notification = new NotificationCompat.Builder(context);
        NotificationCompat.WearableExtender wearableExtender = new NotificationCompat.WearableExtender();
        Map<Integer, NotificationBuilders> msgNotifications = new ArrayMap<Integer, NotificationBuilders>();

        if (com.tct.mail.utils.Utils.isRunningLOrLater()) {
            notification.setColor(context.getResources().getColor(R.color.notification_icon_mail_orange));
        }
        // TODO(shahrk) - fix for multiple mail
        // if(folder.notificationIconResId != 0 || unseenCount <=  2)
        notification.setSmallIcon(R.drawable.ic_notification_mail_24dp);
        notification.setTicker(account.getDisplayName());
        notification.setVisibility(NotificationCompat.VISIBILITY_PRIVATE);

        final long when;

        final long oldWhen = NotificationActionUtils.sNotificationTimestamps.get(notificationId);
        if (oldWhen != 0) {
            when = oldWhen;
        } else {
            when = System.currentTimeMillis();
        }

        notification.setWhen(when);

        // The timestamp is now stored in the notification, so we can remove it from here
        NotificationActionUtils.sNotificationTimestamps.delete(notificationId);

        // Dispatch a CLEAR_NEW_MAIL_NOTIFICATIONS intent if the user taps the "X" next to a
        // notification.  Also this intent gets fired when the user taps on a notification as
        // the AutoCancel flag has been set
        final Intent cancelNotificationIntent = new Intent(
                MailIntentService.ACTION_CLEAR_NEW_MAIL_NOTIFICATIONS);
        cancelNotificationIntent.setPackage(context.getPackageName());
        cancelNotificationIntent.setData(Utils.appendVersionQueryParameter(context, folder.folderUri.fullUri));
        cancelNotificationIntent.putExtra(Utils.EXTRA_ACCOUNT, account);
        cancelNotificationIntent.putExtra(Utils.EXTRA_FOLDER, folder);

        notification.setDeleteIntent(
                PendingIntent.getService(context, notificationId, cancelNotificationIntent, 0));

        // Ensure that the notification is cleared when the user selects it
        notification.setAutoCancel(true);

        boolean eventInfoConfigured = false;

        final boolean isInbox = folder.folderUri.equals(account.settings.defaultInbox);
        final FolderPreferences folderPreferences = new FolderPreferences(context, account.getAccountId(),
                folder, isInbox);

        if (isInbox) {
            final AccountPreferences accountPreferences = new AccountPreferences(context,
                    account.getAccountId());
            moveNotificationSetting(accountPreferences, folderPreferences);
        }

        if (!folderPreferences.areNotificationsEnabled()) {
            LogUtils.i(LOG_TAG, "Notifications are disabled for this folder; not notifying");
            // Don't notify
            return;
        }

        if (unreadCount > 0) {
            // How can I order this properly?
            if (cursor.moveToNext()) {
                final Intent notificationIntent;

                // Launch directly to the conversation, if there is only 1 unseen conversation
                final boolean launchConversationMode = (unseenCount == 1);
                if (launchConversationMode) {
                    notificationIntent = createViewConversationIntent(context, account, folder, cursor);
                } else {
                    notificationIntent = createViewConversationIntent(context, account, folder, null);
                }

                Analytics.getInstance().sendEvent("notification_create",
                        launchConversationMode ? "conversation" : "conversation_list",
                        folder.getTypeDescription(), unseenCount);

                if (notificationIntent == null) {
                    LogUtils.e(LOG_TAG, "Null intent when building notification");
                    return;
                }

                clickIntent = createClickPendingIntent(context, notificationIntent);

                configureLatestEventInfoFromConversation(context, account, folderPreferences, notification,
                        wearableExtender, msgNotifications, notificationId, cursor, clickIntent,
                        notificationIntent, unreadCount, unseenCount, folder, when, photoFetcher);
                eventInfoConfigured = true;
            }
        }

        final boolean vibrate = folderPreferences.isNotificationVibrateEnabled();
        final String ringtoneUri = folderPreferences.getNotificationRingtoneUri();
        //TS: junwei-xu 2015-2-12 EMAIL BUGFIX_884937 MOD_S
        //final boolean notifyOnce = !folderPreferences.isEveryMessageNotificationEnabled();

        //if (!ignoreUnobtrusiveSetting && notifyOnce) {
        //    // If the user has "unobtrusive notifications" enabled, only alert the first time
        //    // new mail is received in this account.  This is the default behavior.  See
        //    // bugs 2412348 and 2413490.
        //    LogUtils.d(LOG_TAG, "Setting Alert Once");
        //    notification.setOnlyAlertOnce(true);
        //}
        //TS: junwei-xu 2015-2-12 EMAIL BUGFIX_884937 MOD_E

        LogUtils.i(LOG_TAG, "Account: %s vibrate: %s",
                LogUtils.sanitizeName(LOG_TAG, account.getEmailAddress()),
                Boolean.toString(folderPreferences.isNotificationVibrateEnabled()));

        int defaults = 0;

        // Check if any current conversation notifications exist previously.  Only notify if
        // one of them is new.
        boolean hasNewConversationNotification;
        Set<Integer> prevConversationNotifications = sConversationNotificationMap.get(notificationKey);
        if (prevConversationNotifications != null) {
            hasNewConversationNotification = false;
            for (Integer currentNotificationId : msgNotifications.keySet()) {
                if (!prevConversationNotifications.contains(currentNotificationId)) {
                    hasNewConversationNotification = true;
                    break;
                }
            }
        } else {
            hasNewConversationNotification = true;
        }

        //TS:zheng.zou 2015-12-17 EMAIL BUGFIX_861247  ADD_S
        final int lastUnreadCount = sLastNotificationUnreadCount.get(notificationId);
        final int lastUnseenCount = sLastNotificationUnseenCount.get(notificationId);
        final long lastWhen = sLastNotificationTimestamps.get(notificationId);
        boolean suppressSound = when - lastWhen < sMinDisturbTimeGap;
        if (lastUnreadCount == unreadCount && lastUnseenCount == unseenCount && suppressSound) {
            LogUtils.i(LOG_TAG, "same with unseen count and unread count, return");
            return;
        }
        LogUtils.i(LOG_TAG, "suppressSound = " + suppressSound);
        //TS:zheng.zou 2015-12-17 EMAIL BUGFIX_861247  ADD_E
        LogUtils.d(LOG_TAG, "getAttention=%s,oldWhen=%s,hasNewConversationNotification=%s", getAttention,
                oldWhen, hasNewConversationNotification);

        /*
         * We do not want to notify if this is coming back from an Undo notification, hence the
         * oldWhen check.
         */
        if (getAttention && oldWhen == 0 && hasNewConversationNotification && !suppressSound) { //TS:zheng.zou 2015-12-17 EMAIL BUGFIX_861247  MOD
            final AccountPreferences accountPreferences = new AccountPreferences(context,
                    account.getAccountId());
            if (accountPreferences.areNotificationsEnabled()) {
                if (vibrate) {
                    defaults |= Notification.DEFAULT_VIBRATE;
                }

                notification.setSound(TextUtils.isEmpty(ringtoneUri) ? null : Uri.parse(ringtoneUri));
                LogUtils.i(LOG_TAG, "New email in %s vibrateWhen: %s, playing notification: %s",
                        LogUtils.sanitizeName(LOG_TAG, account.getEmailAddress()), vibrate, ringtoneUri);
                sLastNotificationTimestamps.put(notificationId, when); //TS:zheng.zou 2015-12-17 EMAIL BUGFIX_861247  ADD
            }
        }

        // TODO(skennedy) Why do we do any of the above if we're just going to bail here?
        if (eventInfoConfigured) {
            // TS: zheng.zou 2015-09-10 EMAIL BUGFIX-557052 MOD_S
            // TS: Gantao 2015-09-10 EMAIL BUGFIX-625126 MOD_S
            defaults |= Notification.DEFAULT_LIGHTS;
            //                defaults |= Notification.FLAG_SHOW_LIGHTS;
            // TS: Gantao 2015-09-10 EMAIL BUGFIX-625126 MOD_E
            notification.setDefaults(defaults);
            notification.setLights(0xff00ff00, 280, 2080);
            // TS: zheng.zou 2015-09-10 EMAIL BUGFIX-557052 MOD_E

            if (oldWhen != 0) {
                // We do not want to display the ticker again if we are re-displaying this
                // notification (like from an Undo notification)
                notification.setTicker(null);
            }

            notification.extend(wearableExtender);

            // create the *public* form of the *private* notification we have been assembling
            // TS: xiaolin.li 2014-01-23 EMAIL BUGFIX-900921 ADD_S
            /*final Notification publicNotification = createPublicNotification(context, account,
                folder, when, unseenCount, unreadCount, clickIntent);
            notification.setPublicVersion(publicNotification);*/
            try {
                final Notification publicNotification = createPublicNotification(context, account, folder, when,
                        unseenCount, unreadCount, clickIntent);
                notification.setPublicVersion(publicNotification);
            } catch (Exception e) {
                LogUtils.i(LOG_TAG, "createPublicNotification Exception.");
            }
            // TS: xiaolin.li 2014-01-23 EMAIL BUGFIX-900921 ADD_E
            LogUtils.i(LOG_TAG, " --- notify notification notificationId = " + notificationId); //TS: zheng.zolu 2015-11-09 EMAIL LOG-839780 ADD
            nm.notify(notificationId, notification.build());

            //[BUGFIX]-Add-BEGINbySCDTABLET.yafang.wei,09/06/2016,2848903,
            // SetscreenonwhencomesnewEmail
            Boolean def_is_wakeup_when_receive_email = context.getResources()
                    .getBoolean(R.bool.def_is_wakeup_when_receive_email);
            if (def_is_wakeup_when_receive_email) {
                PowerManager powerManager = (PowerManager) (context.getSystemService(Context.POWER_SERVICE));
                PowerManager.WakeLock wakeLock = null;
                wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK
                        | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE,
                        "Email_wake_lock");
                long wakeUpTime = 0;
                try {
                    ContentResolver cr = context.getContentResolver();
                    wakeUpTime = android.provider.Settings.System.getInt(cr,
                            Settings.System.SCREEN_OFF_TIMEOUT);
                } catch (Settings.SettingNotFoundException e) {
                }
                wakeLock.acquire(wakeUpTime);
            }
            //[BUGFIX]-Add-ENDbySCDTABLET.yafang.wei

            //TS:zheng.zou 2015-12-17 EMAIL BUGFIX_861247  ADD_S
            sLastNotificationUnreadCount.put(notificationId, unreadCount);
            sLastNotificationUnseenCount.put(notificationId, unseenCount);
            //TS:zheng.zou 2015-12-17 EMAIL BUGFIX_861247  ADD_E

            if (prevConversationNotifications != null) {
                Set<Integer> currentNotificationIds = msgNotifications.keySet();
                for (Integer prevConversationNotificationId : prevConversationNotifications) {
                    if (!currentNotificationIds.contains(prevConversationNotificationId)) {
                        nm.cancel(prevConversationNotificationId);
                        LogUtils.d(LOG_TAG, "canceling conversation notification %s",
                                prevConversationNotificationId);
                    }
                }
            }

            // TS: junwei-xu 2015-03-24 EMAIL BUGFIX-957471, ADD_S
            try {
                for (Map.Entry<Integer, NotificationBuilders> entry : msgNotifications.entrySet()) {
                    NotificationBuilders builders = entry.getValue();
                    builders.notifBuilder.extend(builders.wearableNotifBuilder);
                    nm.notify(entry.getKey(), builders.notifBuilder.build());
                    LogUtils.i(LOG_TAG, "notifying conversation notification %s", entry.getKey());// TS: zheng.zolu 2015-11-09 EMAIL LOG-839780 MOD
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            // TS: junwei-xu 2015-03-24 EMAIL BUGFIX-957471, ADD_E

            Set<Integer> conversationNotificationIds = new HashSet<Integer>();
            conversationNotificationIds.addAll(msgNotifications.keySet());
            sConversationNotificationMap.put(notificationKey, conversationNotificationIds);
        } else {
            LogUtils.i(LOG_TAG, "event info not configured - not notifying");
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

From source file:com.b44t.messenger.NotificationsController.java

private void scheduleNotificationRepeat() {
    try {//from w w  w  .  j av  a 2 s.c o  m
        PendingIntent pintent = PendingIntent.getService(ApplicationLoader.applicationContext, 0,
                new Intent(ApplicationLoader.applicationContext, NotificationRepeat.class), 0);
        SharedPreferences preferences = ApplicationLoader.applicationContext
                .getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
        int minutes = preferences.getInt("repeat_messages", 0);
        if (minutes > 0 && personal_count > 0) {
            alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                    SystemClock.elapsedRealtime() + minutes * 60 * 1000, pintent);
        } else {
            alarmManager.cancel(pintent);
        }
    } catch (Exception e) {
        FileLog.e("messenger", e);
    }
}

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

public static void notifySecondDMs(Context context, int secondAccount) {
    DMDataSource data = DMDataSource.getInstance(context);

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

    int numberNew = sharedPrefs.getInt("dm_unread_" + secondAccount, 0);

    int smallIcon = R.drawable.ic_stat_icon;
    Bitmap largeIcon;//  w ww  . j a  v a2 s .  c o  m

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

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

    NotificationCompat.Builder mBuilder;

    String title = context.getResources().getString(R.string.app_name) + " - "
            + context.getResources().getString(R.string.sec_acc);
    String name;
    String message;
    String messageLong;

    NotificationCompat.InboxStyle inbox = null;
    if (numberNew == 1) {
        name = data.getNewestName(secondAccount);

        // if they are muted, and you don't want them to show muted mentions
        // then just quit
        if (sharedPrefs.getString("muted_users", "").contains(name)
                && !sharedPrefs.getBoolean("show_muted_mentions", false)) {
            return;
        }

        message = context.getResources().getString(R.string.mentioned_by) + " @" + name;
        messageLong = "<b>@" + name + "</b>: " + data.getNewestMessage(secondAccount);
        largeIcon = getImage(context, name);
    } else { // more than one dm
        message = numberNew + " " + context.getResources().getString(R.string.new_mentions);
        messageLong = "<b>" + context.getResources().getString(R.string.mentions) + "</b>: " + numberNew + " "
                + context.getResources().getString(R.string.new_mentions);
        largeIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.drawer_user_dark);

        inbox = getDMInboxStyle(numberNew, secondAccount, context, message);
    }

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

    AppSettings settings = AppSettings.getInstance(context);

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

    mBuilder = new NotificationCompat.Builder(context).setContentTitle(title)
            .setContentText(TweetLinkUtils.removeColorHtml(message, settings)).setSmallIcon(smallIcon)
            .setLargeIcon(largeIcon).setContentIntent(resultPendingIntent)
            .setDeleteIntent(PendingIntent.getBroadcast(context, 0, deleteIntent, 0)).setAutoCancel(true)
            .setPriority(NotificationCompat.PRIORITY_HIGH);

    if (inbox == null) {
        mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(Html.fromHtml(
                settings.addonTheme ? messageLong.replaceAll("FF8800", settings.accentColor) : messageLong)));
    } else {
        mBuilder.setStyle(inbox);
    }

    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(9, 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, messageLong);
        }

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

From source file:github.daneren2005.dsub.util.Util.java

private static void setupViews(RemoteViews rv, Context context, MusicDirectory.Entry song, boolean playing) {

    // Use the same text for the ticker and the expanded notification
    String title = song.getTitle();
    String arist = song.getArtist();
    String album = song.getAlbum();

    // Set the album art.
    try {/*w  w  w .  j  av  a2  s  . com*/
        int size = context.getResources().getDrawable(R.drawable.unknown_album).getIntrinsicHeight();
        Bitmap bitmap = FileUtil.getAlbumArtBitmap(context, song, size);
        if (bitmap == null) {
            // set default album art
            rv.setImageViewResource(R.id.notification_image, R.drawable.unknown_album);
        } else {
            rv.setImageViewBitmap(R.id.notification_image, bitmap);
        }
    } catch (Exception x) {
        Log.w(TAG, "Failed to get notification cover art", x);
        rv.setImageViewResource(R.id.notification_image, R.drawable.unknown_album);
    }

    // set the text for the notifications
    rv.setTextViewText(R.id.notification_title, title);
    rv.setTextViewText(R.id.notification_artist, arist);
    rv.setTextViewText(R.id.notification_album, album);

    Pair<Integer, Integer> colors = getNotificationTextColors(context);
    if (colors.getFirst() != null) {
        rv.setTextColor(R.id.notification_title, colors.getFirst());
    }
    if (colors.getSecond() != null) {
        rv.setTextColor(R.id.notification_artist, colors.getSecond());
    }

    if (!playing) {
        rv.setImageViewResource(R.id.control_pause, R.drawable.notification_play);
        rv.setImageViewResource(R.id.control_previous, R.drawable.notification_stop);
    }

    // Create actions for media buttons
    PendingIntent pendingIntent;
    if (playing) {
        Intent prevIntent = new Intent("KEYCODE_MEDIA_PREVIOUS");
        prevIntent.setComponent(new ComponentName(context, DownloadServiceImpl.class));
        prevIntent.putExtra(Intent.EXTRA_KEY_EVENT,
                new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MEDIA_PREVIOUS));
        pendingIntent = PendingIntent.getService(context, 0, prevIntent, 0);
        rv.setOnClickPendingIntent(R.id.control_previous, pendingIntent);
    } else {
        Intent prevIntent = new Intent("KEYCODE_MEDIA_STOP");
        prevIntent.setComponent(new ComponentName(context, DownloadServiceImpl.class));
        prevIntent.putExtra(Intent.EXTRA_KEY_EVENT,
                new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MEDIA_STOP));
        pendingIntent = PendingIntent.getService(context, 0, prevIntent, 0);
        rv.setOnClickPendingIntent(R.id.control_previous, pendingIntent);
    }

    Intent pauseIntent = new Intent("KEYCODE_MEDIA_PLAY_PAUSE");
    pauseIntent.setComponent(new ComponentName(context, DownloadServiceImpl.class));
    pauseIntent.putExtra(Intent.EXTRA_KEY_EVENT,
            new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE));
    pendingIntent = PendingIntent.getService(context, 0, pauseIntent, 0);
    rv.setOnClickPendingIntent(R.id.control_pause, pendingIntent);

    Intent nextIntent = new Intent("KEYCODE_MEDIA_NEXT");
    nextIntent.setComponent(new ComponentName(context, DownloadServiceImpl.class));
    nextIntent.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MEDIA_NEXT));
    pendingIntent = PendingIntent.getService(context, 0, nextIntent, 0);
    rv.setOnClickPendingIntent(R.id.control_next, pendingIntent);
}

From source file:com.crearo.gpslogger.GpsLoggingService.java

private void stopAlarm() {
    Intent i = new Intent(this, GpsLoggingService.class);
    i.putExtra(IntentConstants.GET_NEXT_POINT, true);
    PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
    nextPointAlarmManager.cancel(pi);/*from   w w  w  . jav a  2 s .c  o m*/
}

From source file:com.crearo.gpslogger.GpsLoggingService.java

@TargetApi(23)
private void setAlarmForNextPoint() {
    LOG.debug("Set alarm for " + preferenceHelper.getMinimumLoggingInterval() + " seconds");

    Intent i = new Intent(this, GpsLoggingService.class);
    i.putExtra(IntentConstants.GET_NEXT_POINT, true);
    PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
    nextPointAlarmManager.cancel(pi);/*from   www . j a  va2  s . c  o  m*/

    if (Systems.isDozing(this)) {
        //Only invoked once per 15 minutes in doze mode
        LOG.debug("Device is dozing, using infrequent alarm");
        nextPointAlarmManager.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                SystemClock.elapsedRealtime() + preferenceHelper.getMinimumLoggingInterval() * 1000, pi);
    } else {
        nextPointAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                SystemClock.elapsedRealtime() + preferenceHelper.getMinimumLoggingInterval() * 1000, pi);
    }
}

From source file:com.tct.email.NotificationController.java

/**
 * Show (or update) a exchange sync new calendar notification. If tapped, the user is taken to the Exchange permission view
 * where he can view the exchange permission. if tap never ask again,notification will not show.
 *///from  w  ww  .ja v a  2  s . co m
public void showCalendarNotification(String packageName) {
    NotificationCompat.Builder notification = new NotificationCompat.Builder(mContext);
    //get the warning icon
    Bitmap icon = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.ic_warning_grey);
    //The Martro style only supported after android L.
    if (com.tct.mail.utils.Utils.isRunningLOrLater()) {
        notification.setColor(mContext.getResources().getColor(R.color.notification_icon_mail_orange));
    }
    notification.setContentTitle(mContext.getResources().getString(R.string.sync_calendar_title));
    notification.setContentText(mContext.getResources().getString(R.string.sync_calendar_content));
    notification.setLargeIcon(icon);
    notification.setSmallIcon(R.drawable.ic_notification_mail_24dp);
    notification.setAutoCancel(true);//TS: zheng.zou 2016-3-19 EMAIL BUGFIX-1841389 ADD_S
    //set the content click/tap intent
    //it will trigger going to app permissions settings
    Intent gotoSettingsIntent = gotoSettingsIntent(mContext, packageName);
    PendingIntent contentIntent = PendingIntent.getActivity(mContext, 0, gotoSettingsIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    notification.setContentIntent(contentIntent);

    //set the action click intent.
    //it will never receive notification.
    //never ask again
    Intent clickIntent = new Intent(NotificationActionIntentService.ACTION_CALENDAR_NEVER_ASK_AGAIN);
    clickIntent.setPackage(mContext.getPackageName());
    PendingIntent pendButtonIntent = PendingIntent.getService(mContext, 0, clickIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    notification.addAction(R.drawable.notification_button,
            mContext.getResources().getString(R.string.notification_never_ask_again).toUpperCase(),
            pendButtonIntent);

    Notification warningNotification = notification.build();
    //        warningNotification.flags |= Notification.FLAG_AUTO_CANCEL;
    //        warningNotification.flags |= Notification.DEFAULT_VIBRATE;
    NotificationManager nm = (NotificationManager) mContext.getSystemService(mContext.NOTIFICATION_SERVICE);
    nm.notify(EXCHANGE_NEWCALENDAR_NOTIFICATION_ID, warningNotification);
}

From source file:com.mendhak.gpslogger.GpsLoggingService.java

@TargetApi(23)
private void setAlarmForNextPoint() {
    LOG.debug("Set alarm for " + preferenceHelper.getMinimumLoggingInterval() + " seconds");

    Intent i = new Intent(this, GpsLoggingService.class);
    i.putExtra(IntentConstants.GET_NEXT_POINT, true);
    PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
    nextPointAlarmManager.cancel(pi);/*www  .  jav  a  2  s .  c  o  m*/

    if (Systems.isDozing(this)) {
        //Only invoked once per 15 minutes in doze mode
        LOG.warn("Device is dozing, using infrequent alarm");
        nextPointAlarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                SystemClock.elapsedRealtime() + preferenceHelper.getMinimumLoggingInterval() * 1000, pi);
    } else {
        nextPointAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                SystemClock.elapsedRealtime() + preferenceHelper.getMinimumLoggingInterval() * 1000, pi);
    }
}