Example usage for android.app Notification DEFAULT_LIGHTS

List of usage examples for android.app Notification DEFAULT_LIGHTS

Introduction

In this page you can find the example usage for android.app Notification DEFAULT_LIGHTS.

Prototype

int DEFAULT_LIGHTS

To view the source code for android.app Notification DEFAULT_LIGHTS.

Click Source Link

Document

Use the default notification lights.

Usage

From source file:com.android.calendar.alerts.AlertService.java

private static void addNotificationOptions(NotificationWrapper nw, boolean quietUpdate, String tickerText,
        boolean defaultVibrate, String reminderRingtone, boolean showLights) {
    Notification notification = nw.mNotification;

    if (showLights) {
        notification.flags |= Notification.FLAG_SHOW_LIGHTS;
        notification.defaults |= Notification.DEFAULT_LIGHTS;
    }//from ww w.  j  a va  2s.co  m

    // Quietly update notification bar. Nothing new. Maybe something just got deleted.
    if (!quietUpdate) {
        // Flash ticker in status bar
        if (!TextUtils.isEmpty(tickerText)) {
            notification.tickerText = tickerText;
        }

        // Generate either a pop-up dialog, status bar notification, or
        // neither. Pop-up dialog and status bar notification may include a
        // sound, an alert, or both. A status bar notification also includes
        // a toast.
        if (defaultVibrate) {
            notification.defaults |= Notification.DEFAULT_VIBRATE;
        }

        // Possibly generate a sound. If 'Silent' is chosen, the ringtone
        // string will be empty.
        notification.sound = TextUtils.isEmpty(reminderRingtone) ? null : Uri.parse(reminderRingtone);
    }
}

From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java

private void SendNotification(String tickerText, String expandedText) {
    NotificationManager notificationManager = (NotificationManager) contextWrapper
            .getSystemService(Context.NOTIFICATION_SERVICE);
    int icon = R.drawable.ateamlogo;
    long when = System.currentTimeMillis();

    Notification notification = new Notification(icon, tickerText, when);

    notification.flags |= (Notification.FLAG_INSISTENT | Notification.FLAG_AUTO_CANCEL);
    notification.defaults |= Notification.DEFAULT_SOUND;
    notification.defaults |= Notification.DEFAULT_VIBRATE;
    notification.defaults |= Notification.DEFAULT_LIGHTS;

    Context context = contextWrapper.getApplicationContext();

    // Intent to launch an activity when the extended text is clicked
    Intent intent2 = new Intent(contextWrapper, SUTAgentAndroid.class);
    PendingIntent launchIntent = PendingIntent.getActivity(context, 0, intent2, 0);

    notification.setLatestEventInfo(context, tickerText, expandedText, launchIntent);

    notificationManager.notify(1959, notification);
}

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

/**
 * Validate the notifications notification.
 *///  w  w w  .j a  v a 2 s  .co 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.concentriclivers.mms.com.android.mms.transaction.MessagingNotification.java

/**
 * updateNotification is *the* main function for building the actual notification handed to
 * the NotificationManager//from www  .  ja  v  a  2  s  . com
 * @param context
 * @param isNew if we've got a new message, show the ticker
 * @param uniqueThreadCount
 */
private static void updateNotification(Context context, boolean isNew, int uniqueThreadCount) {
    // TDH
    Log.d("NotificationDebug", "updateNotification()");

    // If the user has turned off notifications in settings, don't do any notifying.
    if (!MessagingPreferenceActivity.getNotificationEnabled(context)) {
        if (DEBUG) {
            Log.d(TAG, "updateNotification: notifications turned off in prefs, bailing");
        }
        // TDH
        Log.d("NotificationDebug", "Notifications not enabled!");

        return;
    }

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

    // TDH:
    Log.d("NotificationDebug", "messageCount: " + messageCount);
    if (messageCount == 0) {
        Log.d("NotificationDebug", "WTF. Should have at least one message.");
        return;
    }

    NotificationInfo mostRecentNotification = sNotificationSet.first();

    // TDH: Use NotificationCompat2 (and in other places but it is obvious where).
    final NotificationCompat2.Builder noti = new NotificationCompat2.Builder(context)
            .setWhen(mostRecentNotification.mTimeMillis);

    if (isNew) {
        noti.setTicker(mostRecentNotification.mTicker);
    }
    // TDH
    Log.d("NotificationDebug", "Creating TaskStackBuilder");

    TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context);
    // TDH
    Log.d("NotificationDebug", "Created TaskStackBuilder. UniqueThreadCount: " + uniqueThreadCount);

    // 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;
    if (uniqueThreadCount > 1) { // messages from multiple threads
        Intent mainActivityIntent = new Intent(Intent.ACTION_MAIN);

        mainActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP
                | Intent.FLAG_ACTIVITY_CLEAR_TOP);

        mainActivityIntent.setType("vnd.android-dir/mms-sms");
        taskStackBuilder.addNextIntent(mainActivityIntent);
        title = context.getString(R.string.message_count_notification, messageCount);
    } else { // same thread, single or multiple messages
        title = mostRecentNotification.mTitle;
        BitmapDrawable contactDrawable = (BitmapDrawable) mostRecentNotification.mSender.getAvatar(context,
                null);
        if (contactDrawable != 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.
            avatar = contactDrawable.getBitmap();
            if (avatar != null) {
                final int idealIconHeight = res
                        .getDimensionPixelSize(android.R.dimen.notification_large_icon_height);
                final int idealIconWidth = res
                        .getDimensionPixelSize(android.R.dimen.notification_large_icon_width);
                if (avatar.getHeight() < idealIconHeight) {
                    // Scale this image to fit the intended size
                    avatar = Bitmap.createScaledBitmap(avatar, idealIconWidth, idealIconHeight, true);
                }
                if (avatar != null) {
                    noti.setLargeIcon(avatar);
                }
            }
        }

        taskStackBuilder.addParentStack(ComposeMessageActivity.class);
        taskStackBuilder.addNextIntent(mostRecentNotification.mClickIntent);
    }

    // TDH
    Log.d("NotificationDebug", "title: " + title);

    // Always have to set the small icon or the notification is ignored
    noti.setSmallIcon(R.drawable.stat_notify_sms);

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

    // Update the notification.
    noti.setContentTitle(title)
            .setContentIntent(taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT));
    // TDH: Can't do these yet.
    //            .addKind(Notification.KIND_MESSAGE)
    //            .setPriority(Notification.PRIORITY_DEFAULT);     // TODO: set based on contact coming
    //                                                             // from a favorite.

    int defaults = 0;

    if (isNew) {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
        String vibrateWhen;
        if (sp.contains(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_WHEN)) {
            vibrateWhen = sp.getString(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_WHEN, null);
        } else if (sp.contains(MessagingPreferenceActivity.NOTIFICATION_VIBRATE)) {
            vibrateWhen = sp.getBoolean(MessagingPreferenceActivity.NOTIFICATION_VIBRATE, false)
                    ? context.getString(R.string.prefDefault_vibrate_true)
                    : context.getString(R.string.prefDefault_vibrate_false);
        } else {
            vibrateWhen = context.getString(R.string.prefDefault_vibrateWhen);
        }

        boolean vibrateAlways = vibrateWhen.equals("always");
        boolean vibrateSilent = vibrateWhen.equals("silent");
        AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        boolean nowSilent = audioManager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE;

        if (vibrateAlways || vibrateSilent && nowSilent) {
            defaults |= Notification.DEFAULT_VIBRATE;
        }

        String ringtoneStr = sp.getString(MessagingPreferenceActivity.NOTIFICATION_RINGTONE, null);
        noti.setSound(TextUtils.isEmpty(ringtoneStr) ? null : Uri.parse(ringtoneStr));
        if (DEBUG) {
            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));

    final Notification notification;

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

        // TDH
        Log.d("NotificationDebug",
                "Single message, with text: " + mostRecentNotification.formatBigMessage(context));

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

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

            notification = new NotificationCompat2.BigPictureStyle(noti)
                    .bigPicture(mostRecentNotification.mAttachmentBitmap)
                    // This sets the text for the expanded picture form:
                    .setSummaryText(mostRecentNotification.formatPictureMessage(context)).build();
        } else {
            // Show a single notification -- big style with the text of the whole message
            notification = new NotificationCompat2.BigTextStyle(noti)
                    .bigText(mostRecentNotification.formatBigMessage(context)).build();
        }
    } else {
        // We've got multiple messages
        if (uniqueThreadCount == 1) {
            // 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[] = sNotificationSet.toArray(new NotificationInfo[sNotificationSet.size()]);
            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
            notification = new NotificationCompat2.BigTextStyle(noti).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 : " ").build();
        } else {
            // Build a set of the most recent notification per threadId.
            HashSet<Long> uniqueThreads = new HashSet<Long>(sNotificationSet.size());
            ArrayList<NotificationInfo> mostRecentNotifPerThread = new ArrayList<NotificationInfo>();
            Iterator<NotificationInfo> notifications = sNotificationSet.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));
            NotificationCompat2.InboxStyle inboxStyle = new NotificationCompat2.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();
            if (DEBUG) {
                Log.d(TAG, "updateNotification: multi messages," + " showing inboxStyle notification");
            }
        }
    }

    // TDH
    Log.d("NotificationDebug", "Showing notification: " + notification);

    nm.notify(NOTIFICATION_ID, notification);
}

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

private static synchronized void doNotify(final Notification notification,
        final NotificationState notificationState) {
    if (notification == null) {
        return;/*from   ww  w.  j  av  a  2s.  c  o m*/
    }
    final int type = notificationState.mType;
    final ConversationIdSet conversationIds = notificationState.mConversationIds;
    final boolean isBundledNotification = (notificationState instanceof BundledMessageNotificationState);

    // Mark the notification as finished
    notificationState.mCanceled = true;

    final NotificationManagerCompat notificationManager = NotificationManagerCompat
            .from(Factory.get().getApplicationContext());
    // Only need conversationId for tags with a single conversation.
    String conversationId = null;
    if (conversationIds != null && conversationIds.size() == 1) {
        conversationId = conversationIds.first();
    }
    final String notificationTag = buildNotificationTag(type, conversationId, isBundledNotification);

    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notification.defaults |= Notification.DEFAULT_LIGHTS;

    notificationManager.notify(notificationTag, type, notification);

    LogUtil.i(TAG, "Notifying for conversation " + conversationId + "; " + "tag = " + notificationTag
            + ", type = " + type);
}

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 .jav a2 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:org.eclipse.paho.android.service.MqttConnection.java

private void parseMqttMessageV2(String topic, MqttMessage mqttMessage) throws Exception {
    Log.v("mqtt", "parseMqttMessageV2");
    Context ctx = NanuService.getContext();
    byte origMqttMsgByte[] = mqttMessage.getPayload();
    int mqttIndex = 0;
    boolean processVTagSuccess = false;

    boolean processPTagSuccess = false;
    long mqttPacketValue = 0;

    boolean processTTagSuccess = false;
    long mqttTimestampValue = 0;

    boolean processLTagSuccess = false;
    int mqttMsgLengthValue = 0;

    boolean processMTagSuccess = false;
    String mqttMessageValue = "";
    String mqttMembersValue = "";

    boolean processGTagSuccess = false;
    long mqttGroupIDValue = 0;

    boolean processSTagSuccess = false;
    String mqttSubjectValue = "";

    boolean processCTagSuccess = false;
    int mqttMemberCountValue = 0;

    boolean processNTagSuccess = false;
    int mqttAdminCountValue = 0;

    boolean processATagSuccess = false;
    String mqttAdminsValue = "";

    String[] topicArray = topic.split("\\/");

    String sender = topicArray[2];
    if (topicArray.length == 4) {
        processGTagSuccess = true;//w w w  .  j av a  2 s  .  c  om
        try {
            mqttGroupIDValue = Long.parseLong(topicArray[3].toString().trim());
        } catch (NumberFormatException nfe) {
            processGTagSuccess = false;
            nfe.printStackTrace();
        }

        if (mqttGroupIDValue == 0) {
            try {
                mqttGroupIDValue = Long.valueOf(topicArray[3].trim());
            } catch (Exception err) {
                processGTagSuccess = false;
                err.printStackTrace();
            }
        }
    }

    String mqttMsgDateValue = "";
    for (int indexMqttCounter = 0; indexMqttCounter < origMqttMsgByte.length; indexMqttCounter++) {
        /*       Log.v(SettingsManager.TAG, "MqttService origMqttMsgByte[" + indexMqttCounter + "] = " + origMqttMsgByte[indexMqttCounter]); */
    }

    for (int indexMqttCounter = 0; indexMqttCounter < origMqttMsgByte.length; indexMqttCounter++) {
        if (indexMqttCounter == 0) {
            mqttIndex = indexMqttCounter;
            long mqttVTag = getMqttTag(origMqttMsgByte, mqttIndex);
            if (mqttVTag != -1) {
                if (mqttVTag == 86) // "V"
                {
                    processVTagSuccess = true;
                    mqttIndex = mqttIndex + 2;
                } else {
                    processVTagSuccess = false;
                    break;
                }
            }
        } else {
            if (mqttIndex == indexMqttCounter) {
                long mqttTag = getMqttTag(origMqttMsgByte, mqttIndex);
                if (mqttTag != -1) {
                    if (mqttTag == 80) /* "P" */ {
                        mqttIndex = mqttIndex + 1;
                        long mPValue = origMqttMsgByte[mqttIndex];
                        mqttPacketValue = mPValue;
                        mqttIndex = mqttIndex + 1;
                        processPTagSuccess = true;
                    } else if (mqttTag == 84) /* "T" */ {
                        mqttIndex = mqttIndex + 1;
                        byte timeStampArray[] = new byte[8];
                        for (int i = 0; i < 8; i++) {
                            timeStampArray[i] = origMqttMsgByte[mqttIndex + i];
                        }
                        mqttTimestampValue = ByteBuffer.wrap(timeStampArray).order(ByteOrder.LITTLE_ENDIAN)
                                .getLong();

                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
                        String messageYear = sdf.format(mqttTimestampValue);
                        if (messageYear.length() != 4) {
                            mqttTimestampValue = ByteBuffer.wrap(timeStampArray).order(ByteOrder.BIG_ENDIAN)
                                    .getLong();
                        }
                        SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String messageDate = sdfDate.format(mqttTimestampValue);
                        processTTagSuccess = true;
                        mqttIndex = mqttIndex + 8;
                    } else if (mqttTag == 76) /* "L" */ {
                        if (processPTagSuccess) {
                            if (mqttPacketValue == -128 || (mqttPacketValue == -117)
                                    || (mqttPacketValue == -115) || (mqttPacketValue == -126)) {
                                mqttIndex = mqttIndex + 1;
                                mqttMsgLengthValue = origMqttMsgByte[mqttIndex];
                                processLTagSuccess = true;
                                mqttIndex = mqttIndex + 1;
                            } else if (mqttPacketValue == 0) {
                                mqttIndex = mqttIndex + 1;
                                byte msgLengthArray[] = new byte[4];
                                for (int i = 0; i < 4; i++) {
                                    msgLengthArray[i] = origMqttMsgByte[mqttIndex + i];
                                }
                                mqttMsgLengthValue = ByteBuffer.wrap(msgLengthArray)
                                        .order(ByteOrder.LITTLE_ENDIAN).getInt();
                                processLTagSuccess = true;
                                mqttIndex = mqttIndex + 4;
                            }
                        }
                    } else if (mqttTag == 77) /* "M" */ {
                        if (processPTagSuccess) {
                            if ((mqttPacketValue == -128) || (mqttPacketValue == -124)
                                    || (mqttPacketValue == -126) || (mqttPacketValue == -117)) {

                                if (processCTagSuccess) {
                                    mqttIndex = mqttIndex + 1;
                                    for (int i = 0; i < mqttMemberCountValue; i++) {
                                        byte groupMembersArray[] = new byte[8];
                                        for (int j = 0; j < 8; j++) {
                                            groupMembersArray[j] = origMqttMsgByte[mqttIndex + j];
                                        }
                                        long participants = ByteBuffer.wrap(groupMembersArray)
                                                .order(ByteOrder.LITTLE_ENDIAN).getLong();
                                        mqttIndex = mqttIndex + 8;
                                        if (i == (mqttMemberCountValue - 1)) {
                                            mqttMembersValue = mqttMembersValue + participants;
                                        } else {
                                            mqttMembersValue = mqttMembersValue + participants + ",";
                                        }
                                    }
                                    processMTagSuccess = true;
                                } else {
                                    break;
                                }
                            } else if (mqttPacketValue == 0) {
                                if (processLTagSuccess) {
                                    mqttIndex = mqttIndex + 1;
                                    if (mqttMsgLengthValue > 0) {
                                        byte messageArray[] = null;
                                        try {
                                            messageArray = new byte[mqttMsgLengthValue];
                                        } catch (Exception err) {
                                            err.printStackTrace();
                                            processMTagSuccess = false;
                                            break;
                                        }

                                        for (int i = 0; i < mqttMsgLengthValue; i++) {
                                            messageArray[i] = origMqttMsgByte[mqttIndex + i];
                                        }
                                        mqttMessageValue = new String(messageArray);
                                        processMTagSuccess = true;
                                        mqttIndex = mqttIndex + mqttMsgLengthValue + 1;
                                    }
                                } else {
                                    break;
                                }
                            }
                        }
                    } else if (mqttTag == 71) /* "G" */ {
                        mqttIndex = mqttIndex + 1;
                        byte groupIDArray[] = new byte[8];
                        for (int i = 0; i < 8; i++) {
                            groupIDArray[i] = origMqttMsgByte[mqttIndex + i];
                        }
                        mqttGroupIDValue = ByteBuffer.wrap(groupIDArray).order(ByteOrder.LITTLE_ENDIAN)
                                .getLong();
                        processGTagSuccess = true;
                        mqttIndex = mqttIndex + 8;
                    } else if (mqttTag == 83) /* "S" */ {
                        if (processLTagSuccess) {
                            mqttIndex = mqttIndex + 1;
                            if (mqttMsgLengthValue > 0) {
                                byte subjectArray[] = null;
                                try {
                                    subjectArray = new byte[mqttMsgLengthValue];
                                } catch (Exception err) {
                                    err.printStackTrace();
                                    processSTagSuccess = false;
                                    break;
                                }
                                for (int i = 0; i < mqttMsgLengthValue; i++) {
                                    subjectArray[i] = origMqttMsgByte[mqttIndex + i];
                                }
                                mqttSubjectValue = new String(subjectArray);
                                processSTagSuccess = true;
                                mqttIndex = mqttIndex + mqttMsgLengthValue;
                            }
                        } else {
                            break;
                        }
                    } else if (mqttTag == 67) /* "C" */ {
                        mqttIndex = mqttIndex + 1;
                        mqttMemberCountValue = origMqttMsgByte[mqttIndex];
                        processCTagSuccess = true;
                        mqttIndex = mqttIndex + 1;
                    } else if (mqttTag == 78) /* "N" */ {
                        mqttIndex = mqttIndex + 1;
                        mqttAdminCountValue = origMqttMsgByte[mqttIndex];
                        processNTagSuccess = true;
                        mqttIndex = mqttIndex + 1;
                    } else if (mqttTag == 65) /* "A" */ {
                        if (processPTagSuccess) {
                            if (mqttPacketValue == -117) {
                                if (processNTagSuccess) {
                                    mqttIndex = mqttIndex + 1;
                                    for (int i = 0; i < mqttAdminCountValue; i++) {
                                        byte groupAdminsArray[] = new byte[8];
                                        for (int j = 0; j < 8; j++) {
                                            groupAdminsArray[j] = origMqttMsgByte[mqttIndex + j];
                                        }
                                        long admins = ByteBuffer.wrap(groupAdminsArray)
                                                .order(ByteOrder.LITTLE_ENDIAN).getLong();
                                        mqttIndex = mqttIndex + 8;
                                        if (i == (mqttAdminCountValue - 1)) {
                                            mqttAdminsValue = mqttAdminsValue + admins;
                                        } else {
                                            mqttAdminsValue = mqttAdminsValue + admins + ",";
                                        }
                                    }
                                    processATagSuccess = true;
                                } else {
                                    break;
                                }
                            }
                        }
                    } else {
                        break;
                    }
                } else {
                    break;
                }
            }
        }
    }

    if (!processVTagSuccess) {
        return;
    }

    PowerManager pm = (PowerManager) ctx.getSystemService(Context.POWER_SERVICE);
    boolean isScreenOn = pm.isScreenOn();
    if (isScreenOn == false) {
        WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP
                | PowerManager.ON_AFTER_RELEASE, "MyLock");
        if (wl.isHeld()) {
            wl.release();
        }
        wl.acquire(10000);
        WakeLock wl_cpu = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyCpuLock");
        if (wl_cpu.isHeld()) {
            wl_cpu.release();
        }
        wl_cpu.acquire(10000);
    }

    String message = mqttMessageValue;
    Log.v("mqtt", "from: " + sender);
    Log.v("mqtt", "message: " + message);
    Intent intent = new Intent();
    intent.setClassName(ctx, "org.eclipse.paho.android.service.sample.MainActivity");
    intent.putExtra("handle", clientHandle);
    String ns = Context.NOTIFICATION_SERVICE;
    NotificationManager mNotificationManager = (NotificationManager) ctx.getSystemService(ns);
    int messageNotificationId = 1;
    mNotificationManager.cancel(messageNotificationId);
    Calendar.getInstance().getTime().toString();
    long when = System.currentTimeMillis();
    String ticker = sender + " " + mqttMessageValue;
    PendingIntent pendingIntent = PendingIntent.getActivity(ctx, 3, intent, 0);
    NotificationCompat.Builder notificationCompat = new NotificationCompat.Builder(ctx);
    notificationCompat.setAutoCancel(true).setContentTitle(sender).setContentIntent(pendingIntent)
            .setContentText(mqttMessageValue).setTicker(ticker).setWhen(when)
            .setSmallIcon(R.drawable.ic_launcher);

    //  Notification notification = notificationCompat.build();
    Bitmap iconLarge = BitmapFactory.decodeResource(ctx.getResources(), R.drawable.ic_launcher);
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(ctx)
            .setSmallIcon(R.drawable.ic_launcher).setLargeIcon(iconLarge).setContentTitle(sender)
            .setContentText(mqttMessageValue);

    mBuilder.setContentIntent(pendingIntent);
    mBuilder.setTicker(message);
    mBuilder.setAutoCancel(true);
    mBuilder.setDefaults(
            Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS);
    mNotificationManager.notify(messageNotificationId, mBuilder.build());
}