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:net.wespot.pim.view.InqCommunicateFragment.java

private void createNotification(MessageLocalObject messageLocalObject, Long runId) {

    if (!runIdList.contains(runId)) {
        runIdList.add(runId);/*from   w  w  w .j a  va 2 s  .c  om*/
        runIdList_str.add(runId.toString());
    }

    numMessages = 0;
    mBuilder = null;
    mNotificationStyle = null;
    mNotificationManager = null;

    mNotificationManager = (NotificationManager) ARL.getContext()
            .getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationStyle = new NotificationCompat.InboxStyle();
    mBuilder = new NotificationCompat.Builder(ARL.getContext()).setSmallIcon(R.drawable.ic_launcher)
            .setAutoCancel(true).setSortKey("0")
            .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
            .setStyle(mNotificationStyle);

    InquiryLocalObject inquiryLocalObject = DaoConfiguration.getInstance().getInquiryLocalObjectDao()
            .queryBuilder().where(InquiryLocalObjectDao.Properties.RunId.eq(runId)).list().get(0);

    // 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(ARL.getContext());

    Intent resultIntent;

    if (runIdList.size() > 1) {
        resultIntent = new Intent(ARL.getContext(), PimInquiriesFragment.class);
        resultIntent.putStringArrayListExtra(INQUIRIES_ID, (ArrayList<String>) runIdList_str);

        Intent parent = new Intent(ARL.getContext(), MainActivity.class);
        Intent parent1 = new Intent(ARL.getContext(), SplashActivity.class);

        // Adds the back stack for the Intent (but not the Intent itself)
        stackBuilder.addNextIntentWithParentStack(parent1);
        stackBuilder.addNextIntentWithParentStack(parent);

    } else {
        resultIntent = new Intent(ARL.getContext(), InquiryPhasesActivity.class);
        resultIntent.putExtra(INQUIRY_ID, inquiryLocalObject.getId());

        Intent parent = new Intent(ARL.getContext(), PimInquiriesFragment.class);
        Intent parent1 = new Intent(ARL.getContext(), MainActivity.class);
        Intent parent2 = new Intent(ARL.getContext(), SplashActivity.class);

        // Adds the back stack for the Intent (but not the Intent itself)
        stackBuilder.addNextIntentWithParentStack(parent2);
        stackBuilder.addNextIntentWithParentStack(parent1);
        stackBuilder.addNextIntentWithParentStack(parent);
    }

    // Adds the Intent that starts the Activity to the top of the stack
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    mBuilder.setContentIntent(resultPendingIntent);

    if (runIdList.size() == 1) {
        // More than 1 inquiries have messages

        mBuilder.setContentTitle(inquiryLocalObject.getTitle());
        for (MessageLocalObject me : notications_queue_messages) {
            mNotificationStyle.addLine(getNameUser(me.getAuthor()) + ": " + me.getBody()).setSummaryText(
                    ++numMessages != 1 ? numMessages + " new messages" : numMessages + " new message");
        }
    }

    if (runIdList.size() > 1) {
        // More than 1 inquiries have messages

        for (MessageLocalObject me : notications_queue_messages) {
            mBuilder.setContentTitle("Personal Inquiry Manager");
            InquiryLocalObject a = DaoConfiguration.getInstance().getInquiryLocalObjectDao().queryBuilder()
                    .where(InquiryLocalObjectDao.Properties.RunId.eq(me.getRunId())).list().get(0);

            mNotificationStyle.addLine(getNameUser(me.getAuthor()) + " @ " + a.getTitle() + ": " + me.getBody())
                    .setSummaryText(++numMessages != 1
                            ? numMessages + " new messages from " + runIdList.size() + " conversations" + " "
                            : numMessages + " new message from " + runIdList.size() + " conversations");
        }
    }

    mNotificationManager.notify(Integer.parseInt(NUMBER), mBuilder.build());
}

From source file:fr.paug.droidcon.service.SessionAlarmService.java

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

    if (!PrefUtils.shouldShowSessionReminders(this)) {
        // skip if disabled in settings
        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))) {
        LOGD(TAG, "Skipping session notification (already notified)");
        return;
    }

    final ContentResolver cr = getContentResolver();

    LOGD(TAG, "Looking for sessions in interval " + sessionStart + " - " + intervalEnd);
    Cursor 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();
    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));
        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_NEW_TASK | 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))
            // Note: setColor() is available in the support lib v21+.
            // We commented it out because we want the source to compile 
            // against support lib v20. If you are using support lib
            // v21 or above on Android L, uncomment this line.
            .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));
    }
    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);
    LOGD(TAG, "Now showing notification.");
    nm.notify(NOTIFICATION_ID, richNotification.build());
}

From source file:me.myatminsoe.myansms.SmsReceiver.java

/**
 * Update new message {@link Notification}.
 *
 * @param context {@link Context}/* w w  w.  ja v a  2  s .c om*/
 * @param text    text of the last assumed unread message
 * @return number of unread messages
 */
static int updateNewMessageNotification(final Context context, final String text) {
    final NotificationManager mNotificationMgr = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    final boolean enableNotifications = prefs.getBoolean(PreferencesActivity.PREFS_NOTIFICATION_ENABLE, true);
    final boolean privateNotification = prefs.getBoolean(PreferencesActivity.PREFS_NOTIFICATION_PRIVACY, false);
    final boolean showPhoto = !privateNotification
            && prefs.getBoolean(PreferencesActivity.PREFS_CONTACT_PHOTO, true);
    if (!enableNotifications) {
        mNotificationMgr.cancelAll();
        Log.d(TAG, "no notification needed!");
    }
    final int[] status = getUnread(context.getContentResolver(), text);
    final int l = status[ID_COUNT];
    final int tid = status[ID_TID];

    // FIXME l is always -1..
    if (l < 0) {
        return l;
    }

    if (enableNotifications && (text != null || l == 0)) {
        mNotificationMgr.cancel(NOTIFICATION_ID_NEW);
    }
    Uri uri;
    PendingIntent pIntent;
    if (l == 0) {
        final Intent i = new Intent(context, ConversationListActivity.class);
        // add pending intent
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        pIntent = PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
    } else {
        final NotificationCompat.Builder nb = new NotificationCompat.Builder(context);
        boolean showNotification = true;
        Intent i;
        if (tid >= 0) {
            uri = Uri.parse(MessageListActivity.URI + tid);
            i = new Intent(Intent.ACTION_VIEW, uri, context, MessageListActivity.class);
            pIntent = PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);

            if (enableNotifications) {
                final Conversation conv = Conversation.getConversation(context, tid, true);
                if (conv != null) {
                    String a;
                    if (privateNotification) {
                        if (l == 1) {
                            a = context.getString(R.string.new_message_);
                        } else {
                            a = context.getString(R.string.new_messages_);
                        }
                    } else {
                        a = conv.getContact().getDisplayName();
                    }
                    showNotification = true;
                    nb.setSmallIcon(PreferencesActivity.getNotificationIcon(context));
                    nb.setTicker(a);
                    nb.setWhen(lastUnreadDate);
                    if (l == 1) {
                        String body;
                        if (privateNotification) {
                            body = context.getString(R.string.new_message);
                        } else {
                            body = lastUnreadBody;
                        }
                        if (body == null) {
                            body = context.getString(R.string.mms_conversation);
                        }
                        nb.setContentTitle(a);
                        nb.setContentText(body);
                        nb.setContentIntent(pIntent);
                        // add long text
                        nb.setStyle(new NotificationCompat.BigTextStyle().bigText(body));

                        // add actions
                        Intent nextIntent = new Intent(NotificationBroadcastReceiver.ACTION_MARK_READ);
                        nextIntent.putExtra(NotificationBroadcastReceiver.EXTRA_MURI, uri.toString());
                        PendingIntent nextPendingIntent = PendingIntent.getBroadcast(context, 0, nextIntent,
                                PendingIntent.FLAG_UPDATE_CURRENT);

                        nb.addAction(R.drawable.ic_done_24dp, context.getString(R.string.mark_read_),
                                nextPendingIntent);
                        nb.addAction(R.drawable.ic_reply_24dp, context.getString(R.string.reply), pIntent);
                    } else {
                        nb.setContentTitle(a);
                        nb.setContentText(context.getString(R.string.new_messages, l));
                        nb.setContentIntent(pIntent);
                    }
                    if (showPhoto // just for the speeeeed
                            && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                        try {
                            conv.getContact().update(context, false, true);
                        } catch (NullPointerException e) {
                            Log.e(TAG, "updating contact failed", e);
                        }
                        Drawable d = conv.getContact().getAvatar(context, null);
                        if (d instanceof BitmapDrawable) {
                            Bitmap bitmap = ((BitmapDrawable) d).getBitmap();
                            // 24x24 dp according to android iconography  ->
                            // http://developer.android.com/design/style/iconography.html#notification
                            int px = Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 64,
                                    context.getResources().getDisplayMetrics()));
                            nb.setLargeIcon(Bitmap.createScaledBitmap(bitmap, px, px, false));
                        }
                    }
                }
            }
        } else {
            uri = Uri.parse(MessageListActivity.URI);
            i = new Intent(Intent.ACTION_VIEW, uri, context, ConversationListActivity.class);
            pIntent = PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);

            if (enableNotifications) {
                showNotification = true;
                nb.setSmallIcon(PreferencesActivity.getNotificationIcon(context));
                nb.setTicker(context.getString(R.string.new_messages_));
                nb.setWhen(lastUnreadDate);
                nb.setContentTitle(context.getString(R.string.new_messages_));
                nb.setContentText(context.getString(R.string.new_messages, l));
                nb.setContentIntent(pIntent);
                nb.setNumber(l);
            }
        }
        // add pending intent
        i.setFlags(i.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);

        if (enableNotifications && showNotification) {
            int[] ledFlash = PreferencesActivity.getLEDflash(context);
            nb.setLights(PreferencesActivity.getLEDcolor(context), ledFlash[0], ledFlash[1]);
            final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(context);
            if (text != null) {
                final boolean vibrate = p.getBoolean(PreferencesActivity.PREFS_VIBRATE, false);
                final String s = p.getString(PreferencesActivity.PREFS_SOUND, null);
                Uri sound;
                if (s == null || s.length() <= 0) {
                    sound = null;
                } else {
                    sound = Uri.parse(s);
                }
                if (vibrate) {
                    final long[] pattern = PreferencesActivity.getVibratorPattern(context);
                    if (pattern.length == 1 && pattern[0] == 0) {
                        nb.setDefaults(Notification.DEFAULT_VIBRATE);
                    } else {
                        nb.setVibrate(pattern);
                    }
                }
                nb.setSound(sound);
            }
        }

        mNotificationMgr.cancel(NOTIFICATION_ID_NEW);
        if (enableNotifications && showNotification) {
            try {
                mNotificationMgr.notify(NOTIFICATION_ID_NEW, nb.getNotification());
            } catch (IllegalArgumentException e) {

            }
        }
    }
    //noinspection ConstantConditions
    return l;
}

From source file:com.mattprecious.notisync.service.SecondaryService.java

private void handleCustomMessage(CustomMessage message) {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    if (message.packageName.equals("com.whatsapp")) {
        builder.setSmallIcon(R.drawable.package_com_whatsapp);
    } else if (message.appName.contains("Gmail")) {
        builder.setSmallIcon(R.drawable.package_com_google_android_gm);
    } else {/* w w w  . j a  v  a 2 s.  c o m*/
        builder.setSmallIcon(R.drawable.ic_stat_logo);
    }
    builder.setContentTitle(message.messageTitle);
    builder.setContentText(message.message);

    builder.setAutoCancel(true);

    SecondaryProfile profile = null;
    if (message.tag != null) {
        dbAdapter.openReadable();
        profile = dbAdapter.getSecondaryProfileByTag(message.tag);
        dbAdapter.close();

        if (profile != null) {
            if (!profile.isEnabled()) {
                return;
            }

            if (profile.isUnconnectedOnly()) {
                if (isNetworkAvailable()) {
                    return;
                }
            }

            int defaults = 0;
            if (profile.isVibrate()) {
                defaults |= Notification.DEFAULT_VIBRATE;
            }

            if (profile.isLed()) {
                defaults |= Notification.DEFAULT_LIGHTS;
            }

            //builder.setContentTitle(profile.getName());
            builder.setDefaults(defaults);
            builder.setSound(getRingtoneUri(profile.getRingtone()));

            openNotificationDatabaseWrite();
            notificationsDbAdapter.insertNotification(message.packageName, message.tag, message.appName,
                    message.messageTitle, message.message, message.time);
            notificationsDbAdapter.close();
        }
    }

    if (profile == null) {
        builder.setDefaults(Notification.DEFAULT_ALL);
    }

    Intent showIntent = new Intent(this, NotificationListActivity.class);
    PendingIntent intent = PendingIntent.getActivity(this, 0, showIntent, 0);
    builder.setContentIntent(intent);

    Notification notification = new NotificationCompat.BigTextStyle(builder)
            //.bigText(message.messageTitle)
            .bigText(message.message).build();

    // use the profile ID to determine the notification ID
    // TODO: note that if somehow a profile ID is ~2^32, we're overwriting
    // notifications...
    int notificationId = NOTIFICATION_ID_CUSTOM;
    if (profile != null) {
        notificationId += profile.getId();
    }

    notificationManager.notify(notificationId, notification);
}

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

/** Sets up the notification's sound and vibration based upon account details. */
private void setupSoundAndVibration(NotificationCompat.Builder builder, Account account) {
    String ringtoneUri = Settings.System.DEFAULT_NOTIFICATION_URI.toString();
    boolean vibrate = false;

    // Use the Inbox notification preferences
    final Cursor accountCursor = mContext.getContentResolver().query(
            EmailProvider.uiUri("uiaccount", account.mId), UIProvider.ACCOUNTS_PROJECTION, null, null, null);

    com.tct.mail.providers.Account uiAccount = null;
    try {// w w  w. j  a v a 2 s.  c  o m
        if (accountCursor.moveToFirst()) {
            uiAccount = com.tct.mail.providers.Account.builder().buildFrom(accountCursor);
        }
    } finally {
        accountCursor.close();
    }

    if (uiAccount != null) {
        final Cursor folderCursor = mContext.getContentResolver().query(uiAccount.settings.defaultInbox,
                UIProvider.FOLDERS_PROJECTION, null, null, null);

        if (folderCursor == null) {
            // This can happen when the notification is for the security policy notification
            // that happens before the account is setup
            LogUtils.w(LOG_TAG, "Null folder cursor for mailbox %s", uiAccount.settings.defaultInbox);
        } else {
            Folder folder = null;
            try {
                if (folderCursor.moveToFirst()) {
                    folder = new Folder(folderCursor);
                }
            } finally {
                folderCursor.close();
            }

            if (folder != null) {
                final FolderPreferences folderPreferences = new FolderPreferences(mContext,
                        uiAccount.getEmailAddress(), folder, true /* inbox */);

                ringtoneUri = folderPreferences.getNotificationRingtoneUri();
                vibrate = folderPreferences.isNotificationVibrateEnabled();
            } else {
                LogUtils.e(LOG_TAG, "Null folder for mailbox %s", uiAccount.settings.defaultInbox);
            }
        }
    } else {
        LogUtils.e(LOG_TAG, "Null uiAccount for account id %d", account.mId);
    }

    int defaults = Notification.DEFAULT_LIGHTS;
    if (vibrate) {
        defaults |= Notification.DEFAULT_VIBRATE;
    }

    builder.setSound(TextUtils.isEmpty(ringtoneUri) ? null : Uri.parse(ringtoneUri)).setDefaults(defaults);
}

From source file:org.mariotaku.twidere.service.TwidereService.java

private Notification buildNotification(String message, int icon, Intent content_intent, Intent delete_intent) {
    final NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    builder.setTicker(message);//ww w  .  j  a  v  a2  s  . c  o m
    builder.setContentTitle(getString(R.string.new_notifications));
    builder.setContentText(message);
    builder.setAutoCancel(true);
    builder.setWhen(System.currentTimeMillis());
    builder.setSmallIcon(icon);
    builder.setDeleteIntent(
            PendingIntent.getBroadcast(this, 0, delete_intent, PendingIntent.FLAG_UPDATE_CURRENT));
    builder.setContentIntent(
            PendingIntent.getActivity(this, 0, content_intent, PendingIntent.FLAG_UPDATE_CURRENT));
    int defaults = 0;
    if (mPreferences.getBoolean(PREFERENCE_KEY_NOTIFICATION_HAVE_SOUND, false)) {
        builder.setSound(Uri.parse(mPreferences.getString(PREFERENCE_KEY_NOTIFICATION_RINGTONE,
                Settings.System.DEFAULT_RINGTONE_URI.getPath())), Notification.STREAM_DEFAULT);
    }
    if (mPreferences.getBoolean(PREFERENCE_KEY_NOTIFICATION_HAVE_VIBRATION, false)) {
        defaults |= Notification.DEFAULT_VIBRATE;
    }
    if (mPreferences.getBoolean(PREFERENCE_KEY_NOTIFICATION_HAVE_LIGHTS, false)) {
        final int color_def = getResources().getColor(R.color.holo_blue_light);
        final int color = mPreferences.getInt(PREFERENCE_KEY_NOTIFICATION_LIGHT_COLOR, color_def);
        builder.setLights(color, 1000, 2000);
    }
    builder.setDefaults(defaults);
    return builder.getNotification();
}

From source file:com.pacoapp.paco.triggering.NotificationCreator.java

private Notification createAndroidNotification(Context context, NotificationHolder notificationHolder,
        String experimentTitle, String message, String experimentSpecificRingtone, Integer color,
        Boolean dismissible) {/* w  w  w . j  a va2  s  . c  o m*/
    int icon = R.drawable.paco32;

    String tickerText = context.getString(R.string.time_for_notification_title) + experimentTitle;
    if (notificationHolder.isCustomNotification()) {
        tickerText = message;
    }

    Intent surveyIntent = new Intent(context, ExperimentExecutor.class);
    surveyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    surveyIntent.putExtra(NOTIFICATION_ID, notificationHolder.getId().longValue());

    PendingIntent notificationIntent = PendingIntent.getActivity(context, notificationHolder.getId().intValue(),
            surveyIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    // Adding bigText style to notification enabling larger messages to be read
    // in the notification pane
    NotificationCompat.BigTextStyle bigStyle = new NotificationCompat.BigTextStyle();
    bigStyle.setBigContentTitle(experimentTitle);
    bigStyle.bigText(message);

    // Make sure we have a color, or use the default
    if (color == null) {
        color = PacoNotificationAction.DEFAULT_COLOR;
    }

    //Make sure we know whether the notification is dismissible/not, or use default
    if (dismissible == null) {
        dismissible = PacoNotificationAction.DEFAULT_DISMISSIBLE;
    }

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context).setSmallIcon(icon)
            .setContentTitle(experimentTitle).setTicker(tickerText).setContentText(message)
            .setWhen(notificationHolder.getAlarmTime()).setContentIntent(notificationIntent)
            .setOngoing(!dismissible) //whether it's dismissible
            .setAutoCancel(dismissible) //whether it should disappear on user click
            .setLights(color, PacoNotificationAction.DEFAULT_NOTIFICATION_DELAY,
                    PacoNotificationAction.DEFAULT_NOTIFICATION_DELAY)
            .setStyle(bigStyle);

    int defaults = Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS;
    defaults = getRingtone(context, notificationBuilder, defaults, experimentSpecificRingtone);
    notificationBuilder.setDefaults(defaults);
    return notificationBuilder.build();
}

From source file:com.hhunj.hhudata.ForegroundService.java

protected void showNotification(CharSequence from, CharSequence message) {
    // look up the notification manager service
    NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    // The PendingIntent to launch our activity if the user selects this
    // notification

    //,//from ww w. j a v  a  2 s .com
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, IncomingMessageView.class), 0);

    // The ticker text, this uses a formatted string so our message could be
    // localized
    String tickerText = getString(R.string.imcoming_message_ticker_text, message);

    // construct the Notification object.
    Notification notif = new Notification(R.drawable.stat_sample, tickerText, System.currentTimeMillis());

    // Set the info for the views that show in the notification panel.
    notif.setLatestEventInfo(this, from, message, contentIntent);

    //   

    //
    Date dt = new Date();
    if (IsDuringWorkHours(dt)) {
        notif.defaults |= (Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);
    } else {
        notif.defaults |= (Notification.DEFAULT_VIBRATE);
    }

    // after a 100ms delay, vibrate for 250ms, pause for 100 ms and
    // then vibrate for 500ms.//
    notif.vibrate = new long[] { 100, 250, 100, 500 };

    nm.notify(R.string.imcoming_message_ticker_text, notif);
}

From source file:com.bonsai.btcreceive.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, MainActivity.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(MainActivity.class);
    // Adds the Intent that starts the Activity to the top of the stack
    stackBuilder.addNextIntent(intent);/* w w  w .  ja  v  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.jjcamera.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;
    LOGD(TAG, "Considering notifying for time interval.");
    LOGD(TAG, "    Interval start: " + sessionStart + "=" + (new Date(sessionStart)).toString());
    LOGD(TAG, "    Interval end: " + intervalEnd + "=" + (new Date(intervalEnd)).toString());
    LOGD(TAG, "    Current time is: " + currentTime + "=" + (new Date(currentTime)).toString());
    if (sessionStart < currentTime) {
        LOGD(TAG, "Skipping session notification (too late -- time interval already started)");
        return;/*from  w  w  w .jav a2  s.co  m*/
    }

    if (!SettingsUtils.shouldShowSessionReminders(this)) {
        // skip if disabled in settings
        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))) {
        LOGD(TAG, "Skipping session notification (already notified)");
        return;
    }

    final ContentResolver cr = getContentResolver();

    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();
        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));
            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);
        LOGD(TAG, "Now showing notification.");
        nm.notify(NOTIFICATION_ID, richNotification.build());
    } finally {
        if (c != null) {
            try {
                c.close();
            } catch (Exception ignored) {
            }
        }
    }
}