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:br.com.arlsoft.pushclient.PushClientModule.java

public static void sendNotification(Bundle extras) {
    if (extras == null || extras.isEmpty())
        return;// w  w  w  .  jav  a 2 s .c om

    TiApplication appContext = TiApplication.getInstance();
    int appIconId = appContext.getResources().getIdentifier("appicon", "drawable", appContext.getPackageName());
    String appName = appContext.getAppInfo().getName();

    Bundle extrasRoot = extras;

    int badgeCount = -1;
    int notificationId = 0;
    String notificationTitle = null;
    String notificationText = null;
    String notificationTicker = null;
    Uri notificationSound = null;
    int notificationDefaults = 0;

    // TEXT
    if (extras.containsKey("text")) {
        notificationText = extras.getString("text");
    } else if (extras.containsKey("alert")) {
        notificationText = extras.getString("alert");
    } else if (extras.containsKey("message")) {
        notificationText = extras.getString("message");
    } else if (extras.containsKey("data")) {
        try {
            JSONObject reader = new JSONObject(extras.getString("data"));
            Bundle newExtras = new Bundle();
            for (int i = 0; i < reader.names().length(); i++) {
                String key = reader.names().getString(i);
                newExtras.putString(key, reader.getString(key));
            }
            if (newExtras.containsKey("text")) {
                notificationText = newExtras.getString("text");
                extras = newExtras;
            } else if (newExtras.containsKey("alert")) {
                notificationText = newExtras.getString("alert");
                extras = newExtras;
            } else if (newExtras.containsKey("message")) {
                notificationText = newExtras.getString("message");
                extras = newExtras;
            }
        } catch (JSONException e) {
            String text = extras.getString("data");
            if (text != null) {
                notificationText = text;
            }
        }
    } else if (extras.containsKey("msg")) {
        try {
            JSONObject reader = new JSONObject(extras.getString("msg"));
            Bundle newExtras = new Bundle();
            for (int i = 0; i < reader.names().length(); i++) {
                String key = reader.names().getString(i);
                newExtras.putString(key, reader.getString(key));
            }
            if (newExtras.containsKey("text")) {
                notificationText = newExtras.getString("text");
                extras = newExtras;
            } else if (newExtras.containsKey("alert")) {
                notificationText = newExtras.getString("alert");
                extras = newExtras;
            } else if (newExtras.containsKey("message")) {
                notificationText = newExtras.getString("message");
                extras = newExtras;
            }
        } catch (JSONException e) {
            String text = extras.getString("msg");
            if (text != null) {
                notificationText = text;
            }
        }
    } else if (extras.containsKey("default")) {
        try {
            JSONObject reader = new JSONObject(extras.getString("default"));
            Bundle newExtras = new Bundle();
            for (int i = 0; i < reader.names().length(); i++) {
                String key = reader.names().getString(i);
                newExtras.putString(key, reader.getString(key));
            }
            if (newExtras.containsKey("text")) {
                notificationText = newExtras.getString("text");
                extras = newExtras;
            } else if (newExtras.containsKey("alert")) {
                notificationText = newExtras.getString("alert");
                extras = newExtras;
            } else if (newExtras.containsKey("message")) {
                notificationText = newExtras.getString("message");
                extras = newExtras;
            }
        } catch (JSONException e) {
            String text = extras.getString("default");
            if (text != null) {
                notificationText = text;
            }
        }
    } else if (extras.containsKey("payload")) {
        try {
            JSONObject reader = new JSONObject(extras.getString("payload"));
            Bundle newExtras = new Bundle();
            for (int i = 0; i < reader.names().length(); i++) {
                String key = reader.names().getString(i);
                newExtras.putString(key, reader.getString(key));
            }
            if (newExtras.containsKey("text")) {
                notificationText = newExtras.getString("text");
                extras = newExtras;
            } else if (newExtras.containsKey("alert")) {
                notificationText = newExtras.getString("alert");
                extras = newExtras;
            } else if (newExtras.containsKey("message")) {
                notificationText = newExtras.getString("message");
                extras = newExtras;
            }
        } catch (JSONException e) {
            String text = extras.getString("payload");
            if (text != null) {
                notificationText = text;
            }
        }
    }

    // TITLE
    if (extras.containsKey("title")) {
        notificationTitle = extras.getString("title");
    } else {
        notificationTitle = appName;
    }

    // TICKER
    if (extras.containsKey("ticker")) {
        notificationTicker = extras.getString("ticker");
    } else {
        notificationTicker = notificationText;
    }

    // SOUND
    if (extras.containsKey("sound")) {
        if (extras.getString("sound").equalsIgnoreCase("default")) {
            notificationDefaults |= Notification.DEFAULT_SOUND;
        } else {
            File file = null;
            // getResourcesDirectory
            file = new File("app://" + extras.getString("sound"));
            if (file != null && file.exists()) {
                notificationSound = Uri.fromFile(file);
            } else {
                // getResourcesDirectory + sound folder
                file = new File("app://sound/" + extras.getString("sound"));
                if (file != null && file.exists()) {
                    notificationSound = Uri.fromFile(file);
                } else {
                    // getExternalStorageDirectory
                    file = new File("appdata://" + extras.getString("sound"));
                    if (file != null && file.exists()) {
                        notificationSound = Uri.fromFile(file);
                    } else {
                        // getExternalStorageDirectory + sound folder
                        file = new File("appdata://sound/" + extras.getString("sound"));
                        if (file != null && file.exists()) {
                            notificationSound = Uri.fromFile(file);
                        } else {
                            // res folder
                            int soundId = appContext.getResources().getIdentifier(extras.getString("sound"),
                                    "raw", appContext.getPackageName());
                            if (soundId != 0) {
                                notificationSound = Uri.parse("android.resource://"
                                        + appContext.getPackageName() + "/raw/" + soundId);
                            } else {
                                // res folder without file extension
                                String soundFile = extras.getString("sound").split("\\.")[0];
                                soundId = appContext.getResources().getIdentifier(soundFile, "raw",
                                        appContext.getPackageName());
                                if (soundId != 0) {
                                    notificationSound = Uri.parse("android.resource://"
                                            + appContext.getPackageName() + "/raw/" + soundId);
                                }
                            }
                        }
                    }
                }
            }
        }
    } else if (extrasRoot.containsKey("sound")) {
        if (extrasRoot.getString("sound").equalsIgnoreCase("default")) {
            notificationDefaults |= Notification.DEFAULT_SOUND;
        } else {
            File file = null;
            // getResourcesDirectory
            file = new File("app://" + extrasRoot.getString("sound"));
            if (file != null && file.exists()) {
                notificationSound = Uri.fromFile(file);
            } else {
                // getResourcesDirectory + sound folder
                file = new File("app://sound/" + extrasRoot.getString("sound"));
                if (file != null && file.exists()) {
                    notificationSound = Uri.fromFile(file);
                } else {
                    // getExternalStorageDirectory
                    file = new File("appdata://" + extrasRoot.getString("sound"));
                    if (file != null && file.exists()) {
                        notificationSound = Uri.fromFile(file);
                    } else {
                        // getExternalStorageDirectory + sound folder
                        file = new File("appdata://sound/" + extrasRoot.getString("sound"));
                        if (file != null && file.exists()) {
                            notificationSound = Uri.fromFile(file);
                        } else {
                            // res folder
                            int soundId = appContext.getResources().getIdentifier(extrasRoot.getString("sound"),
                                    "raw", appContext.getPackageName());
                            if (soundId != 0) {
                                notificationSound = Uri.parse("android.resource://"
                                        + appContext.getPackageName() + "/raw/" + soundId);
                            } else {
                                // res folder without file extension
                                String soundFile = extrasRoot.getString("sound").split("\\.")[0];
                                soundId = appContext.getResources().getIdentifier(soundFile, "raw",
                                        appContext.getPackageName());
                                if (soundId != 0) {
                                    notificationSound = Uri.parse("android.resource://"
                                            + appContext.getPackageName() + "/raw/" + soundId);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    // VIBRATE
    if (extras.containsKey("vibrate") && extras.getString("vibrate").equalsIgnoreCase("true")) {
        notificationDefaults |= Notification.DEFAULT_VIBRATE;
    }

    // LIGHTS
    if (extras.containsKey("lights") && extras.getString("lights").equalsIgnoreCase("true")) {
        notificationDefaults |= Notification.DEFAULT_LIGHTS;
    }

    // NOTIFICATION ID
    if (extras.containsKey("notificationId")) {
        try {
            notificationId = Integer.parseInt(extras.getString("notificationId"));
        } catch (NumberFormatException nfe) {
        }
    }
    if (notificationId == 0) {
        notificationId = appContext.getAppProperties().getInt(PROPERTY_NOTIFICATION_ID, 0);
        notificationId++;
        appContext.getAppProperties().setInt(PROPERTY_NOTIFICATION_ID, notificationId);
    }

    // BADGE
    if (extras.containsKey("badge")) {
        try {
            badgeCount = Integer.parseInt(extras.getString("badge"));
        } catch (NumberFormatException nfe) {
        }
    }

    // LARGE ICON
    Bitmap largeIcon = null;
    if (extras.containsKey("largeIcon")) {
        largeIcon = getBitmap(extras.getString("largeIcon"));
    } else if (extras.containsKey("licon")) {
        largeIcon = getBitmap(extras.getString("licon"));
    } else if (extrasRoot.containsKey("largeIcon")) {
        largeIcon = getBitmap(extrasRoot.getString("largeIcon"));
    } else if (extrasRoot.containsKey("licon")) {
        largeIcon = getBitmap(extrasRoot.getString("licon"));
    }

    // SMALL ICON
    if (extras.containsKey("smallIcon")) {
        appIconId = appContext.getResources().getIdentifier(extras.getString("smallIcon"), "drawable",
                appContext.getPackageName());
        if (appIconId == 0) {
            Log.i(TAG, "Unable to find resource identifier to custom smallIcon : "
                    + extras.getString("smallIcon"));
        }
    } else if (extras.containsKey("sicon")) {
        appIconId = appContext.getResources().getIdentifier(extras.getString("sicon"), "drawable",
                appContext.getPackageName());
        if (appIconId == 0) {
            Log.i(TAG, "Unable to find resource identifier to custom sicon : " + extras.getString("sicon"));
        }
    } else if (extrasRoot.containsKey("smallIcon")) {
        appIconId = appContext.getResources().getIdentifier(extrasRoot.getString("smallIcon"), "drawable",
                appContext.getPackageName());
        if (appIconId == 0) {
            Log.i(TAG, "Unable to find resource identifier to custom smallIcon : "
                    + extrasRoot.getString("smallIcon"));
        }
    } else if (extrasRoot.containsKey("sicon")) {
        appIconId = appContext.getResources().getIdentifier(extrasRoot.getString("sicon"), "drawable",
                appContext.getPackageName());
        if (appIconId == 0) {
            Log.i(TAG, "Unable to find resource identifier to custom smallIcon : "
                    + extrasRoot.getString("sicon"));
        }
    }

    if (notificationText != null) {
        // Intent launch = getLauncherIntent(extras);
        Intent launch = new Intent(appContext, PendingNotificationActivity.class);
        launch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        if (extrasRoot != null && !extrasRoot.isEmpty()) {
            launch.putExtra(PROPERTY_EXTRAS, extrasRoot);
        }
        launch.setAction("dummy_unique_action_identifyer:" + notificationId);

        PendingIntent contentIntent = PendingIntent.getActivity(appContext, 0, launch,
                PendingIntent.FLAG_CANCEL_CURRENT);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(appContext);

        mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(notificationText));
        mBuilder.setContentText(notificationText);

        if (notificationTitle != null) {
            mBuilder.setContentTitle(notificationTitle);
        }
        if (notificationTicker != null) {
            mBuilder.setTicker(notificationTicker);
        }
        if (notificationDefaults != 0) {
            mBuilder.setDefaults(notificationDefaults);
        }
        if (notificationSound != null) {
            mBuilder.setSound(notificationSound);
        }
        if (badgeCount >= 0) {
            mBuilder.setNumber(badgeCount);
        }
        if (largeIcon != null) {
            mBuilder.setLargeIcon(largeIcon);
        }

        if (appIconId == 0) {
            appIconId = appContext.getResources().getIdentifier("appicon", "drawable",
                    appContext.getPackageName());
        }

        mBuilder.setSmallIcon(appIconId);
        mBuilder.setContentIntent(contentIntent);
        mBuilder.setAutoCancel(true);
        mBuilder.setWhen(System.currentTimeMillis());

        // ledARGB, ledOnMS, ledOffMS
        boolean customLight = false;
        int argb = 0xFFFFFFFF;
        int onMs = 1000;
        int offMs = 2000;
        if (extras.containsKey("ledARGB")) {
            try {
                argb = TiColorHelper.parseColor(extras.getString("ledARGB"));
                customLight = true;
            } catch (Exception ex) {
                try {
                    argb = Integer.parseInt(extras.getString("ledARGB"));
                    customLight = true;
                } catch (NumberFormatException nfe) {
                }
            }
        } else if (extras.containsKey("ledc")) {
            try {
                argb = TiColorHelper.parseColor(extras.getString("ledc"));
                customLight = true;
            } catch (Exception ex) {
                try {
                    argb = Integer.parseInt(extras.getString("ledc"));
                    customLight = true;
                } catch (NumberFormatException nfe) {
                }
            }
        } else if (extrasRoot.containsKey("ledARGB")) {
            try {
                argb = TiColorHelper.parseColor(extrasRoot.getString("ledARGB"));
                customLight = true;
            } catch (Exception ex) {
                try {
                    argb = Integer.parseInt(extrasRoot.getString("ledARGB"));
                    customLight = true;
                } catch (NumberFormatException nfe) {
                }
            }
        } else if (extrasRoot.containsKey("ledc")) {
            try {
                argb = TiColorHelper.parseColor(extrasRoot.getString("ledc"));
                customLight = true;
            } catch (Exception ex) {
                try {
                    argb = Integer.parseInt(extrasRoot.getString("ledc"));
                    customLight = true;
                } catch (NumberFormatException nfe) {
                }
            }
        }
        if (extras.containsKey("ledOnMS")) {
            try {
                onMs = Integer.parseInt(extras.getString("ledOnMS"));
                customLight = true;
            } catch (NumberFormatException nfe) {
            }
        }
        if (extras.containsKey("ledOffMS")) {
            try {
                offMs = Integer.parseInt(extras.getString("ledOffMS"));
                customLight = true;
            } catch (NumberFormatException nfe) {
            }
        }
        if (customLight) {
            mBuilder.setLights(argb, onMs, offMs);
        }

        //Visibility
        if (extras.containsKey("visibility")) {
            try {
                mBuilder.setVisibility(Integer.parseInt(extras.getString("visibility")));
            } catch (NumberFormatException nfe) {
            }
        } else if (extras.containsKey("vis")) {
            try {
                mBuilder.setVisibility(Integer.parseInt(extras.getString("vis")));
            } catch (NumberFormatException nfe) {
            }
        } else if (extrasRoot.containsKey("visibility")) {
            try {
                mBuilder.setVisibility(Integer.parseInt(extrasRoot.getString("visibility")));
            } catch (NumberFormatException nfe) {
            }
        } else if (extrasRoot.containsKey("vis")) {
            try {
                mBuilder.setVisibility(Integer.parseInt(extrasRoot.getString("vis")));
            } catch (NumberFormatException nfe) {
            }
        }

        //Icon background color
        int accent_argb = 0xFFFFFFFF;
        if (extras.containsKey("accentARGB")) {
            try {
                accent_argb = TiColorHelper.parseColor(extras.getString("accentARGB"));
                mBuilder.setColor(accent_argb);
            } catch (Exception ex) {
                try {
                    accent_argb = Integer.parseInt(extras.getString("accentARGB"));
                    mBuilder.setColor(accent_argb);
                } catch (NumberFormatException nfe) {
                }
            }
        } else if (extras.containsKey("bgac")) {
            try {
                accent_argb = TiColorHelper.parseColor(extras.getString("bgac"));
                mBuilder.setColor(accent_argb);
            } catch (Exception ex) {
                try {
                    accent_argb = Integer.parseInt(extras.getString("bgac"));
                    mBuilder.setColor(accent_argb);
                } catch (NumberFormatException nfe) {
                }
            }
        } else if (extrasRoot.containsKey("accentARGB")) {
            try {
                accent_argb = TiColorHelper.parseColor(extrasRoot.getString("accentARGB"));
                mBuilder.setColor(accent_argb);
            } catch (Exception ex) {
                try {
                    accent_argb = Integer.parseInt(extrasRoot.getString("accentARGB"));
                    mBuilder.setColor(accent_argb);
                } catch (NumberFormatException nfe) {
                }
            }
        } else if (extrasRoot.containsKey("bgac")) {
            try {
                accent_argb = TiColorHelper.parseColor(extrasRoot.getString("bgac"));
                mBuilder.setColor(accent_argb);
            } catch (Exception ex) {
                try {
                    accent_argb = Integer.parseInt(extrasRoot.getString("bgac"));
                    mBuilder.setColor(accent_argb);
                } catch (NumberFormatException nfe) {
                }
            }
        }

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

        nm.notify(notificationId, mBuilder.build());
    }
}

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

public static void makeFavsNotification(ArrayList<String[]> tweets, Context context, boolean toDrawer) {
    String shortText;/*w w w .ja v  a 2  s  .c  om*/
    String longText;
    String title;
    int smallIcon = R.drawable.ic_stat_icon;
    Bitmap largeIcon;

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

    NotificationCompat.InboxStyle inbox = null;

    if (tweets.size() == 1) {
        title = tweets.get(0)[0];
        shortText = tweets.get(0)[1];
        longText = shortText;

        largeIcon = getImage(context, tweets.get(0)[2]);
    } else {
        inbox = new NotificationCompat.InboxStyle();

        title = context.getResources().getString(R.string.favorite_users);
        shortText = tweets.size() + " " + context.getResources().getString(R.string.fav_user_tweets);
        longText = "";

        try {
            inbox.setBigContentTitle(shortText);
        } catch (Exception e) {

        }

        if (tweets.size() <= 5) {
            for (String[] s : tweets) {
                inbox.addLine(Html.fromHtml("<b>" + s[0] + ":</b> " + s[1]));
            }
        } else {
            for (int i = 0; i < 5; i++) {
                inbox.addLine(Html.fromHtml("<b>" + tweets.get(i)[0] + ":</b> " + tweets.get(i)[1]));
            }

            inbox.setSummaryText("+" + (tweets.size() - 5) + " " + context.getString(R.string.tweets));
        }

        largeIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.drawer_user_dark);
    }

    NotificationCompat.Builder mBuilder;

    AppSettings settings = AppSettings.getInstance(context);

    if (shortText.contains("@" + settings.myScreenName)) {
        // return because there is a mention notification for this already
        return;
    }

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

    mBuilder = new NotificationCompat.Builder(context).setContentTitle(title)
            .setContentText(TweetLinkUtils.removeColorHtml(shortText, settings)).setSmallIcon(smallIcon)
            .setLargeIcon(largeIcon).setContentIntent(resultPendingIntent).setAutoCancel(true)
            .setDeleteIntent(PendingIntent.getBroadcast(context, 0, deleteIntent, 0))
            .setPriority(NotificationCompat.PRIORITY_HIGH);

    if (inbox == null) {
        mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(Html.fromHtml(
                settings.addonTheme ? longText.replaceAll("FF8800", settings.accentColor) : longText)));
    } else {
        mBuilder.setStyle(inbox);
    }
    if (settings.vibrate) {
        mBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
    }

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

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

    if (settings.notifications) {

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);

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

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

        // Pebble notification
        if (context
                .getSharedPreferences("com.daiv.android.twitter_world_preferences",
                        Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE)
                .getBoolean("pebble_notification", false)) {
            sendAlertToPebble(context, title, shortText);
        }

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

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

/**
 * Validate the notifications notification.
 *///from ww  w . j a  v  a2  s.  c om
private static void validateNotifications(Context context, final Folder folder, final Account account,
        boolean getAttention, boolean ignoreUnobtrusiveSetting, NotificationKey key) {

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

    final NotificationMap notificationMap = getNotificationMap(context);
    if (LogUtils.isLoggable(LOG_TAG, LogUtils.VERBOSE)) {
        LogUtils.i(LOG_TAG, "Validating Notification: %s mapSize: %d " + "folder: %s getAttention: %b",
                createNotificationString(notificationMap), notificationMap.size(), folder.name, getAttention);
    } else {
        LogUtils.i(LOG_TAG, "Validating Notification, mapSize: %d " + "getAttention: %b",
                notificationMap.size(), getAttention);
    }
    // The number of unread messages for this account and label.
    final Integer unread = notificationMap.getUnread(key);
    final int unreadCount = unread != null ? unread.intValue() : 0;
    final Integer unseen = notificationMap.getUnseen(key);
    int unseenCount = unseen != null ? unseen.intValue() : 0;

    Cursor cursor = null;

    try {
        final Uri.Builder uriBuilder = folder.conversationListUri.buildUpon();
        uriBuilder.appendQueryParameter(UIProvider.SEEN_QUERY_PARAMETER, Boolean.FALSE.toString());
        // Do not allow this quick check to disrupt any active network-enabled conversation
        // cursor.
        uriBuilder.appendQueryParameter(UIProvider.ConversationListQueryParameters.USE_NETWORK,
                Boolean.FALSE.toString());
        cursor = context.getContentResolver().query(uriBuilder.build(), UIProvider.CONVERSATION_PROJECTION,
                null, null, null);
        if (cursor == null) {
            // This folder doesn't exist.
            LogUtils.i(LOG_TAG, "The cursor is null, so the specified folder probably does not exist");
            clearFolderNotification(context, account, folder, false);
            return;
        }
        final int cursorUnseenCount = cursor.getCount();

        // Make sure the unseen count matches the number of items in the cursor.  But, we don't
        // want to overwrite a 0 unseen count that was specified in the intent
        if (unseenCount != 0 && unseenCount != cursorUnseenCount) {
            LogUtils.i(LOG_TAG, "Unseen count doesn't match cursor count.  unseen: %d cursor count: %d",
                    unseenCount, cursorUnseenCount);
            unseenCount = cursorUnseenCount;
        }

        // For the purpose of the notifications, the unseen count should be capped at the num of
        // unread conversations.
        if (unseenCount > unreadCount) {
            unseenCount = unreadCount;
        }

        final int notificationId = getNotificationId(account.getAccountManagerAccount(), folder);

        if (unseenCount == 0) {
            LogUtils.i(LOG_TAG, "validateNotifications - cancelling account %s / folder %s",
                    LogUtils.sanitizeName(LOG_TAG, account.name),
                    LogUtils.sanitizeName(LOG_TAG, folder.persistentId));
            nm.cancel(notificationId);
            return;
        }

        // We now have all we need to create the notification and the pending intent
        PendingIntent clickIntent;

        NotificationCompat.Builder notification = new NotificationCompat.Builder(context);
        notification.setSmallIcon(R.drawable.stat_notify_email);
        notification.setTicker(account.name);

        final long when;

        final long oldWhen = NotificationActionUtils.sNotificationTimestamps.get(notificationId);
        if (oldWhen != 0) {
            when = oldWhen;
        } else {
            when = System.currentTimeMillis();
        }

        notification.setWhen(when);

        // The timestamp is now stored in the notification, so we can remove it from here
        NotificationActionUtils.sNotificationTimestamps.delete(notificationId);

        // Dispatch a CLEAR_NEW_MAIL_NOTIFICATIONS intent if the user taps the "X" next to a
        // notification.  Also this intent gets fired when the user taps on a notification as
        // the AutoCancel flag has been set
        final Intent cancelNotificationIntent = new Intent(
                MailIntentService.ACTION_CLEAR_NEW_MAIL_NOTIFICATIONS);
        cancelNotificationIntent.setPackage(context.getPackageName());
        cancelNotificationIntent.setData(Utils.appendVersionQueryParameter(context, folder.folderUri.fullUri));
        cancelNotificationIntent.putExtra(Utils.EXTRA_ACCOUNT, account);
        cancelNotificationIntent.putExtra(Utils.EXTRA_FOLDER, folder);

        notification.setDeleteIntent(
                PendingIntent.getService(context, notificationId, cancelNotificationIntent, 0));

        // Ensure that the notification is cleared when the user selects it
        notification.setAutoCancel(true);

        boolean eventInfoConfigured = false;

        final boolean isInbox = folder.folderUri.equals(account.settings.defaultInbox);
        final FolderPreferences folderPreferences = new FolderPreferences(context, account.getEmailAddress(),
                folder, isInbox);

        if (isInbox) {
            final AccountPreferences accountPreferences = new AccountPreferences(context,
                    account.getEmailAddress());
            moveNotificationSetting(accountPreferences, folderPreferences);
        }

        if (!folderPreferences.areNotificationsEnabled()) {
            LogUtils.i(LOG_TAG, "Notifications are disabled for this folder; not notifying");
            // Don't notify
            return;
        }

        if (unreadCount > 0) {
            // How can I order this properly?
            if (cursor.moveToNext()) {
                final Intent notificationIntent;

                // Launch directly to the conversation, if there is only 1 unseen conversation
                final boolean launchConversationMode = (unseenCount == 1);
                if (launchConversationMode) {
                    notificationIntent = createViewConversationIntent(context, account, folder, cursor);
                } else {
                    notificationIntent = createViewConversationIntent(context, account, folder, null);
                }

                Analytics.getInstance().sendEvent("notification_create",
                        launchConversationMode ? "conversation" : "conversation_list",
                        folder.getTypeDescription(), unseenCount);

                if (notificationIntent == null) {
                    LogUtils.e(LOG_TAG, "Null intent when building notification");
                    return;
                }

                // Amend the click intent with a hint that its source was a notification,
                // but remove the hint before it's used to generate notification action
                // intents. This prevents the following sequence:
                // 1. generate single notification
                // 2. user clicks reply, then completes Compose activity
                // 3. main activity launches, gets FROM_NOTIFICATION hint in intent
                notificationIntent.putExtra(Utils.EXTRA_FROM_NOTIFICATION, true);
                clickIntent = PendingIntent.getActivity(context, -1, notificationIntent,
                        PendingIntent.FLAG_UPDATE_CURRENT);
                notificationIntent.removeExtra(Utils.EXTRA_FROM_NOTIFICATION);

                configureLatestEventInfoFromConversation(context, account, folderPreferences, notification,
                        cursor, clickIntent, notificationIntent, unreadCount, unseenCount, folder, when);
                eventInfoConfigured = true;
            }
        }

        final boolean vibrate = folderPreferences.isNotificationVibrateEnabled();
        final String ringtoneUri = folderPreferences.getNotificationRingtoneUri();
        final boolean notifyOnce = !folderPreferences.isEveryMessageNotificationEnabled();

        if (!ignoreUnobtrusiveSetting && notifyOnce) {
            // If the user has "unobtrusive notifications" enabled, only alert the first time
            // new mail is received in this account.  This is the default behavior.  See
            // bugs 2412348 and 2413490.
            notification.setOnlyAlertOnce(true);
        }

        LogUtils.i(LOG_TAG, "Account: %s vibrate: %s", LogUtils.sanitizeName(LOG_TAG, account.name),
                Boolean.toString(folderPreferences.isNotificationVibrateEnabled()));

        int defaults = 0;

        /*
         * We do not want to notify if this is coming back from an Undo notification, hence the
         * oldWhen check.
         */
        if (getAttention && oldWhen == 0) {
            final AccountPreferences accountPreferences = new AccountPreferences(context, account.name);
            if (accountPreferences.areNotificationsEnabled()) {
                if (vibrate) {
                    defaults |= Notification.DEFAULT_VIBRATE;
                }

                notification.setSound(TextUtils.isEmpty(ringtoneUri) ? null : Uri.parse(ringtoneUri));
                LogUtils.i(LOG_TAG, "New email in %s vibrateWhen: %s, playing notification: %s",
                        LogUtils.sanitizeName(LOG_TAG, account.name), vibrate, ringtoneUri);
            }
        }

        // TODO(skennedy) Why do we do any of the above if we're just going to bail here?
        if (eventInfoConfigured) {
            defaults |= Notification.DEFAULT_LIGHTS;
            notification.setDefaults(defaults);

            if (oldWhen != 0) {
                // We do not want to display the ticker again if we are re-displaying this
                // notification (like from an Undo notification)
                notification.setTicker(null);
            }

            nm.notify(notificationId, notification.build());
        } else {
            LogUtils.i(LOG_TAG, "event info not configured - not notifying");
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

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

private static void updateBuilderAudioVibrate(final NotificationState state,
        final NotificationCompat.Builder notifBuilder, final boolean silent, final Uri ringtoneUri,
        final String conversationId) {
    int defaults = Notification.DEFAULT_LIGHTS;
    if (!silent) {
        final BuglePrefs prefs = Factory.get().getApplicationPrefs();
        final long latestNotificationTimestamp = prefs
                .getLong(BuglePrefsKeys.LATEST_NOTIFICATION_MESSAGE_TIMESTAMP, Long.MIN_VALUE);
        final long latestReceivedTimestamp = state.getLatestReceivedTimestamp();
        prefs.putLong(BuglePrefsKeys.LATEST_NOTIFICATION_MESSAGE_TIMESTAMP,
                Math.max(latestNotificationTimestamp, latestReceivedTimestamp));
        if (latestReceivedTimestamp > latestNotificationTimestamp) {
            synchronized (mLock) {
                // Find out the last time we dinged for this conversation
                Long lastTime = sLastMessageDingTime.get(conversationId);
                if (sTimeBetweenDingsMs == 0) {
                    sTimeBetweenDingsMs = BugleGservices.get().getInt(
                            BugleGservicesKeys.NOTIFICATION_TIME_BETWEEN_RINGS_SECONDS,
                            BugleGservicesKeys.NOTIFICATION_TIME_BETWEEN_RINGS_SECONDS_DEFAULT) * 1000;
                }/*from w  w w.  j  a va  2s . c  om*/
                if (lastTime == null || SystemClock.elapsedRealtime() - lastTime > sTimeBetweenDingsMs) {
                    sLastMessageDingTime.put(conversationId, SystemClock.elapsedRealtime());
                    notifBuilder.setSound(ringtoneUri);
                    if (shouldVibrate(state)) {
                        defaults |= Notification.DEFAULT_VIBRATE;
                    }
                }
            }
        }
    }
    notifBuilder.setDefaults(defaults);
}

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

public static void makeFavsNotification(ArrayList<String[]> tweets, Context context, boolean toDrawer) {
    String shortText;//from   w  w  w  . j a v  a  2 s.  c  o m
    String longText;
    String title;
    int smallIcon = R.drawable.ic_stat_icon;
    Bitmap largeIcon;

    Intent resultIntent;

    if (toDrawer) {
        resultIntent = new Intent(context, RedirectToDrawer.class);
    } else {
        resultIntent = new Intent(context, NotiTweetPager.class);
    }

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

    NotificationCompat.InboxStyle inbox = null;

    if (tweets.size() == 1) {
        title = tweets.get(0)[0];
        shortText = tweets.get(0)[1];
        longText = shortText;

        largeIcon = getImage(context, tweets.get(0)[2]);
    } else {
        inbox = new NotificationCompat.InboxStyle();

        title = context.getResources().getString(R.string.favorite_users);
        shortText = tweets.size() + " " + context.getResources().getString(R.string.fav_user_tweets);
        longText = "";

        try {
            inbox.setBigContentTitle(shortText);
        } catch (Exception e) {

        }

        if (tweets.size() <= 5) {
            for (String[] s : tweets) {
                inbox.addLine(Html.fromHtml("<b>" + s[0] + ":</b> " + s[1]));
            }
        } else {
            for (int i = 0; i < 5; i++) {
                inbox.addLine(Html.fromHtml("<b>" + tweets.get(i)[0] + ":</b> " + tweets.get(i)[1]));
            }

            inbox.setSummaryText("+" + (tweets.size() - 5) + " " + context.getString(R.string.tweets));
        }

        largeIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.drawer_user_dark);
    }

    NotificationCompat.Builder mBuilder;

    AppSettings settings = AppSettings.getInstance(context);

    if (shortText.contains("@" + settings.myScreenName)) {
        // return because there is a mention notification for this already
        return;
    }

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

    mBuilder = new NotificationCompat.Builder(context).setContentTitle(title)
            .setContentText(TweetLinkUtils.removeColorHtml(shortText, settings)).setSmallIcon(smallIcon)
            .setLargeIcon(largeIcon).setContentIntent(resultPendingIntent).setAutoCancel(true)
            .setDeleteIntent(PendingIntent.getBroadcast(context, 0, deleteIntent, 0))
            .setPriority(NotificationCompat.PRIORITY_HIGH);

    if (inbox == null) {
        mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(Html.fromHtml(
                settings.addonTheme ? longText.replaceAll("FF8800", settings.accentColor) : longText)));
    } else {
        mBuilder.setStyle(inbox);
    }
    if (settings.vibrate) {
        mBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
    }

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

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

    if (settings.notifications) {

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);

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

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

        // Pebble notification
        if (context
                .getSharedPreferences("com.klinker.android.twitter_world_preferences",
                        Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE)
                .getBoolean("pebble_notification", false)) {
            sendAlertToPebble(context, title, shortText);
        }

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

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

/**
 * Show (or update) a send failed notification. If tapped, the user is taken to the OUTBOX view
 * where he can view the list of failed mails. if tap retry,mail will retry to send.
 *//*  w ww .  j  a va  2 s.c  o m*/
public void showMailSendFaildNotification(long accountId, int number) {
    Account account = Account.restoreAccountWithId(mContext, accountId);
    if (account == null) {
        LogUtils.e(LOG_TAG, "Null account during notification SEND_FAILED ");
        return;
    }
    NotificationCompat.Builder notification = new NotificationCompat.Builder(mContext);
    ContentResolver conentResolver = mContext.getContentResolver();
    Folder UIFolder = queryUIFolder(conentResolver, accountId);
    Folder UIInboxFolder = queryUIInboxFolder(conentResolver, accountId);
    com.tct.mail.providers.Account UIAccount = queryUIaccount(conentResolver, accountId);
    if (UIFolder == null || UIAccount == null || UIInboxFolder == null) {
        LogUtils.e(LOG_TAG,
                "Null UIFolder or null UIAccount during showMailSendFaildNotification,do nothing,just return ");
        return;
    }
    //get account address
    String accountAddress = account.getEmailAddress();
    //get account senderName,if null,use address instand
    String senderName = account.getSenderName();
    //get the notification's title(2 emails not send or Email not send)
    String title = createTitle(number);
    //get the warning icon
    Bitmap icon = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.ic_warning_grey);

    //get the conversation
    final Uri.Builder uriBuilder = UIFolder.conversationListUri.buildUpon();
    Cursor conversationsCursor = mContext.getContentResolver().query(uriBuilder.build(),
            UIProvider.CONVERSATION_PROJECTION, null, null, null);

    //The Martro style only supported after android L.
    //TS:kaifeng.lu 2016-01-04 EMAIL BUGFIX_1272060   MOD_S
    if (com.tct.mail.utils.Utils.isRunningLOrLater()) {
        notification.setColor(mContext.getResources().getColor(R.color.notification_icon_mail_orange));
        //TS:kaifeng.lu 2016-01-04 EMAIL BUGFIX_1272060   MOD_E
        NotificationCompat.InboxStyle digest = new NotificationCompat.InboxStyle(notification);

        // query current account's outbox mails.and get the subject.
        // Subject1;
        // Subject2;
        // Subject3;
        if (conversationsCursor != null) {
            try {
                while (conversationsCursor.moveToNext()) {
                    final Conversation conversation = new Conversation(conversationsCursor);
                    String sub = createSubject(conversation);
                    digest.addLine(sub);
                }
            } catch (Exception e) {
                LogUtils.e(LOG_TAG, "exception happen during get notification subject", e.getMessage());
            } finally {
                if (conversationsCursor != null) {
                    conversationsCursor.close();
                }
            }
        }

        //only 1 mails failed, show the subject and its senderName and emailAddress.
        //Line1: show the mail's subject ,same with METHOD: notification.setContentText
        //TS:kaifeng.lu 2015-11-20 EMAIL BUGFIX_709873  MOD_S
        if (number > 0) {
            if (TextUtils.isEmpty(senderName)) {
                //TS:kaifeng.lu 2016-01-04 EMAIL BUGFIX_1272060   DEL
                //                    digest.addLine(accountAddress);
            } else {
                digest.addLine(senderName); // Line2: show the senderName,same with METHOD:Notification#setSubText()
            }
            digest.setSummaryText(accountAddress);
        }
        //TS:kaifeng.lu 2015-11-20 EMAIL BUGFIX_709873  MOD_E
        notification.setContentTitle(title);
        notification.setTicker(accountAddress);
        notification.setLargeIcon(icon);
        notification.setSmallIcon(R.drawable.ic_notification_mail_24dp);
        //set the content click/tap intent
        //it will trigger going to OUBOX
        Intent toOutboxAction = Utils.createViewFolderIntent(mContext, UIFolder.folderUri.fullUri, UIAccount);
        PendingIntent contentIntent = PendingIntent.getActivity(mContext, 0, toOutboxAction,
                PendingIntent.FLAG_UPDATE_CURRENT);
        notification.setContentIntent(contentIntent);
        //set the action click intent.
        //it will trigger the refresh.
        PendingIntent actionIntent = createRefreshIntent(UIFolder, true, account.mId);
        notification.addAction(R.drawable.ic_refresh_grey_24dp,
                mContext.getResources().getString(R.string.retry), actionIntent);

        //set the failed mails.
        //TS:kaifeng.lu 2016-01-04 EMAIL BUGFIX_1272060   DEL
        //            notification.setNumber(number);

        //set the light and sound
        FolderPreferences folderPreferences = new FolderPreferences(mContext, UIAccount.getAccountId(),
                UIInboxFolder, true);
        boolean vibrate = folderPreferences.isNotificationVibrateEnabled();
        //not give sound for retry notification
        //String ringtoneUri = folderPreferences.getNotificationRingtoneUri();
        int defaults = 0;
        if (vibrate) {
            defaults |= Notification.DEFAULT_VIBRATE;
        }
        // TS: zheng.zou 2015-09-10 EMAIL BUGFIX-557052 MOD_S
        //defaults |= Notification.FLAG_SHOW_LIGHTS;
        defaults |= Notification.DEFAULT_LIGHTS;
        notification.setDefaults(defaults);
        notification.setLights(0xff00ff00, 280, 2080);
        // TS: zheng.zou 2015-09-10 EMAIL BUGFIX-557052 MOD_E
        // notification.setSound(TextUtils.isEmpty(ringtoneUri) ? null
        //          : Uri.parse(ringtoneUri));
        //  LogUtils.i(LOG_TAG, "failed email in %s vibrateWhen: %s, playing notification: %s",
        //          LogUtils.sanitizeName(LOG_TAG, account.getEmailAddress()), vibrate);
        // TS: chao.zhang 2015-09-24 EMAIL FEATURE-585337 MOD_S
        //NOTE: UE:the notification only can be cancel by click.
        notification.setOngoing(true);
    }
    Notification warnningNotification = notification.build();
    warnningNotification.flags |= Notification.FLAG_AUTO_CANCEL;
    //TS:kaifeng.lu 2015-11-20 EMAIL BUGFIX_709873  MOD_S
    mNotificationManager.notify(getSendFailedNotificationId(accountId), warnningNotification);
    //TS:kaifeng.lu 2015-11-20 EMAIL BUGFIX_709873  MOD_E
    // TS: chao.zhang 2015-09-24 EMAIL FEATURE-585337 MOD_S
}

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

public static void notifySecondDMs(Context context, int secondAccount) {
    DMDataSource data = DMDataSource.getInstance(context);

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

    int numberNew = sharedPrefs.getInt("dm_unread_" + secondAccount, 0);

    int smallIcon = R.drawable.ic_stat_icon;
    Bitmap largeIcon;//  w w w. j  a v  a 2 s. co m

    NotificationCompat.Builder mBuilder;

    String title = context.getResources().getString(R.string.app_name) + " - "
            + context.getResources().getString(R.string.sec_acc);
    String name;
    String message;
    String messageLong;

    NotificationCompat.InboxStyle inbox = null;
    if (numberNew == 1) {
        name = data.getNewestName(secondAccount);

        // if they are muted, and you don't want them to show muted mentions
        // then just quit
        if (sharedPrefs.getString("muted_users", "").contains(name)
                && !sharedPrefs.getBoolean("show_muted_mentions", false)) {
            return;
        }

        message = context.getResources().getString(R.string.mentioned_by) + " @" + name;
        messageLong = "<b>@" + name + "</b>: " + data.getNewestMessage(secondAccount);
        largeIcon = getImage(context, name);
    } else { // more than one dm
        message = numberNew + " " + context.getResources().getString(R.string.new_mentions);
        messageLong = "<b>" + context.getResources().getString(R.string.mentions) + "</b>: " + numberNew + " "
                + context.getResources().getString(R.string.new_mentions);
        largeIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.drawer_user_dark);

        inbox = getDMInboxStyle(numberNew, secondAccount, context, message);
    }

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

    AppSettings settings = AppSettings.getInstance(context);

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

    mBuilder = new NotificationCompat.Builder(context).setContentTitle(title)
            .setContentText(TweetLinkUtils.removeColorHtml(message, settings)).setSmallIcon(smallIcon)
            .setLargeIcon(largeIcon).setDeleteIntent(PendingIntent.getBroadcast(context, 0, deleteIntent, 0))
            .setAutoCancel(true).setPriority(NotificationCompat.PRIORITY_HIGH);

    if (inbox == null) {
        mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(Html.fromHtml(
                settings.addonTheme ? messageLong.replaceAll("FF8800", settings.accentColor) : messageLong)));
    } else {
        mBuilder.setStyle(inbox);
    }

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

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

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

    if (settings.notifications) {

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);

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

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

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

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

From source file:com.dwdesign.tweetings.service.TweetingsService.java

private Notification buildNotification(final String title, final String message, final int icon,
        final Intent content_intent, final Intent delete_intent) {
    final NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    builder.setTicker(message);//from  www .  j  a  v  a  2s .  c  om
    builder.setContentTitle(title);
    builder.setContentText(message);
    builder.setAutoCancel(true);
    builder.setWhen(System.currentTimeMillis());
    builder.setSmallIcon(icon);
    if (delete_intent != null) {
        builder.setDeleteIntent(
                PendingIntent.getBroadcast(this, 0, delete_intent, PendingIntent.FLAG_UPDATE_CURRENT));
    }
    if (content_intent != null) {
        builder.setContentIntent(
                PendingIntent.getActivity(this, 0, content_intent, PendingIntent.FLAG_UPDATE_CURRENT));
    }
    int defaults = 0;
    final Calendar now = Calendar.getInstance();
    if (mPreferences.getBoolean(PREFERENCE_KEY_NOTIFICATION_HAVE_SOUND, true)
            && !mPreferences.getBoolean("silent_notifications_at_" + now.get(Calendar.HOUR_OF_DAY), false)) {
        Uri soundUri = Uri.parse(mPreferences.getString(PREFERENCE_KEY_NOTIFICATION_RINGTONE,
                "android.resource://" + getPackageName() + "/" + R.raw.notify));
        builder.setSound(soundUri, Notification.STREAM_DEFAULT);
    }
    if (mPreferences.getBoolean(PREFERENCE_KEY_NOTIFICATION_HAVE_VIBRATION, true)
            && !mPreferences.getBoolean("silent_notifications_at_" + now.get(Calendar.HOUR_OF_DAY), false)) {
        defaults |= Notification.DEFAULT_VIBRATE;
    }
    if (mPreferences.getBoolean(PREFERENCE_KEY_NOTIFICATION_HAVE_LIGHTS, true)
            && !mPreferences.getBoolean("silent_notifications_at_" + now.get(Calendar.HOUR_OF_DAY), false)) {
        final int color_def = getResources().getColor(R.color.holo_blue_dark);
        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.android.mail.utils.NotificationUtils.java

/**
 * Validate the notifications notification.
 *///from w  ww. j ava 2s .c o  m
private static void validateNotifications(Context context, final Folder folder, final Account account,
        boolean getAttention, boolean ignoreUnobtrusiveSetting, NotificationKey key,
        final ContactFetcher contactFetcher) {

    NotificationManagerCompat nm = NotificationManagerCompat.from(context);

    final NotificationMap notificationMap = getNotificationMap(context);
    if (LogUtils.isLoggable(LOG_TAG, LogUtils.VERBOSE)) {
        LogUtils.i(LOG_TAG,
                "Validating Notification: %s mapSize: %d "
                        + "folder: %s getAttention: %b ignoreUnobtrusive: %b",
                createNotificationString(notificationMap), notificationMap.size(), folder.name, getAttention,
                ignoreUnobtrusiveSetting);
    } else {
        LogUtils.i(LOG_TAG, "Validating Notification, mapSize: %d " + "getAttention: %b ignoreUnobtrusive: %b",
                notificationMap.size(), getAttention, ignoreUnobtrusiveSetting);
    }
    // The number of unread messages for this account and label.
    final Integer unread = notificationMap.getUnread(key);
    final int unreadCount = unread != null ? unread.intValue() : 0;
    final Integer unseen = notificationMap.getUnseen(key);
    int unseenCount = unseen != null ? unseen.intValue() : 0;

    Cursor cursor = null;

    try {
        final Uri.Builder uriBuilder = folder.conversationListUri.buildUpon();
        uriBuilder.appendQueryParameter(UIProvider.SEEN_QUERY_PARAMETER, Boolean.FALSE.toString());
        // Do not allow this quick check to disrupt any active network-enabled conversation
        // cursor.
        uriBuilder.appendQueryParameter(UIProvider.ConversationListQueryParameters.USE_NETWORK,
                Boolean.FALSE.toString());
        cursor = context.getContentResolver().query(uriBuilder.build(), UIProvider.CONVERSATION_PROJECTION,
                null, null, null);
        if (cursor == null) {
            // This folder doesn't exist.
            LogUtils.i(LOG_TAG, "The cursor is null, so the specified folder probably does not exist");
            clearFolderNotification(context, account, folder, false);
            return;
        }
        final int cursorUnseenCount = cursor.getCount();

        // Make sure the unseen count matches the number of items in the cursor.  But, we don't
        // want to overwrite a 0 unseen count that was specified in the intent
        if (unseenCount != 0 && unseenCount != cursorUnseenCount) {
            LogUtils.i(LOG_TAG, "Unseen count doesn't match cursor count.  unseen: %d cursor count: %d",
                    unseenCount, cursorUnseenCount);
            unseenCount = cursorUnseenCount;
        }

        // For the purpose of the notifications, the unseen count should be capped at the num of
        // unread conversations.
        if (unseenCount > unreadCount) {
            unseenCount = unreadCount;
        }

        final int notificationId = getNotificationId(account.getAccountManagerAccount(), folder);

        NotificationKey notificationKey = new NotificationKey(account, folder);

        if (unseenCount == 0) {
            LogUtils.i(LOG_TAG, "validateNotifications - cancelling account %s / folder %s",
                    LogUtils.sanitizeName(LOG_TAG, account.getEmailAddress()),
                    LogUtils.sanitizeName(LOG_TAG, folder.persistentId));
            nm.cancel(notificationId);
            cancelConversationNotifications(notificationKey, nm);

            return;
        }

        // We now have all we need to create the notification and the pending intent
        PendingIntent clickIntent = null;

        NotificationCompat.Builder notification = new NotificationCompat.Builder(context);
        NotificationCompat.WearableExtender wearableExtender = new NotificationCompat.WearableExtender();
        Map<Integer, NotificationBuilders> msgNotifications = new ArrayMap<Integer, NotificationBuilders>();

        if (com.android.mail.utils.Utils.isRunningLOrLater()) {
            notification.setColor(context.getResources().getColor(R.color.notification_icon_color));
        }

        if (unseenCount > 1) {
            notification.setSmallIcon(R.drawable.ic_notification_multiple_mail_24dp);
        } else {
            notification.setSmallIcon(R.drawable.ic_notification_mail_24dp);
        }
        notification.setTicker(account.getDisplayName());
        notification.setVisibility(NotificationCompat.VISIBILITY_PRIVATE);
        notification.setCategory(NotificationCompat.CATEGORY_EMAIL);

        final long when;

        final long oldWhen = NotificationActionUtils.sNotificationTimestamps.get(notificationId);
        if (oldWhen != 0) {
            when = oldWhen;
        } else {
            when = System.currentTimeMillis();
        }

        notification.setWhen(when);

        // The timestamp is now stored in the notification, so we can remove it from here
        NotificationActionUtils.sNotificationTimestamps.delete(notificationId);

        // Dispatch a CLEAR_NEW_MAIL_NOTIFICATIONS intent if the user taps the "X" next to a
        // notification.  Also this intent gets fired when the user taps on a notification as
        // the AutoCancel flag has been set
        final Intent cancelNotificationIntent = new Intent(
                MailIntentService.ACTION_CLEAR_NEW_MAIL_NOTIFICATIONS);
        cancelNotificationIntent.setPackage(context.getPackageName());
        cancelNotificationIntent.setData(Utils.appendVersionQueryParameter(context, folder.folderUri.fullUri));
        cancelNotificationIntent.putExtra(Utils.EXTRA_ACCOUNT, account);
        cancelNotificationIntent.putExtra(Utils.EXTRA_FOLDER, folder);

        notification.setDeleteIntent(
                PendingIntent.getService(context, notificationId, cancelNotificationIntent, 0));

        // Ensure that the notification is cleared when the user selects it
        notification.setAutoCancel(true);

        boolean eventInfoConfigured = false;

        final boolean isInbox = folder.folderUri.equals(account.settings.defaultInbox);
        final FolderPreferences folderPreferences = new FolderPreferences(context, account.getAccountId(),
                folder, isInbox);

        if (isInbox) {
            final AccountPreferences accountPreferences = new AccountPreferences(context,
                    account.getAccountId());
            moveNotificationSetting(accountPreferences, folderPreferences);
        }

        if (!folderPreferences.areNotificationsEnabled()) {
            LogUtils.i(LOG_TAG, "Notifications are disabled for this folder; not notifying");
            // Don't notify
            return;
        }

        if (unreadCount > 0) {
            // How can I order this properly?
            if (cursor.moveToNext()) {
                final Intent notificationIntent;

                // Launch directly to the conversation, if there is only 1 unseen conversation
                final boolean launchConversationMode = (unseenCount == 1);
                if (launchConversationMode) {
                    notificationIntent = createViewConversationIntent(context, account, folder, cursor);
                } else {
                    notificationIntent = createViewConversationIntent(context, account, folder, null);
                }

                Analytics.getInstance().sendEvent("notification_create",
                        launchConversationMode ? "conversation" : "conversation_list",
                        folder.getTypeDescription(), unseenCount);

                if (notificationIntent == null) {
                    LogUtils.e(LOG_TAG, "Null intent when building notification");
                    return;
                }

                clickIntent = createClickPendingIntent(context, notificationIntent);

                configureLatestEventInfoFromConversation(context, account, folderPreferences, notification,
                        wearableExtender, msgNotifications, notificationId, cursor, clickIntent,
                        notificationIntent, unreadCount, unseenCount, folder, when, contactFetcher);
                eventInfoConfigured = true;
            }
        }

        final boolean vibrate = folderPreferences.isNotificationVibrateEnabled();
        final String ringtoneUri = folderPreferences.getNotificationRingtoneUri();
        final boolean notifyOnce = !folderPreferences.isEveryMessageNotificationEnabled();

        if (!ignoreUnobtrusiveSetting && notifyOnce) {
            // If the user has "unobtrusive notifications" enabled, only alert the first time
            // new mail is received in this account.  This is the default behavior.  See
            // bugs 2412348 and 2413490.
            LogUtils.d(LOG_TAG, "Setting Alert Once");
            notification.setOnlyAlertOnce(true);
        }

        LogUtils.i(LOG_TAG, "Account: %s vibrate: %s",
                LogUtils.sanitizeName(LOG_TAG, account.getEmailAddress()),
                Boolean.toString(folderPreferences.isNotificationVibrateEnabled()));

        int defaults = 0;

        // Check if any current conversation notifications exist previously.  Only notify if
        // one of them is new.
        boolean hasNewConversationNotification;
        Set<Integer> prevConversationNotifications = sConversationNotificationMap.get(notificationKey);
        if (prevConversationNotifications != null) {
            hasNewConversationNotification = false;
            for (Integer currentNotificationId : msgNotifications.keySet()) {
                if (!prevConversationNotifications.contains(currentNotificationId)) {
                    hasNewConversationNotification = true;
                    break;
                }
            }
        } else {
            hasNewConversationNotification = true;
        }

        LogUtils.d(LOG_TAG, "getAttention=%s,oldWhen=%s,hasNewConversationNotification=%s", getAttention,
                oldWhen, hasNewConversationNotification);

        /*
         * We do not want to notify if this is coming back from an Undo notification, hence the
         * oldWhen check.
         */
        if (getAttention && oldWhen == 0 && hasNewConversationNotification) {
            final AccountPreferences accountPreferences = new AccountPreferences(context,
                    account.getAccountId());
            if (accountPreferences.areNotificationsEnabled()) {
                if (vibrate) {
                    defaults |= Notification.DEFAULT_VIBRATE;
                }

                notification.setSound(TextUtils.isEmpty(ringtoneUri) ? null : Uri.parse(ringtoneUri));
                LogUtils.i(LOG_TAG, "New email in %s vibrateWhen: %s, playing notification: %s",
                        LogUtils.sanitizeName(LOG_TAG, account.getEmailAddress()), vibrate, ringtoneUri);
            }
        }

        // TODO(skennedy) Why do we do any of the above if we're just going to bail here?
        if (eventInfoConfigured) {
            defaults |= Notification.DEFAULT_LIGHTS;
            notification.setDefaults(defaults);

            if (oldWhen != 0) {
                // We do not want to display the ticker again if we are re-displaying this
                // notification (like from an Undo notification)
                notification.setTicker(null);
            }

            notification.extend(wearableExtender);

            // create the *public* form of the *private* notification we have been assembling
            final Notification publicNotification = createPublicNotification(context, account, folder, when,
                    unseenCount, unreadCount, clickIntent);

            notification.setPublicVersion(publicNotification);

            nm.notify(notificationId, notification.build());

            if (prevConversationNotifications != null) {
                Set<Integer> currentNotificationIds = msgNotifications.keySet();
                for (Integer prevConversationNotificationId : prevConversationNotifications) {
                    if (!currentNotificationIds.contains(prevConversationNotificationId)) {
                        nm.cancel(prevConversationNotificationId);
                        LogUtils.d(LOG_TAG, "canceling conversation notification %s",
                                prevConversationNotificationId);
                    }
                }
            }

            for (Map.Entry<Integer, NotificationBuilders> entry : msgNotifications.entrySet()) {
                NotificationBuilders builders = entry.getValue();
                builders.notifBuilder.extend(builders.wearableNotifBuilder);
                nm.notify(entry.getKey(), builders.notifBuilder.build());
                LogUtils.d(LOG_TAG, "notifying conversation notification %s", entry.getKey());
            }

            Set<Integer> conversationNotificationIds = new HashSet<Integer>();
            conversationNotificationIds.addAll(msgNotifications.keySet());
            sConversationNotificationMap.put(notificationKey, conversationNotificationIds);
        } else {
            LogUtils.i(LOG_TAG, "event info not configured - not notifying");
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}