Example usage for android.app Notification DEFAULT_VIBRATE

List of usage examples for android.app Notification DEFAULT_VIBRATE

Introduction

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

Prototype

int DEFAULT_VIBRATE

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

Click Source Link

Document

Use the default notification vibrate.

Usage

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

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

    AppSettings settings = AppSettings.getInstance(context);

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

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

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

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

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

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

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

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

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

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

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

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

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

    if (settings.notifications) {

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);

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

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

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

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

From source file:com.paywith.ibeacon.service.IBeaconService.java

protected void generateNotification(String title, String merchanttext, String murl, String location_id) {

    String ns = Context.NOTIFICATION_SERVICE;
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);

    Builder mNotifyBuilder = new NotificationCompat.Builder(this);

    //int icon = R.drawable.ic_launcher;
    //CharSequence tickerText = "PayWith";
    //long when = System.currentTimeMillis();

    //@SuppressWarnings("deprecation")
    //Notification notification = new Notification(icon,
    //        tickerText, when);

    mNotifyBuilder.setContentText(merchanttext).setContentTitle(title).setSmallIcon(R.drawable.ic_launcher);//logo

    //notification.flags |= Notification.FLAG_AUTO_CANCEL;
    Context context = getApplicationContext();
    Intent notificationIntent = new Intent("android.intent.category.LAUNCHER");
    //CharSequence contentTitle = title;
    //CharSequence contentText = merchanttext;

    notificationIntent.putExtra("OpenUrl", murl);
    notificationIntent.putExtra("MerchantName", merchanttext);
    notificationIntent.setClassName("com.paywith.paywith", "com.paywith.paywith.MainActivity");

    //PendingIntent contentIntent = PendingIntent
    //         .getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);

    //notification.setLatestEventInfo(context, contentTitle,
    //        contentText, contentIntent);

    //mNotificationManager.notify(ongoing_notification_id, notification);

    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);
    // PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT

    // this gives us flexibility to add vibration and sound etc:
    Notification note = mNotifyBuilder.build();

    // THIS line is what makes the notification tappable to launch app and generate mCard payment:
    note.setLatestEventInfo(context, title, merchanttext, contentIntent);

    // make phone vibrate and make sound on notification:
    note.defaults |= Notification.DEFAULT_VIBRATE;
    note.defaults |= Notification.DEFAULT_SOUND;

    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    //Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP

    note.flags |= Notification.FLAG_AUTO_CANCEL;
    // Because the ID remains unchanged, the existing notification is updated.
    mNotificationManager.notify(ongoing_notification_id, note);
    //Log.e("notification","sent");
}

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

/**
 * updateNotification is *the* main function for building the actual notification handed to
 * the NotificationManager//w w  w . j  a va 2s  . c  o m
 * @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  a2 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());
}

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

private static void notifyFailed(Context context, boolean isDownload, long threadId, boolean noisy) {
    // TODO factor out common code for creating notifications
    boolean enabled = MessagingPreferenceActivity.getNotificationEnabled(context);
    if (!enabled) {
        return;/* w w  w .  j  a va 2s. c  om*/
    }

    // Strategy:
    // a. If there is a single failure notification, tapping on the notification goes
    //    to the compose view.
    // b. If there are two failure it stays in the thread view. Selecting one undelivered
    //    thread will dismiss one undelivered notification but will still display the
    //    notification.If you select the 2nd undelivered one it will dismiss the notification.

    long[] msgThreadId = { 0, 1 }; // Dummy initial values, just to initialize the memory
    int totalFailedCount = getUndeliveredMessageCount(context, msgThreadId);
    if (totalFailedCount == 0 && !isDownload) {
        return;
    }
    // The getUndeliveredMessageCount method puts a non-zero value in msgThreadId[1] if all
    // failures are from the same thread.
    // If isDownload is true, we're dealing with 1 specific failure; therefore "all failed" are
    // indeed in the same thread since there's only 1.
    boolean allFailedInSameThread = (msgThreadId[1] != 0) || isDownload;

    Intent failedIntent;
    Notification notification = new Notification();
    String title;
    String description;
    if (totalFailedCount > 1) {
        description = context.getString(R.string.notification_failed_multiple,
                Integer.toString(totalFailedCount));
        title = context.getString(R.string.notification_failed_multiple_title);
    } else {
        title = isDownload ? context.getString(R.string.message_download_failed_title)
                : context.getString(R.string.message_send_failed_title);

        description = context.getString(R.string.message_failed_body);
    }

    TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context);
    if (allFailedInSameThread) {
        failedIntent = new Intent(context, ComposeMessageActivity.class);
        if (isDownload) {
            // When isDownload is true, the valid threadId is passed into this function.
            failedIntent.putExtra("failed_download_flag", true);
        } else {
            threadId = msgThreadId[0];
            failedIntent.putExtra("undelivered_flag", true);
        }
        failedIntent.putExtra("thread_id", threadId);
        taskStackBuilder.addParentStack(ComposeMessageActivity.class);
    } else {
        failedIntent = new Intent(context, ConversationList.class);
    }
    taskStackBuilder.addNextIntent(failedIntent);

    notification.icon = R.drawable.stat_notify_sms_failed;

    notification.tickerText = title;

    notification.setLatestEventInfo(context, title, description,
            taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT));

    if (noisy) {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
        boolean vibrate = sp.getBoolean(MessagingPreferenceActivity.NOTIFICATION_VIBRATE,
                false /* don't vibrate by default */);
        if (vibrate) {
            notification.defaults |= Notification.DEFAULT_VIBRATE;
        }

        String ringtoneStr = sp.getString(MessagingPreferenceActivity.NOTIFICATION_RINGTONE, null);
        notification.sound = TextUtils.isEmpty(ringtoneStr) ? null : Uri.parse(ringtoneStr);
    }

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

    if (isDownload) {
        notificationMgr.notify(DOWNLOAD_FAILED_NOTIFICATION_ID, notification);
    } else {
        notificationMgr.notify(MESSAGE_FAILED_NOTIFICATION_ID, notification);
    }
}

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

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

    AppSettings settings = AppSettings.getInstance(context);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    if (settings.notifications) {

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);

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

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

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

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

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

public static void sendTestNotification(Context context) {

    if (!TEST_NOTIFICATION) {
        return;//from  w  w  w .ja  va  2  s .  c  o m
    }

    AppSettings settings = AppSettings.getInstance(context);

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

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

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

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

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

    NotificationCompat.Builder mBuilder;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

From source file:com.zuzhili.bussiness.helper.CCPHelper.java

/**
 * ???/*from  ww w  . j  a  v  a  2 s.co  m*/
 * content  ?
 */
private void showMsgNotification(Context context, String content, String ticker, String listId) {
    // NotificationManager
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(android.content.Context.NOTIFICATION_SERVICE);

    // ?
    Intent notificationIntent = new Intent(context, HomeTabActivity.class); // ??Activity
    notificationIntent.putExtra(Constants.TO_GROUPSLISTFRG, "ok");
    notificationIntent.putExtra(Constants.CHANGE_SOCIAL, listId);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);//Intent.FLAG_ACTIVITY_SINGLE_TOP|
    notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);
    notificationIntent.setData(Uri.parse("custom://" + System.currentTimeMillis()));
    PendingIntent contentItent = PendingIntent.getActivity(context, 0, notificationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    // Notification??
    Notification notification = new NotificationCompat.Builder(context)
            .setContentTitle(context.getString(R.string.new_msg_notification_title)).setContentText(content)
            .setSmallIcon(R.drawable.notify).setTicker(ticker).setContentIntent(contentItent)
            .setWhen(System.currentTimeMillis()).build();

    //FLAG_AUTO_CANCEL   ??
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notification.flags |= Notification.FLAG_SHOW_LIGHTS;
    //DEFAULT_VIBRATE <uses-permission android:name="android.permission.VIBRATE" />??
    notification.defaults = Notification.DEFAULT_VIBRATE;
    notification.defaults |= Notification.DEFAULT_SOUND;
    notification.ledARGB = Color.BLUE;
    notification.ledOnMS = 5000; //

    // ? NotificationNotificationManager
    notificationManager.cancel(0);
    notificationManager.notify(0, notification);
}

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

public static void sendTestNotification(Context context) {

    if (!TEST_NOTIFICATION) {
        return;//from w w  w.j  ava  2s.c  o  m
    }

    AppSettings settings = AppSettings.getInstance(context);

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

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

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

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

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

    NotificationCompat.Builder mBuilder;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

private static void notifyFailed(Context context, boolean isDownload, long threadId, boolean noisy) {
    // TODO factor out common code for creating notifications
    boolean enabled = MessagingPreferenceActivity.getNotificationEnabled(context);
    if (!enabled) {
        return;//  ww w  . j  av  a 2  s.  c o  m
    }

    // Strategy:
    // a. If there is a single failure notification, tapping on the notification goes
    //    to the compose view.
    // b. If there are two failure it stays in the thread view. Selecting one undelivered
    //    thread will dismiss one undelivered notification but will still display the
    //    notification.If you select the 2nd undelivered one it will dismiss the notification.
    int totalFailedCount = getUndeliveredMessageCount(context);

    Intent failedIntent;
    Notification notification = new Notification();
    String title;
    String description;
    if (totalFailedCount > 1) {
        description = context.getString(R.string.notification_failed_multiple,
                Integer.toString(totalFailedCount));
        title = context.getString(R.string.notification_failed_multiple_title);
    } else {
        title = isDownload ? context.getString(R.string.message_download_failed_title)
                : context.getString(R.string.message_send_failed_title);

        description = context.getString(R.string.message_failed_body);
    }

    TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context);
    // Get failed intent by folder mode or conversation mode.
    if (MessageUtils.isMailboxMode()) {
        failedIntent = getFailedIntentFromFolderMode(context, totalFailedCount, isDownload);
        if (failedIntent == null) {
            return;
        } else if (isDownload) {
            // When isDownload is true, the valid threadId is passed into this function.
            failedIntent.putExtra(FAILED_DOWNLOAD_FLAG, true);
        } else {
            failedIntent.putExtra(UNDELIVERED_FLAG, true);
        }
    } else {
        failedIntent = getFailedIntentFromConversationMode(context, isDownload, threadId);
    }

    taskStackBuilder.addNextIntent(failedIntent);

    notification.icon = R.drawable.stat_notify_sms_failed;

    notification.tickerText = title;

    notification.setLatestEventInfo(context, title, description,
            taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT));

    if (noisy) {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
        boolean vibrate = sp.getBoolean(MessagingPreferenceActivity.NOTIFICATION_VIBRATE,
                false /* don't vibrate by default */);
        if (vibrate) {
            notification.defaults |= Notification.DEFAULT_VIBRATE;
        }

        String ringtoneStr = sp.getString(MessagingPreferenceActivity.NOTIFICATION_RINGTONE, null);
        notification.sound = TextUtils.isEmpty(ringtoneStr) ? null : Uri.parse(ringtoneStr);
    }

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

    if (isDownload) {
        notificationMgr.notify(DOWNLOAD_FAILED_NOTIFICATION_ID, notification);
    } else {
        notificationMgr.notify(MESSAGE_FAILED_NOTIFICATION_ID, notification);
    }
}