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:ua.org.gdg.devfest.iosched.service.SessionAlarmService.java

private void notifySession(final long sessionStart, final long sessionEnd, final long alarmOffset) {
    long currentTime;
    if (sessionStart < (currentTime = UIUtils.getCurrentTime(this)))
        return;//from ww  w.  j  a va  2  s.c om

    // Avoid repeated notifications.
    if (alarmOffset == UNDEFINED_ALARM_OFFSET && UIUtils.isNotificationFiredForBlock(this,
            ScheduleContract.Blocks.generateBlockId(sessionStart, sessionEnd))) {
        return;
    }

    final ContentResolver cr = getContentResolver();
    final Uri starredBlockUri = ScheduleContract.Blocks
            .buildStarredSessionsUri(ScheduleContract.Blocks.generateBlockId(sessionStart, sessionEnd));
    Cursor c = cr.query(starredBlockUri, SessionDetailQuery.PROJECTION, null, null, null);
    int starredCount = 0;
    ArrayList<String> starredSessionTitles = new ArrayList<String>();
    ArrayList<String> starredSessionRoomIds = new ArrayList<String>();
    String sessionId = null; // needed to get session track icon
    while (c.moveToNext()) {
        sessionId = c.getString(SessionDetailQuery.SESSION_ID);
        starredCount = c.getInt(SessionDetailQuery.NUM_STARRED_SESSIONS);
        starredSessionTitles.add(c.getString(SessionDetailQuery.SESSION_TITLE));
        starredSessionRoomIds.add(c.getString(SessionDetailQuery.ROOM_ID));
    }
    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.
    PendingIntent pi = TaskStackBuilder.create(this).addNextIntent(new Intent(this, HomeActivity.class))
            .addNextIntent(new Intent(Intent.ACTION_VIEW, starredBlockUri))
            .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)
            .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_droidconuk).setContentIntent(pi)
            .setPriority(Notification.PRIORITY_MAX).setAutoCancel(true);
    if (starredCount == 1) {
        // get the track icon to show as the notification big picture
        Uri tracksUri = ScheduleContract.Sessions.buildTracksDirUri(sessionId);
        Cursor tracksCursor = cr.query(tracksUri, SessionTrackQuery.PROJECTION, null, null, null);
        if (tracksCursor.moveToFirst()) {
            String trackName = tracksCursor.getString(SessionTrackQuery.TRACK_NAME);
            int trackColour = tracksCursor.getInt(SessionTrackQuery.TRACK_COLOR);
            Bitmap trackIcon = UIUtils.getTrackIconSync(getApplicationContext(), trackName, trackColour);
            if (trackIcon != null) {
                notifBuilder.setLargeIcon(trackIcon);
            }
        }
    }
    if (minutesLeft > 5) {
        notifBuilder.addAction(R.drawable.ic_alarm_holo_dark,
                String.format(res.getString(R.string.snooze_x_min), 5),
                createSnoozeIntent(sessionStart, sessionEnd, 5));
    }
    NotificationCompat.InboxStyle richNotification = new NotificationCompat.InboxStyle(notifBuilder)
            .setBigContentTitle(res.getQuantityString(R.plurals.session_notification_title, starredCount,
                    minutesLeft, starredCount));

    // 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);
    nm.notify(NOTIFICATION_ID, richNotification.build());
}

From source file:org.floens.chan.ui.service.WatchNotifier.java

/**
 * Create a notification with the supplied parameters.
 * The style of the big notification is InboxStyle, a list of text.
 *
 * @param tickerText    The tickertext to show, or null if no tickertext should be shown.
 * @param contentTitle  The title of the notification
 * @param contentText   The content of the small notification
 * @param contentNumber The contentInfo and number, or -1 if not shown
 * @param expandedLines A list of lines for the big notification, or null if not shown
 * @param makeSound     Should the notification make a sound
 * @param target        The target pin, or null to open the pinned pane on tap
 * @return/*from w ww .j a  v a 2s  .  c o m*/
 */
@SuppressWarnings("deprecation")
private Notification getNotificationFor(String tickerText, String contentTitle, String contentText,
        int contentNumber, List<CharSequence> expandedLines, boolean light, boolean makeSound, Pin target) {
    Intent intent = new Intent(this, ChanActivity.class);
    intent.setAction(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_LAUNCHER);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP
            | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);

    intent.putExtra("pin_id", target == null ? -1 : target.id);

    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    if (makeSound) {
        builder.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);
    }

    if (light) {
        long watchLed = ChanPreferences.getWatchLed();
        if (watchLed >= 0) {
            builder.setLights((int) watchLed, 1000, 1000);
        }
    }

    builder.setContentIntent(pendingIntent);

    if (tickerText != null) {
        tickerText = tickerText.substring(0, Math.min(tickerText.length(), 50));
    }

    builder.setTicker(tickerText);
    builder.setContentTitle(contentTitle);
    builder.setContentText(contentText);

    if (contentNumber >= 0) {
        builder.setContentInfo(Integer.toString(contentNumber));
        builder.setNumber(contentNumber);
    }

    builder.setSmallIcon(R.drawable.ic_stat_notify);

    Intent pauseWatching = new Intent(this, WatchNotifier.class);
    pauseWatching.putExtra("pause_pins", true);

    PendingIntent pauseWatchingPending = PendingIntent.getService(this, 0, pauseWatching,
            PendingIntent.FLAG_UPDATE_CURRENT);

    builder.addAction(R.drawable.ic_action_pause, getString(R.string.watch_pause_pins), pauseWatchingPending);

    if (expandedLines != null) {
        NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
        for (CharSequence line : expandedLines.subList(Math.max(0, expandedLines.size() - 10),
                expandedLines.size())) {
            style.addLine(line);
        }
        style.setBigContentTitle(contentTitle);
        builder.setStyle(style);
    }

    return builder.getNotification();
}

From source file:com.google.android.apps.iosched.calendar.SessionAlarmService.java

/**
 * Constructs and triggers system notification for when starred sessions are about to begin.
 *///w w  w .  ja  v a 2  s .c  o m
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void notifySession(final long sessionStart, final long sessionEnd, final long alarmOffset) {
    long currentTime = System.currentTimeMillis();
    if (sessionStart < currentTime) {
        return;
    }

    // Avoid repeated notifications.
    if (alarmOffset == UNDEFINED_ALARM_OFFSET && UIUtils.isNotificationFiredForBlock(this,
            ScheduleContract.Blocks.generateBlockId(sessionStart, sessionEnd))) {
        return;
    }

    final ContentResolver resolver = getContentResolver();
    final Uri starredBlockUri = ScheduleContract.Blocks
            .buildStarredSessionsUri(ScheduleContract.Blocks.generateBlockId(sessionStart, sessionEnd));
    Cursor cursor = resolver.query(starredBlockUri, new String[] { ScheduleContract.Blocks.NUM_STARRED_SESSIONS,
            ScheduleContract.Sessions.SESSION_TITLE }, null, null, null);
    int starredCount = 0;
    ArrayList<String> starredSessionTitles = new ArrayList<String>();
    while (cursor.moveToNext()) {
        starredSessionTitles.add(cursor.getString(1));
        starredCount = cursor.getInt(0);
    }

    if (starredCount < 1) {
        return;
    }

    // Generates the pending intent which gets fired when the user touches on the notification.
    Intent sessionIntent = new Intent(Intent.ACTION_VIEW, starredBlockUri);
    sessionIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pi = PendingIntent.getActivity(this, 0, sessionIntent, 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);
    }

    // Construct a notification. Use Jelly Bean (API 16) rich notifications if possible.
    Notification notification;
    if (UIUtils.hasJellyBean()) {
        // Rich notifications
        Notification.Builder builder = new Notification.Builder(this)
                .setContentTitle(starredSessionTitles.get(0)).setContentText(contentText)
                .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) {
            builder.addAction(R.drawable.ic_alarm_holo_dark,
                    String.format(res.getString(R.string.snooze_x_min), 5),
                    createSnoozeIntent(sessionStart, sessionEnd, 5));
        }
        Notification.InboxStyle richNotification = new Notification.InboxStyle(builder)
                .setBigContentTitle(res.getQuantityString(R.plurals.session_notification_title, starredCount,
                        minutesLeft, starredCount));

        // Adds starred sessions starting at this time block to the notification.
        for (int i = 0; i < starredCount; i++) {
            richNotification.addLine(starredSessionTitles.get(i));
        }
        notification = richNotification.build();

    } else {
        // Pre-Jelly Bean non-rich notifications
        notification = new NotificationCompat.Builder(this).setContentTitle(starredSessionTitles.get(0))
                .setContentText(contentText)
                .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).getNotification();
    }
    NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    nm.notify(NOTIFICATION_ID, notification);
}

From source file:com.partypoker.poker.engagement.reach.EngagementDefaultNotifier.java

@Override
public Boolean handleNotification(EngagementReachInteractiveContent content) throws RuntimeException {
    /* System notification case */
    if (content.isSystemNotification()) {
        /* Big picture handling */
        Bitmap bigPicture = null;/*from   w w w. j ava  2s  .  c  o  m*/
        String bigPictureURL = content.getNotificationBigPicture();
        if (bigPictureURL != null && Build.VERSION.SDK_INT >= 16) {
            /* Schedule picture download if needed, or load picture if download completed. */
            Long downloadId = content.getDownloadId();
            if (downloadId == null) {
                EngagementNotificationUtilsV11.downloadBigPicture(mContext, content);
                return null;
            } else
                bigPicture = EngagementNotificationUtilsV11.getBigPicture(mContext, downloadId);
        }

        /* Generate notification identifier */
        int notificationId = getNotificationId(content);

        /* Build notification using support lib to manage compatibility with old Android versions */
        NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext);

        /* Icon for ticker and content icon */
        builder.setSmallIcon(mNotificationIcon);

        /*
         * Large icon, handled only since API Level 11 (needs down scaling if too large because it's
         * cropped otherwise by the system).
         */
        Bitmap notificationImage = content.getNotificationImage();
        if (notificationImage != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
            builder.setLargeIcon(scaleBitmapForLargeIcon(mContext, notificationImage));

        /* Texts */
        String notificationTitle = content.getNotificationTitle();
        String notificationMessage = content.getNotificationMessage();
        String notificationBigText = content.getNotificationBigText();
        builder.setContentTitle(notificationTitle);
        builder.setContentText(notificationMessage);

        /*
         * Replay: display original date and don't replay all the tickers (be as quiet as possible
         * when replaying).
         */
        Long notificationFirstDisplayedDate = content.getNotificationFirstDisplayedDate();
        if (notificationFirstDisplayedDate != null)
            builder.setWhen(notificationFirstDisplayedDate);
        else
            builder.setTicker(notificationTitle);

        /* Big picture */
        if (bigPicture != null)
            builder.setStyle(new BigPictureStyle().bigPicture(bigPicture).setBigContentTitle(notificationTitle)
                    .setSummaryText(notificationMessage));

        /* Big text */
        else if (notificationBigText != null)
            builder.setStyle(new BigTextStyle().bigText(notificationBigText));

        /* Vibration/sound if not a replay */
        if (notificationFirstDisplayedDate == null) {
            int defaults = 0;
            if (content.isNotificationSound())
                defaults |= Notification.DEFAULT_SOUND;
            if (content.isNotificationVibrate())
                defaults |= Notification.DEFAULT_VIBRATE;
            builder.setDefaults(defaults);
        }

        /* Launch the receiver on action */
        Intent actionIntent = new Intent(INTENT_ACTION_ACTION_NOTIFICATION);
        com.microsoft.azure.engagement.reach.EngagementReachAgent.setContentIdExtra(actionIntent, content);
        actionIntent.putExtra(INTENT_EXTRA_NOTIFICATION_ID, notificationId);
        Intent intent = content.getIntent();
        if (intent != null)
            actionIntent.putExtra(INTENT_EXTRA_COMPONENT, intent.getComponent());
        actionIntent.setPackage(mContext.getPackageName());
        PendingIntent contentIntent = PendingIntent.getBroadcast(mContext, (int) content.getLocalId(),
                actionIntent, FLAG_CANCEL_CURRENT);
        builder.setContentIntent(contentIntent);

        /* Also launch receiver if the notification is exited (clear button) */
        Intent exitIntent = new Intent(INTENT_ACTION_EXIT_NOTIFICATION);
        exitIntent.putExtra(INTENT_EXTRA_NOTIFICATION_ID, notificationId);
        EngagementReachAgent.setContentIdExtra(exitIntent, content);
        exitIntent.setPackage(mContext.getPackageName());
        PendingIntent deleteIntent = PendingIntent.getBroadcast(mContext, (int) content.getLocalId(),
                exitIntent, FLAG_CANCEL_CURRENT);
        builder.setDeleteIntent(deleteIntent);

        /* Can be dismissed ? */
        Notification notification = builder.build();
        if (!content.isNotificationCloseable())
            notification.flags |= Notification.FLAG_NO_CLEAR;

        /* Allow overriding */
        if (onNotificationPrepared(notification, content))

            /*
             * Submit notification, replacing the previous one if any (this should happen only if the
             * application process is restarted).
             */
            mNotificationManager.notify(notificationId, notification);
    }

    /* Activity embedded notification case */
    else {
        /* Get activity */
        Activity activity = EngagementActivityManager.getInstance().getCurrentActivity().get();

        /* Cannot notify in app if no activity provided */
        if (activity == null)
            return false;

        /* Get notification area */
        String category = content.getCategory();
        int areaId = getInAppAreaId(category);
        View notificationAreaView = activity.findViewById(areaId);

        /* No notification area, check if we can install overlay */
        if (notificationAreaView == null) {
            /* Check overlay is not disabled in this activity */
            Bundle activityConfig = EngagementUtils.getActivityMetaData(activity);
            if (!activityConfig.getBoolean(METADATA_NOTIFICATION_OVERLAY, true))
                return false;

            /* Inflate overlay layout and get reference to notification area */
            View overlay = LayoutInflater.from(mContext).inflate(getOverlayLayoutId(category), null);
            activity.addContentView(overlay, new LayoutParams(MATCH_PARENT, MATCH_PARENT));
            notificationAreaView = activity.findViewById(areaId);
        }

        /* Otherwise check if there is an overlay containing the area to restore visibility */
        else {
            View overlay = activity.findViewById(getOverlayViewId(category));
            if (overlay != null)
                overlay.setVisibility(View.VISIBLE);
        }

        /* Make the notification area visible */
        notificationAreaView.setVisibility(View.VISIBLE);

        /* Prepare area */
        prepareInAppArea(content, notificationAreaView);
    }

    /* Success */
    return true;
}

From source file:fr.vassela.acrrd.notifier.TelephoneCallNotifier.java

public void displayCompatNotification(Context context, String ticker, String contentTitle, String contentText,
        boolean autoCancel, boolean ongoingEvent, boolean activateEvent) {
    try {/*from   ww  w  . ja v  a 2  s .co m*/
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        boolean isPreferencesNotificationsActivated = sharedPreferences
                .getBoolean("preferences_notifications_activate", false);
        boolean isPreferencesNotificationsSoundActivated = sharedPreferences
                .getBoolean("preferences_notifications_sound_activate", false);
        boolean isPreferencesNotificationsVibrateActivated = sharedPreferences
                .getBoolean("preferences_notifications_vibrate_activate", false);
        boolean isPreferencesNotificationsLedActivated = sharedPreferences
                .getBoolean("preferences_notifications_led_activate", false);

        if (isPreferencesNotificationsActivated == true) {
            long notificationWhen = System.currentTimeMillis();
            int notificationDefaults = 0;

            Intent intent;

            if (ongoingEvent == true) {
                intent = new Intent(context, Main.class);
                intent.putExtra("setCurrentTab", "home");
            } else {
                intent = new Intent(SHOW_RECORDS);
            }

            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

            NotificationManager notificationManager = (NotificationManager) context
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            NotificationCompat.Builder notificationCompatBuilder = new NotificationCompat.Builder(context);

            if (ongoingEvent == false) {
                notificationCompatBuilder.setWhen(notificationWhen);
            }

            if (isPreferencesNotificationsSoundActivated == true) {
                notificationDefaults = notificationDefaults | Notification.DEFAULT_SOUND;
            }

            if (isPreferencesNotificationsVibrateActivated == true) {
                notificationDefaults = notificationDefaults | Notification.DEFAULT_VIBRATE;
            }

            if (isPreferencesNotificationsLedActivated == true) {
                notificationDefaults = notificationDefaults | Notification.DEFAULT_LIGHTS;
            }

            if (ongoingEvent == false) {
                notificationCompatBuilder.setDefaults(notificationDefaults);
            }

            if (activateEvent == true) {
                notificationCompatBuilder.setSmallIcon(R.drawable.presence_audio_online);
            } else {
                notificationCompatBuilder.setSmallIcon(R.drawable.presence_audio_busy);
            }

            if (ongoingEvent == false) {
                notificationCompatBuilder.setTicker(ticker);
            }

            notificationCompatBuilder.setContentTitle(contentTitle);
            notificationCompatBuilder.setContentText(contentText);
            notificationCompatBuilder.setContentIntent(pendingIntent);
            notificationCompatBuilder.setAutoCancel(autoCancel);
            notificationCompatBuilder.setOngoing(ongoingEvent);

            Notification notification = notificationCompatBuilder.build();

            if (ongoingEvent == true) {
                notificationManager.notify(getOngoingNotificationId(), notification);
            } else {
                notificationManager.notify(getNotificationId(), notification);
            }
        }
    } catch (Exception e) {
        Log.w("TelephoneCallNotifier", "displayCompatNotification : " + context.getApplicationContext()
                .getString(R.string.log_telephone_call_notifier_error_display_notification) + " : " + e);
        databaseManager.insertLog(context.getApplicationContext(),
                "" + context.getApplicationContext()
                        .getString(R.string.log_telephone_call_notifier_error_display_notification),
                new Date().getTime(), 2, false);
    }
}

From source file:fr.neamar.notiflow.GcmIntentService.java

private void sendNotification(String flow, String msg, Bundle extras) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

    Boolean notifyOwnMessages = prefs.getBoolean("prefNotifyOwnMessages", false);
    Boolean isOwnMessage = extras.getString("own", "false").equals("true");

    String notifyType = prefs.getString("prefNotifyType", "all"); // all | mentions | private
    Boolean isMentioned = extras.getString("mentioned", "false").equals("true");
    Boolean isPrivate = extras.getString("private", "false").equals("true");

    Log.d(TAG, "New message, type " + notifyType + ", mentioned: " + isMentioned + ", private: " + isPrivate);

    if (isOwnMessage && !notifyOwnMessages) {
        Log.i(TAG, "Canceling notification (user sent): " + extras.toString());
        mNotificationManager.cancel(extras.getString("flow"), 0);
        NotificationHelper.cleanNotifications(getApplicationContext(), extras.getString("flow"));
        return;// w w w  .ja  v  a  2 s. co  m

    } else if (notifyType.equals("mentions") && !isMentioned && !isPrivate) {
        Log.i(TAG, "Skipping message (not mentioned): " + extras.toString());
        return;

    } else if (notifyType.equals("private") && !isPrivate) {
        Log.i(TAG, "Skipping message (not private): " + extras.toString());
        return;
    }

    Date lastNotification = NotificationHelper.getLastNotificationDate(getApplicationContext(), flow);
    NotificationHelper.addNotification(getApplicationContext(), flow, msg);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
    NotificationCompat.WearableExtender wearableExtender = new NotificationCompat.WearableExtender();

    Boolean silentMode = prefs.getBoolean("prefNotifySilent", false);

    if (!silentMode) {
        Date now = new Date();
        Long timeSinceLastNotification = now.getTime() - lastNotification.getTime();

        Integer frequency = Integer.parseInt(prefs.getString("prefNotifyVibrationFrequency", "15")) * 1000;
        Boolean notifyWhenActive = prefs.getBoolean("prefNotifyWhenActive", false);
        Boolean isActive = extras.getString("active", "false").equals("true");

        if (timeSinceLastNotification < frequency) {
            Log.i(TAG, "Skipping vibration -- cooldown in effect");

        } else if (isActive && !notifyWhenActive) {
            Log.i(TAG, "Skipping vibration -- user already active");

        } else {
            mBuilder.setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS);
        }
    }

    ArrayList<String> prevMessages = NotificationHelper.getNotifications(getApplicationContext(), flow);
    Integer pendingCount = prevMessages.size();

    if (pendingCount == 1) {
        // Only one notification : display using BigTextStyle for multiline.
        NotificationCompat.BigTextStyle style = new NotificationCompat.BigTextStyle()
                .bigText(Html.fromHtml(msg));

        mBuilder.setStyle(style);
    } else {
        // More than one notification: use inbox style, displaying up to 5 messages
        NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();

        for (int i = 0; i < Math.min(pendingCount, 5); i++) {
            style.addLine(Html.fromHtml(prevMessages.get(i)));
        }

        mBuilder.setStyle(style).setContentInfo(Integer.toString(pendingCount)).setNumber(pendingCount);

        NotificationCompat.BigTextStyle pageStyle = new NotificationCompat.BigTextStyle();
        StringBuilder pageText = new StringBuilder();

        // And then add a second page for Wearables, displaying the whole pending conversation
        for (int i = pendingCount - 1; i >= 0; i--) {
            if (i < pendingCount - 1) {
                pageText.append("<br /><br />");
            }
            pageText.append(prevMessages.get(i));
        }

        pageStyle.bigText(Html.fromHtml(pageText.toString()));

        Notification secondPage = new NotificationCompat.Builder(this).setStyle(pageStyle)
                .extend(new NotificationCompat.WearableExtender().setStartScrollBottom(true)).build();

        wearableExtender.addPage(secondPage);

    }

    // Set large icon, which gets used for wearable background as well
    String avatar = extras.getString("avatar", "");
    if (!avatar.equals("")) {

        String sizeExpr = "(/\\d+/?)$";
        Boolean isCloudFront = avatar.contains("cloudfront");
        Boolean hasSize = avatar.matches(".*" + sizeExpr);

        if (isCloudFront) {
            if (!hasSize) {
                avatar += "/400";
            } else {
                avatar.replaceFirst(sizeExpr, "/400");
            }
        }

        ImageLoader imageLoader = ImageLoader.getInstance();
        Bitmap image = imageLoader.loadImageSync(avatar);

        // scale for notification tray
        int height = (int) getResources().getDimension(android.R.dimen.notification_large_icon_height);
        int width = (int) getResources().getDimension(android.R.dimen.notification_large_icon_width);
        Bitmap scaledImage = Bitmap.createScaledBitmap(image, width, height, false);

        mBuilder.setLargeIcon(scaledImage);
        wearableExtender.setBackground(image);
    }

    // Increase priority only for mentions and 1-1 conversations
    if (isMentioned || isPrivate) {
        mBuilder.setPriority(NotificationCompat.PRIORITY_HIGH);
    }

    // Retrieve color
    // Default to 0x7BD3FB
    int color = Integer.parseInt(extras.getString("color", "8115195"));

    Notification notification = mBuilder.setSmallIcon(R.drawable.notification).setColor(color)
            .setContentTitle(flow).setContentText(Html.fromHtml(msg)).setAutoCancel(true)
            .setContentIntent(createClickedIntent(flow, extras)).setDeleteIntent(createDismissedIntent(flow))
            .setTicker(Html.fromHtml(msg)).setCategory(Notification.CATEGORY_SOCIAL).extend(wearableExtender)
            .build();

    mNotificationManager.notify(flow, 0, notification);
    Log.i(TAG, "Displaying message: " + extras.toString());
}

From source file:com.conferenceengineer.android.iosched.service.SessionAlarmService.java

private void notifySession(final long sessionStart, final long sessionEnd, final long alarmOffset) {
    long currentTime;
    if (sessionStart < (currentTime = UIUtils.getCurrentTime(this)))
        return;//  ww w .ja va  2s . c  o m

    // Avoid repeated notifications.
    if (alarmOffset == UNDEFINED_ALARM_OFFSET && UIUtils.isNotificationFiredForBlock(this,
            ScheduleContract.Blocks.generateBlockId(sessionStart, sessionEnd))) {
        return;
    }

    final ContentResolver cr = getContentResolver();
    final Uri starredBlockUri = ScheduleContract.Blocks
            .buildStarredSessionsUri(ScheduleContract.Blocks.generateBlockId(sessionStart, sessionEnd));
    Cursor c = cr.query(starredBlockUri, SessionDetailQuery.PROJECTION, null, null, null);
    int starredCount = 0;
    ArrayList<String> starredSessionTitles = new ArrayList<String>();
    ArrayList<String> starredSessionRoomIds = new ArrayList<String>();
    String sessionId = null; // needed to get session track icon
    while (c.moveToNext()) {
        sessionId = c.getString(SessionDetailQuery.SESSION_ID);
        starredCount = c.getInt(SessionDetailQuery.NUM_STARRED_SESSIONS);
        starredSessionTitles.add(c.getString(SessionDetailQuery.SESSION_TITLE));
        starredSessionRoomIds.add(c.getString(SessionDetailQuery.ROOM_ID));
    }
    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.
    PendingIntent pi = TaskStackBuilder.create(this).addNextIntent(new Intent(this, HomeActivity.class))
            .addNextIntent(new Intent(Intent.ACTION_VIEW, starredBlockUri))
            .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)
            .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.conference_ic_notification).setContentIntent(pi)
            .setPriority(Notification.PRIORITY_MAX).setAutoCancel(true);
    if (starredCount == 1) {
        // get the track icon to show as the notification big picture
        Uri tracksUri = ScheduleContract.Sessions.buildTracksDirUri(sessionId);
        Cursor tracksCursor = cr.query(tracksUri, SessionTrackQuery.PROJECTION, null, null, null);
        if (tracksCursor.moveToFirst()) {
            String trackName = tracksCursor.getString(SessionTrackQuery.TRACK_NAME);
            int trackColour = tracksCursor.getInt(SessionTrackQuery.TRACK_COLOR);
            Bitmap trackIcon = UIUtils.getTrackIconSync(getApplicationContext(), trackName, trackColour);
            if (trackIcon != null) {
                notifBuilder.setLargeIcon(trackIcon);
            }
        }
    }
    if (minutesLeft > 5) {
        notifBuilder.addAction(R.drawable.ic_alarm_holo_dark,
                String.format(res.getString(R.string.snooze_x_min), 5),
                createSnoozeIntent(sessionStart, sessionEnd, 5));
    }
    NotificationCompat.InboxStyle richNotification = new NotificationCompat.InboxStyle(notifBuilder)
            .setBigContentTitle(res.getQuantityString(R.plurals.session_notification_title, starredCount,
                    minutesLeft, starredCount));

    // 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);
    nm.notify(NOTIFICATION_ID, richNotification.build());
}

From source file:com.snappy.GCMIntentService.java

/**
 * Issues a notification to inform the user that server has sent a message.
 *///from  ww  w . ja  v a2  s.  c o  m
private void generateNotification(Context context, String message, String fromName, Bundle pushExtras,
        String body) {

    db = new LocalDB(context);
    List<LocalMessage> myMessages = db.getAllMessages();

    // Open a new activity called GCMMessageView
    Intent intento = new Intent(this, SplashScreenActivity.class);
    intento.replaceExtras(pushExtras);
    // Pass data to the new activity
    intento.putExtra(Const.PUSH_INTENT, true);
    intento.setAction(Long.toString(System.currentTimeMillis()));
    intento.addFlags(
            Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_FROM_BACKGROUND | Intent.FLAG_ACTIVITY_TASK_ON_HOME);

    // Starts the activity on notification click
    PendingIntent pIntent = PendingIntent.getActivity(this, 0, intento, PendingIntent.FLAG_UPDATE_CURRENT);

    // Create the notification with a notification builder
    NotificationCompat.Builder notification = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.icon_notification).setWhen(System.currentTimeMillis())
            .setContentTitle(myMessages.size() + " " + this.getString(R.string.push_new_message_message))
            .setStyle(new NotificationCompat.BigTextStyle().bigText("Mas mensajes")).setAutoCancel(true)
            .setDefaults(
                    Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND | Notification.DEFAULT_LIGHTS)
            .setContentText(body).setContentIntent(pIntent);

    NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
    inboxStyle.setBigContentTitle(myMessages.size() + " " + this.getString(R.string.push_new_message_message));

    for (int i = 0; i < myMessages.size(); i++) {

        inboxStyle.addLine(myMessages.get(i).getMessage());
    }

    notification.setStyle(inboxStyle);

    // Remove the notification on click
    //notification.flags |= Notification.FLAG_AUTO_CANCEL;
    //notification.defaults |= Notification.DEFAULT_VIBRATE;
    //notification.defaults |= Notification.DEFAULT_SOUND;
    //notification.defaults |= Notification.DEFAULT_LIGHTS;

    NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    manager.notify(R.string.app_name, notification.build());
    {
        // Wake Android Device when notification received
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);

        final PowerManager.WakeLock mWakelock = pm
                .newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "GCM_PUSH");
        mWakelock.acquire();
        // Timer before putting Android Device to sleep mode.
        Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            public void run() {
                mWakelock.release();
            }
        };
        timer.schedule(task, 5000);
    }
}

From source file:com.onesignal.GenerateNotification.java

private static NotificationCompat.Builder getBaseNotificationCompatBuilder(JSONObject gcmBundle,
        boolean notify) {
    int notificationIcon = getSmallIconId(gcmBundle);

    int notificationDefaults = 0;

    if (OneSignal.getVibrate(currentContext))
        notificationDefaults = Notification.DEFAULT_VIBRATE;

    String message = null;/*ww  w.j ava2 s .  c o m*/
    try {
        message = gcmBundle.getString("alert");
    } catch (Throwable t) {
    }

    NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(currentContext).setAutoCancel(true)
            .setSmallIcon(notificationIcon) // Small Icon required or notification doesn't display
            .setContentTitle(getTitle(gcmBundle))
            .setStyle(new NotificationCompat.BigTextStyle().bigText(message)).setContentText(message);
    if (notify)
        notifBuilder.setTicker(message);

    // Android 5.0 accent color to use, only works when AndroidManifest.xml is
    // targetSdkVersion >= 21
    if (gcmBundle.has("bgac")) {
        try {
            notifBuilder.setColor(new BigInteger(gcmBundle.getString("bgac"), 16).intValue());
        } catch (Throwable t) {
        } // Can throw if an old android support lib is used or parse error.
    }

    BigInteger ledColor = null;

    if (notify && gcmBundle.has("ledc")) {
        try {
            ledColor = new BigInteger(gcmBundle.getString("ledc"), 16);
            notifBuilder.setLights(ledColor.intValue(), 2000, 5000);
        } catch (Throwable t) {
            notificationDefaults |= Notification.DEFAULT_LIGHTS;
        } // Can throw if an old android support lib is used or parse error.
    } else
        notificationDefaults |= Notification.DEFAULT_LIGHTS;

    try {
        int visibility = Notification.VISIBILITY_PUBLIC;
        if (gcmBundle.has("vis"))
            visibility = Integer.parseInt(gcmBundle.getString("vis"));
        notifBuilder.setVisibility(visibility);
    } catch (Throwable t) {
    } // Can throw if an old android support lib is used or parse error

    Bitmap largeIcon = getLargeIcon(gcmBundle);
    if (largeIcon != null)
        notifBuilder.setLargeIcon(largeIcon);

    Bitmap bigPictureIcon = getBitmapIcon(gcmBundle, "bicon");
    if (bigPictureIcon != null)
        notifBuilder.setStyle(
                new NotificationCompat.BigPictureStyle().bigPicture(bigPictureIcon).setSummaryText(message));

    if (notify && OneSignal.getSoundEnabled(currentContext)) {
        Uri soundUri = getCustomSound(gcmBundle);
        if (soundUri != null)
            notifBuilder.setSound(soundUri);
        else
            notificationDefaults |= Notification.DEFAULT_SOUND;
    }

    if (!notify)
        notificationDefaults = 0;

    notifBuilder.setDefaults(notificationDefaults);

    return notifBuilder;
}

From source file:it.gulch.linuxday.android.services.AlarmIntentService.java

private void notifyEvent(Intent intent) {
    long eventId = Long.parseLong(intent.getDataString());
    Event event = eventManager.get(eventId);
    if (event == null) {
        return;/*from  w  w w .j  a  v  a 2 s . c o m*/
    }

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

    //      PendingIntent eventPendingIntent =
    //            TaskStackBuilder.create(this).addNextIntent(new Intent(this,
    // MainActivity.class)).addNextIntent(
    //                  new Intent(this, EventDetailsActivity.class).setData(Uri.parse(String.valueOf(event
    // .getId()))))
    //                  .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    PendingIntent eventPendingIntent = TaskStackBuilder.create(this)
            .addNextIntent(new Intent(this, MainActivity.class))
            .addNextIntent(new Intent(this, EventDetailsActivity.class)
                    .setData(Uri.parse(String.valueOf(event.getId()))))
            .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    int defaultFlags = Notification.DEFAULT_SOUND;
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    if (sharedPreferences.getBoolean(SettingsFragment.KEY_PREF_NOTIFICATIONS_VIBRATE, false)) {
        defaultFlags |= Notification.DEFAULT_VIBRATE;
    }

    String trackName = event.getTrack().getTitle();
    CharSequence bigText;
    String contentText;
    if (CollectionUtils.isEmpty(event.getPeople())) {
        contentText = trackName;
        bigText = event.getSubtitle();
    } else {
        String personsSummary = StringUtils.join(event.getPeople(), ", ");
        contentText = String.format("%1$s - %2$s", trackName, personsSummary);
        String subTitle = event.getSubtitle();

        SpannableString spannableBigText;
        if (TextUtils.isEmpty(subTitle)) {
            spannableBigText = new SpannableString(personsSummary);
        } else {
            spannableBigText = new SpannableString(String.format("%1$s\n%2$s", subTitle, personsSummary));
        }

        // Set the persons summary in italic
        spannableBigText.setSpan(new StyleSpan(Typeface.ITALIC),
                +spannableBigText.length() - personsSummary.length(), spannableBigText.length(),
                +Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        bigText = spannableBigText;
    }

    String roomName = event.getTrack().getRoom().getName();
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher).setWhen(event.getStartDate().getTime())
            .setContentTitle(event.getTitle()).setContentText(contentText)
            .setStyle(new NotificationCompat.BigTextStyle().bigText(bigText).setSummaryText(trackName))
            .setContentInfo(roomName).setContentIntent(eventPendingIntent).setAutoCancel(true)
            .setDefaults(defaultFlags).setPriority(NotificationCompat.PRIORITY_HIGH);

    // Blink the LED with FOSDEM color if enabled in the options
    if (sharedPreferences.getBoolean(SettingsFragment.KEY_PREF_NOTIFICATIONS_LED, false)) {
        notificationBuilder.setLights(getResources().getColor(R.color.maincolor), 1000, 5000);
    }

    /*// Android Wear extensions
    NotificationCompat.WearableExtender wearableExtender = new NotificationCompat.WearableExtender();
            
    // Add an optional action button to show the room map image
    int roomImageResId = getResources()
    .getIdentifier(StringUtils.roomNameToResourceName(roomName), "drawable", getPackageName());
    if(roomImageResId != 0) {
       // The room name is the unique Id of a RoomImageDialogActivity
       Intent mapIntent = new Intent(this, RoomImageDialogActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
       .setData(Uri.parse(roomName));
       mapIntent.putExtra(RoomImageDialogActivity.EXTRA_ROOM_NAME, roomName);
       mapIntent.putExtra(RoomImageDialogActivity.EXTRA_ROOM_IMAGE_RESOURCE_ID, roomImageResId);
       PendingIntent mapPendingIntent =
       PendingIntent.getActivity(this, 0, mapIntent, PendingIntent.FLAG_UPDATE_CURRENT);
       CharSequence mapTitle = getString(R.string.room_map);
       notificationBuilder
       .addAction(new NotificationCompat.Action(R.drawable.ic_action_place, mapTitle, mapPendingIntent));
       // Use bigger action icon for wearable notification
       wearableExtender.addAction(
       new NotificationCompat.Action(R.drawable.ic_place_white_wear, mapTitle, mapPendingIntent));
    }
            
    notificationBuilder.extend(wearableExtender);*/

    NotificationManagerCompat.from(this).notify((int) eventId, notificationBuilder.build());
}