Example usage for android.app Notification DEFAULT_SOUND

List of usage examples for android.app Notification DEFAULT_SOUND

Introduction

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

Prototype

int DEFAULT_SOUND

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

Click Source Link

Document

Use the default notification sound.

Usage

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

private void notifySession(final long sessionStart, final long alarmOffset) {
    long currentTime = UIUtils.getCurrentTime(this);
    final long intervalEnd = sessionStart + MILLI_TEN_MINUTES;
    LogUtils.LOGD(TAG, "Considering notifying for time interval.");
    LogUtils.LOGD(TAG, "    Interval start: " + sessionStart + "=" + (new Date(sessionStart)).toString());
    LogUtils.LOGD(TAG, "    Interval end: " + intervalEnd + "=" + (new Date(intervalEnd)).toString());
    LogUtils.LOGD(TAG, "    Current time is: " + currentTime + "=" + (new Date(currentTime)).toString());
    if (sessionStart < currentTime) {
        LogUtils.LOGD(TAG, "Skipping session notification (too late -- time interval already started)");
        return;//ww  w. j a v a 2 s .  c om
    }

    if (!SettingsUtils.shouldShowSessionReminders(this)) {
        // skip if disabled in settings
        LogUtils.LOGD(TAG, "Skipping session notification for sessions. Disabled in settings.");
        return;
    }

    // Avoid repeated notifications.
    if (alarmOffset == UNDEFINED_ALARM_OFFSET && UIUtils.isNotificationFiredForBlock(this,
            ScheduleContract.Blocks.generateBlockId(sessionStart, intervalEnd))) {
        LogUtils.LOGD(TAG, "Skipping session notification (already notified)");
        return;
    }

    final ContentResolver cr = getContentResolver();

    LogUtils.LOGD(TAG, "Looking for sessions in interval " + sessionStart + " - " + intervalEnd);
    Cursor c = null;
    try {
        c = cr.query(ScheduleContract.Sessions.CONTENT_MY_SCHEDULE_URI, SessionDetailQuery.PROJECTION,
                ScheduleContract.Sessions.STARTING_AT_TIME_INTERVAL_SELECTION,
                ScheduleContract.Sessions.buildAtTimeIntervalArgs(sessionStart, intervalEnd), null);
        int starredCount = c.getCount();
        LogUtils.LOGD(TAG, "# starred sessions in that interval: " + c.getCount());
        String singleSessionId = null;
        String singleSessionRoomId = null;
        ArrayList<String> starredSessionTitles = new ArrayList<String>();
        while (c.moveToNext()) {
            singleSessionId = c.getString(SessionDetailQuery.SESSION_ID);
            singleSessionRoomId = c.getString(SessionDetailQuery.ROOM_ID);
            starredSessionTitles.add(c.getString(SessionDetailQuery.SESSION_TITLE));
            LogUtils.LOGD(TAG, "-> Title: " + c.getString(SessionDetailQuery.SESSION_TITLE));
        }
        if (starredCount < 1) {
            return;
        }

        // Generates the pending intent which gets fired when the user taps on the notification.
        // NOTE: Use TaskStackBuilder to comply with Android's design guidelines
        // related to navigation from notifications.
        Intent baseIntent = new Intent(this, MyScheduleActivity.class);
        baseIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        TaskStackBuilder taskBuilder = TaskStackBuilder.create(this).addNextIntent(baseIntent);

        // For a single session, tapping the notification should open the session details (b/15350787)
        if (starredCount == 1) {
            taskBuilder.addNextIntent(
                    new Intent(Intent.ACTION_VIEW, ScheduleContract.Sessions.buildSessionUri(singleSessionId)));
        }

        PendingIntent pi = taskBuilder.getPendingIntent(0, PendingIntent.FLAG_CANCEL_CURRENT);

        final Resources res = getResources();
        String contentText;
        int minutesLeft = (int) (sessionStart - currentTime + 59000) / 60000;
        if (minutesLeft < 1) {
            minutesLeft = 1;
        }

        if (starredCount == 1) {
            contentText = res.getString(R.string.session_notification_text_1, minutesLeft);
        } else {
            contentText = res.getQuantityString(R.plurals.session_notification_text, starredCount - 1,
                    minutesLeft, starredCount - 1);
        }

        NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(this)
                .setContentTitle(starredSessionTitles.get(0)).setContentText(contentText)
                .setColor(getResources().getColor(R.color.theme_primary))
                .setTicker(res
                        .getQuantityString(R.plurals.session_notification_ticker, starredCount, starredCount))
                .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
                .setLights(SessionAlarmService.NOTIFICATION_ARGB_COLOR,
                        SessionAlarmService.NOTIFICATION_LED_ON_MS, SessionAlarmService.NOTIFICATION_LED_OFF_MS)
                .setSmallIcon(R.drawable.ic_stat_notification).setContentIntent(pi)
                .setPriority(Notification.PRIORITY_MAX).setAutoCancel(true);
        if (minutesLeft > 5) {
            notifBuilder.addAction(R.drawable.ic_alarm_holo_dark,
                    String.format(res.getString(R.string.snooze_x_min), 5),
                    createSnoozeIntent(sessionStart, intervalEnd, 5));
        }
        if (starredCount == 1 && SettingsUtils.isAttendeeAtVenue(this)) {
            notifBuilder.addAction(R.drawable.ic_map_holo_dark, res.getString(R.string.title_map),
                    createRoomMapIntent(singleSessionRoomId));
        }
        String bigContentTitle;
        if (starredCount == 1 && starredSessionTitles.size() > 0) {
            bigContentTitle = starredSessionTitles.get(0);
        } else {
            bigContentTitle = res.getQuantityString(R.plurals.session_notification_title, starredCount,
                    minutesLeft, starredCount);
        }
        NotificationCompat.InboxStyle richNotification = new NotificationCompat.InboxStyle(notifBuilder)
                .setBigContentTitle(bigContentTitle);

        // Adds starred sessions starting at this time block to the notification.
        for (int i = 0; i < starredCount; i++) {
            richNotification.addLine(starredSessionTitles.get(i));
        }
        NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        LogUtils.LOGD(TAG, "Now showing notification.");
        nm.notify(NOTIFICATION_ID, richNotification.build());
    } finally {
        if (c != null) {
            try {
                c.close();
            } catch (Exception ignored) {
            }
        }
    }
}

From source file:com.bonsai.wallet32.WalletService.java

private void showEventNotification(int noteId, int icon, String title, String msg) {
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setSmallIcon(icon)
            .setContentTitle(title).setContentText(msg).setAutoCancel(true).setDefaults(
                    Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);

    // Creates an explicit intent for an Activity in your app
    Intent intent = new Intent(this, ViewTransactionsActivity.class);

    // The stack builder object will contain an artificial back
    // stack for the started Activity.  This ensures that
    // navigating backward from the Activity leads out of your
    // application to the Home screen.
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    // Adds the back stack for the Intent (but not the Intent itself)
    stackBuilder.addParentStack(ViewTransactionsActivity.class);
    // Adds the Intent that starts the Activity to the top of the stack
    stackBuilder.addNextIntent(intent);/*  w w  w.  j av a  2  s .c  o  m*/
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(resultPendingIntent);

    mNM.notify(noteId, mBuilder.build());
}

From source file:com.test.onesignal.GenerateNotificationRunner.java

@Test
@Config(sdk = 17)/*  w  ww.  j  ava  2s.c o  m*/
public void notificationExtenderServiceOverridePropertiesWithSummaryApi17() throws Exception {
    testNotificationExtenderServiceOverridePropertiesWithSummary();

    Map<Integer, PostedNotification> postedNotifs = ShadowRoboNotificationManager.notifications;
    Iterator<Map.Entry<Integer, PostedNotification>> postedNotifsIterator = postedNotifs.entrySet().iterator();

    // Test - First notification should be the summary with the custom sound set.
    PostedNotification postedSummaryNotification = postedNotifsIterator.next().getValue();
    Assert.assertNotSame(Notification.DEFAULT_SOUND,
            postedSummaryNotification.notif.flags & Notification.DEFAULT_SOUND);
    Assert.assertEquals("content://media/internal/audio/media/32",
            postedSummaryNotification.notif.sound.toString());

    Assert.assertEquals(1, postedNotifs.size());
}

From source file:com.test.onesignal.GenerateNotificationRunner.java

@Test
@Config(sdk = 21)//from  www  .  jav  a  2  s  .com
public void notificationExtenderServiceOverridePropertiesWithSummary() throws Exception {
    testNotificationExtenderServiceOverridePropertiesWithSummary();

    Map<Integer, PostedNotification> postedNotifs = ShadowRoboNotificationManager.notifications;
    Iterator<Map.Entry<Integer, PostedNotification>> postedNotifsIterator = postedNotifs.entrySet().iterator();

    // Test - First notification should be the summary with the custom sound set.
    PostedNotification postedSummaryNotification = postedNotifsIterator.next().getValue();
    Assert.assertNotSame(Notification.DEFAULT_SOUND,
            postedSummaryNotification.notif.flags & Notification.DEFAULT_SOUND);
    Assert.assertEquals("content://media/internal/audio/media/32",
            postedSummaryNotification.notif.sound.toString());

    // Test - individual notification 1 should not play a sound
    PostedNotification notification = postedNotifsIterator.next().getValue();
    Assert.assertNotSame(Notification.DEFAULT_SOUND, notification.notif.flags & Notification.DEFAULT_SOUND);
    Assert.assertNull(notification.notif.sound);

    // Test - individual notification 2 should not play a sound
    notification = postedNotifsIterator.next().getValue();
    Assert.assertNotSame(Notification.DEFAULT_SOUND, notification.notif.flags & Notification.DEFAULT_SOUND);
    Assert.assertNull(notification.notif.sound);
}

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:im.neon.services.EventStreamService.java

/**
 * Display a permanent notification when there is an incoming call.
 * @param session the session// w w  w .j av  a 2  s  . c o m
 * @param room the room
 * @param event the event
 * @param callId the callId
 * @param bingRule the bing rule.
 */
private void displayIncomingCallNotification(MXSession session, Room room, Event event, String callId,
        BingRule bingRule) {
    Log.d(LOG_TAG, "displayIncomingCallNotification : " + callId + " in " + room.getRoomId());

    // the incoming call in progress is already displayed
    if (!TextUtils.isEmpty(mIncomingCallId)) {
        Log.d(LOG_TAG, "displayIncomingCallNotification : the incoming call in progress is already displayed");
    } else if (!TextUtils.isEmpty(mCallIdInProgress)) {
        Log.d(LOG_TAG, "displayIncomingCallNotification : a 'call in progress' notification is displayed");
    }
    // test if there is no active call
    else if (null == VectorCallViewActivity.getActiveCall()) {
        Log.d(LOG_TAG, "displayIncomingCallNotification : display the dedicated notification");

        if ((null != bingRule) && bingRule.isCallRingNotificationSound(bingRule.notificationSound())) {
            VectorCallSoundManager.startRinging();
        }

        Notification notification = NotificationUtils.buildIncomingCallNotification(EventStreamService.this,
                getRoomName(session, room, event), session.getMyUserId(), callId);

        if ((null != bingRule) && bingRule.isDefaultNotificationSound(bingRule.notificationSound())) {
            notification.defaults |= Notification.DEFAULT_SOUND;
        }

        startForeground(NOTIF_ID_FOREGROUND_SERVICE, notification);
        mForegroundServiceIdentifier = FOREGROUND_ID_INCOMING_CALL;

        mIncomingCallId = callId;

        // turn the screen on for 3 seconds
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        PowerManager.WakeLock wl = pm.newWakeLock(
                PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "MXEventListener");
        wl.acquire(3000);
        wl.release();

    } else {
        Log.d(LOG_TAG,
                "displayIncomingCallNotification : do not display the incoming call notification because there is a pending call");
    }
}

From source file:es.javocsoft.android.lib.toolbox.ToolBox.java

/**
 * Creates a system notification.//w w  w . j a v a2  s . c o  m
 *    
 * @param context            Context.
 * @param notSound            Enable or disable the sound
 * @param notSoundRawId         Custom raw sound id. If enabled and not set 
 *                         default notification sound will be used. Set to -1 to 
 *                         default system notification.
 * @param multipleNot         Setting to True allows showing multiple notifications.
 * @param groupMultipleNotKey   If is set, multiple notifications can be grupped by this key.
 * @param notAction            Action for this notification
 * @param notTitle            Title
 * @param notMessage         Message
 * @param notClazz            Class to be executed
 * @param extras            Extra information
 * 
 */
public static void notification_generate(Context context, boolean notSound, int notSoundRawId,
        boolean multipleNot, String groupMultipleNotKey, String notAction, String notTitle, String notMessage,
        Class<?> notClazz, Bundle extras, boolean wakeUp) {

    try {
        int iconResId = notification_getApplicationIcon(context);
        long when = System.currentTimeMillis();

        Notification notification = new Notification(iconResId, notMessage, when);

        // Hide the notification after its selected
        notification.flags |= Notification.FLAG_AUTO_CANCEL;

        if (notSound) {
            if (notSoundRawId > 0) {
                try {
                    notification.sound = Uri.parse("android.resource://"
                            + context.getApplicationContext().getPackageName() + "/" + notSoundRawId);
                } catch (Exception e) {
                    if (LOG_ENABLE) {
                        Log.w(TAG, "Custom sound " + notSoundRawId + "could not be found. Using default.");
                    }
                    notification.defaults |= Notification.DEFAULT_SOUND;
                    notification.sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                }
            } else {
                notification.defaults |= Notification.DEFAULT_SOUND;
                notification.sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            }
        }

        Intent notificationIntent = new Intent(context, notClazz);
        notificationIntent.setAction(notClazz.getName() + "." + notAction);
        if (extras != null) {
            notificationIntent.putExtras(extras);
        }

        //Set intent so it does not start a new activity
        //
        //Notes:
        //   - The flag FLAG_ACTIVITY_SINGLE_TOP makes that only one instance of the activity exists(each time the
        //      activity is summoned no onCreate() method is called instead, onNewIntent() is called.
        //  - If we use FLAG_ACTIVITY_CLEAR_TOP it will make that the last "snapshot"/TOP of the activity it will 
        //     be this called this intent. We do not want this because the HOME button will call this "snapshot". 
        //     To avoid this behaviour we use FLAG_ACTIVITY_BROUGHT_TO_FRONT that simply takes to foreground the 
        //     activity.
        //
        //See http://developer.android.com/reference/android/content/Intent.html           
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_SINGLE_TOP);

        PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        int REQUEST_UNIQUE_ID = 0;
        if (multipleNot) {
            if (groupMultipleNotKey != null && groupMultipleNotKey.length() > 0) {
                REQUEST_UNIQUE_ID = groupMultipleNotKey.hashCode();
            } else {
                if (random == null) {
                    random = new Random();
                }
                REQUEST_UNIQUE_ID = random.nextInt();
            }
            PendingIntent.getActivity(context, REQUEST_UNIQUE_ID, notificationIntent,
                    PendingIntent.FLAG_ONE_SHOT);
        }

        notification.setLatestEventInfo(context, notTitle, notMessage, intent);

        //This makes the device to wake-up is is idle with the screen off.
        if (wakeUp) {
            powersaving_wakeUp(context);
        }

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

        //We check if the sound is disabled to enable just for a moment
        AudioManager amanager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        int previousAudioMode = amanager.getRingerMode();
        ;
        if (notSound && previousAudioMode != AudioManager.RINGER_MODE_NORMAL) {
            amanager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
        }

        notificationManager.notify(REQUEST_UNIQUE_ID, notification);

        //We restore the sound setting
        if (previousAudioMode != AudioManager.RINGER_MODE_NORMAL) {
            //We wait a little so sound is played
            try {
                Thread.sleep(3000);
            } catch (Exception e) {
            }
        }
        amanager.setRingerMode(previousAudioMode);

        Log.d(TAG, "Android Notification created.");

    } catch (Exception e) {
        if (LOG_ENABLE)
            Log.e(TAG, "The notification could not be created (" + e.getMessage() + ")", e);
    }
}

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: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;//from   www. j  ava2 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.zuzhili.bussiness.helper.CCPHelper.java

/**
 * ???/*from  w  w w . j av  a  2s .c om*/
 * 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);
}