Example usage for android.app Notification PRIORITY_HIGH

List of usage examples for android.app Notification PRIORITY_HIGH

Introduction

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

Prototype

int PRIORITY_HIGH

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

Click Source Link

Document

Higher #priority , for more important notifications or alerts.

Usage

From source file:com.ubergeek42.WeechatAndroid.service.Notificator.java

private static void makeNoise(Builder builder, Resources res, List<HotMessage> messages) {
    if (P.notificationTicker)
        builder.setTicker(messages.size() == 0 ? res.getQuantityString(R.plurals.hot_messages_missing, 1)
                : messages.get(messages.size() - 1).forTicker());
    builder.setPriority(Notification.PRIORITY_HIGH);
    if (!TextUtils.isEmpty(P.notificationSound))
        builder.setSound(Uri.parse(P.notificationSound));
    int flags = 0;
    if (P.notificationLight)
        flags |= Notification.DEFAULT_LIGHTS;
    if (P.notificationVibrate)
        flags |= Notification.DEFAULT_VIBRATE;
    builder.setDefaults(flags);/* ww w .j  ava2 s . c  o m*/
}

From source file:grupo19.locmess19.Services.LocationUpdatesService.java

private Notification getNotification() {

    Intent intent = new Intent(this, LocationUpdatesService.class);
    CharSequence text = Utils.getLocationText(mLocation);

    // Extra to help us figure out if we arrived in onStartCommand via the notification or not.
    intent.putExtra(EXTRA_STARTED_FROM_NOTIFICATION, true);

    // The PendingIntent that leads to a call to onStartCommand() in this service.
    PendingIntent servicePendingIntent = PendingIntent.getService(this, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    // The PendingIntent to launch activity.
    Intent newMessageIntent = new Intent(this, InboxActivity.class);
    newMessageIntent.putExtra("messageStringArray", messageStringArray);
    PendingIntent activityPendingIntent = PendingIntent.getActivity(this, 0, newMessageIntent, 0);

    return new NotificationCompat.Builder(this)
            .addAction(R.drawable.cast_album_art_placeholder, getString(R.string.launch_activity),
                    activityPendingIntent)
            .addAction(R.drawable.cast_album_art_placeholder, getString(R.string.remove_location_updates),
                    servicePendingIntent)
            .setContentText(text).setContentTitle(Utils.getLocationTitle(this)).setOngoing(true)
            .setPriority(Notification.PRIORITY_HIGH).setSmallIcon(R.mipmap.ic_launcher).setTicker(text)
            .setWhen(System.currentTimeMillis()).build();
}

From source file:com.online.fullsail.SaveWebMedia.java

@Override
protected void onPostExecute(File download) {
    String fileString = download.toString();
    mNM.cancel(timestamp);/*from w  w  w  .ja  v  a 2s  .  co  m*/
    System.gc();
    String fileName = fileString.substring(fileString.lastIndexOf('/') + 1, fileString.length());
    String fileExt = fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length());
    File downFile = new File(externalData, fileName);
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.fromFile(downFile), "application/" + fileExt);
    List<ResolveInfo> intents = this.context.getPackageManager().queryIntentActivities(intent,
            PackageManager.MATCH_DEFAULT_ONLY);
    if (intents == null || intents.size() == 0) {
        intent.setDataAndType(Uri.fromFile(downFile), "video/" + fileExt);
        intents = this.context.getPackageManager().queryIntentActivities(intent,
                PackageManager.MATCH_DEFAULT_ONLY);
        if (intents == null || intents.size() == 0) {
            intent.setDataAndType(Uri.fromFile(downFile), "image/" + fileExt);
            intents = this.context.getPackageManager().queryIntentActivities(intent,
                    PackageManager.MATCH_DEFAULT_ONLY);
            if (intents == null || intents.size() == 0) {
                intent = new Intent(Intent.ACTION_SEARCH);
                if (Integer.parseInt(Build.VERSION.SDK) > Build.VERSION_CODES.ECLAIR) {
                    intent.setPackage("com.android.vending");
                }
                intent.putExtra("query", fileExt);

            }
        }
    }
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    PendingIntent contentIntent = PendingIntent.getActivity(this.context, 0, intent,
            PendingIntent.FLAG_ONE_SHOT);
    Notification notification = null;
    Resources resources = this.context.getResources();
    String[] mediaTypes = resources.getStringArray(R.array.media);
    boolean acceptedType = false;
    for (int i = 0; i < mediaTypes.length; i++) {
        if (fileExt.toLowerCase().equals(mediaTypes[i])) {
            acceptedType = true;
        }
    }
    if (acceptedType) {
        Bitmap preview = null;
        String[] videoTypes = resources.getStringArray(R.array.movFiles);
        for (int i = 0; i < videoTypes.length; i++) {
            if (fileExt.toLowerCase().equals(videoTypes[i])) {
                preview = getVideoFrame(fileString);
            }
        }
        String[] imageTypes = resources.getStringArray(R.array.movFiles);
        for (int i = 0; i < imageTypes.length; i++) {
            if (fileExt.toLowerCase().equals(imageTypes[i])) {
                preview = decodeBitmapFile(fileString);
            }
        }
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this.context);
        builder.setTicker(this.context.getString(R.string.notify_download_complete))
                .setWhen(System.currentTimeMillis())
                .setContentTitle(this.context.getString(R.string.Document_complete))
                .setContentText(this.context.getString(R.string.Pdf_completed, fileName))
                .setSmallIcon(R.drawable.icon).setAutoCancel(true).setPriority(Notification.PRIORITY_HIGH)
                .setContentIntent(contentIntent);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            notification = new NotificationCompat.BigPictureStyle(builder).bigPicture(preview).build();
        } else {
            notification = builder.build();
        }
    } else {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this.context);
        builder.setContentTitle(this.context.getString(R.string.Document_complete))
                .setContentText(this.context.getString(R.string.Pdf_completed, fileName))
                .setSmallIcon(R.drawable.icon).setAutoCancel(true).setPriority(Notification.PRIORITY_HIGH)
                .setContentIntent(contentIntent);
        notification = builder.build();
    }
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    mNM.notify(timestamp, notification);
}

From source file:org.dmfs.tasks.notification.NotificationUpdaterService.java

@SuppressLint("InlinedApi")
public void resendPinNotification(Uri taskUri) {
    if (taskUri == null) {
        return;//from  w  ww . j  ava 2s .  com
    }
    long taskId = ContentUris.parseId(taskUri);
    if (taskId < 0) {
        return;
    }
    Integer notificationId = Long.valueOf(taskId).intValue();
    mBuilder.setDefaults(Notification.DEFAULT_ALL);
    mBuilder.setOngoing(true);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        mBuilder.setPriority(Notification.PRIORITY_HIGH);
    }

    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
    notificationManager.notify(notificationId, mBuilder.build());
}

From source file:com.example.android.wearable.wear.wearnotifications.handlers.MessagingIntentService.java

private NotificationCompat.Builder recreateBuilderWithMessagingStyle() {

    // Main steps for building a MESSAGING_STYLE notification (for more detailed comments on
    // building this notification, check StandaloneMainActivity.java)::
    //      0. Get your data
    //      1. Build the MESSAGING_STYLE
    //      2. Add support for Wear 1.+
    //      3. Set up main Intent for notification
    //      4. Set up RemoteInput (users can input directly from notification)
    //      5. Build and issue the notification

    // 0. Get your data (everything unique per Notification)
    MockDatabase.MessagingStyleCommsAppData messagingStyleCommsAppData = MockDatabase.getMessagingStyleData();

    // 1. Build the Notification.Style (MESSAGING_STYLE)
    String contentTitle = messagingStyleCommsAppData.getContentTitle();

    MessagingStyle messagingStyle = new NotificationCompat.MessagingStyle(
            messagingStyleCommsAppData.getReplayName()).setConversationTitle(contentTitle);

    // Adds all Messages
    for (MessagingStyle.Message message : messagingStyleCommsAppData.getMessages()) {
        messagingStyle.addMessage(message);
    }/*ww  w.  jav a 2 s .com*/

    // 2. Add support for Wear 1.+.
    String fullMessageForWearVersion1 = messagingStyleCommsAppData.getFullConversation();

    Notification chatHistoryForWearV1 = new NotificationCompat.Builder(getApplicationContext())
            .setStyle(new NotificationCompat.BigTextStyle().bigText(fullMessageForWearVersion1))
            .setContentTitle(contentTitle).setSmallIcon(R.drawable.ic_launcher)
            .setContentText(fullMessageForWearVersion1).build();

    // Adds page with all text to support Wear 1.+.
    NotificationCompat.WearableExtender wearableExtenderForWearVersion1 = new NotificationCompat.WearableExtender()
            .setHintContentIntentLaunchesActivity(true).addPage(chatHistoryForWearV1);

    // 3. Set up main Intent for notification
    Intent notifyIntent = new Intent(this, MessagingMainActivity.class);

    PendingIntent mainPendingIntent = PendingIntent.getActivity(this, 0, notifyIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    // 4. Set up a RemoteInput Action, so users can input (keyboard, drawing, voice) directly
    // from the notification without entering the app.
    String replyLabel = getString(R.string.reply_label);
    RemoteInput remoteInput = new RemoteInput.Builder(MessagingIntentService.EXTRA_REPLY).setLabel(replyLabel)
            .build();

    Intent replyIntent = new Intent(this, MessagingIntentService.class);
    replyIntent.setAction(MessagingIntentService.ACTION_REPLY);
    PendingIntent replyActionPendingIntent = PendingIntent.getService(this, 0, replyIntent, 0);

    // Enable action to appear inline on Wear 2.0 (24+). This means it will appear over the
    // lower portion of the Notification for easy action (only possible for one action).
    final NotificationCompat.Action.WearableExtender inlineActionForWear2_0 = new NotificationCompat.Action.WearableExtender()
            .setHintDisplayActionInline(true).setHintLaunchesActivity(false);

    NotificationCompat.Action replyAction = new NotificationCompat.Action.Builder(
            R.drawable.ic_reply_white_18dp, replyLabel, replyActionPendingIntent).addRemoteInput(remoteInput)
                    // Allows system to generate replies by context of conversation
                    .setAllowGeneratedReplies(true)
                    // Add WearableExtender to enable inline actions
                    .extend(inlineActionForWear2_0).build();

    // 5. Build and issue the notification
    NotificationCompat.Builder notificationCompatBuilder = new NotificationCompat.Builder(
            getApplicationContext());

    GlobalNotificationBuilder.setNotificationCompatBuilderInstance(notificationCompatBuilder);

    // Builds and issues notification
    notificationCompatBuilder.setStyle(messagingStyle).setContentTitle(contentTitle)
            .setContentText(messagingStyleCommsAppData.getContentText()).setSmallIcon(R.drawable.ic_launcher)
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_person_black_48dp))
            .setContentIntent(mainPendingIntent).setColor(getResources().getColor(R.color.colorPrimary))
            .setSubText(Integer.toString(messagingStyleCommsAppData.getNumberOfNewMessages()))
            .addAction(replyAction).setCategory(Notification.CATEGORY_MESSAGE)
            .setPriority(Notification.PRIORITY_HIGH).setVisibility(Notification.VISIBILITY_PRIVATE)
            .extend(wearableExtenderForWearVersion1);

    for (String name : messagingStyleCommsAppData.getParticipants()) {
        notificationCompatBuilder.addPerson(name);
    }

    return notificationCompatBuilder;
}

From source file:com.google.android.gms.location.sample.locationupdatesforegroundservice.LocationUpdatesService.java

/**
 * Returns the {@link NotificationCompat} used as part of the foreground service.
 */// www  .  ja v a2  s .co  m
private Notification getNotification() {
    Intent intent = new Intent(this, LocationUpdatesService.class);

    CharSequence text = Utils.getLocationText(mLocation);

    // Extra to help us figure out if we arrived in onStartCommand via the notification or not.
    intent.putExtra(EXTRA_STARTED_FROM_NOTIFICATION, true);

    // The PendingIntent that leads to a call to onStartCommand() in this service.
    PendingIntent servicePendingIntent = PendingIntent.getService(this, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    // The PendingIntent to launch activity.
    PendingIntent activityPendingIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, MainActivity.class), 0);

    return new NotificationCompat.Builder(this)
            .addAction(R.drawable.ic_launch, getString(R.string.launch_activity), activityPendingIntent)
            .addAction(R.drawable.ic_cancel, getString(R.string.remove_location_updates), servicePendingIntent)
            .setContentText(text).setContentTitle(Utils.getLocationTitle(this)).setOngoing(true)
            .setPriority(Notification.PRIORITY_HIGH).setSmallIcon(R.mipmap.ic_launcher).setTicker(text)
            .setWhen(System.currentTimeMillis()).build();
}

From source file:io.coldstart.android.GCMIntentService.java

private void sendRateLimitNotification(String rateLimitCount) {
    if (null == rateLimitCount)
        rateLimitCount = "0";

    Intent intent = new Intent(this, TrapListActivity.class);
    intent.putExtra("forceDownload", true);
    PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);

    Intent broadcastDownload = new Intent();
    broadcastDownload.setAction(BatchDownloadReceiver.BROADCAST_ACTION);
    PendingIntent pBroadcastDownload = PendingIntent.getBroadcast(this, 0, broadcastDownload, 0);

    Intent broadcastIgnore = new Intent();
    broadcastIgnore.setAction(BatchIgnoreReceiver.BROADCAST_ACTION);
    PendingIntent pBroadcastIgnore = PendingIntent.getBroadcast(this, 0, broadcastIgnore, 0);

    Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    Notification notification = null;

    if (Build.VERSION.SDK_INT >= 16) {
        notification = new Notification.InboxStyle(new Notification.Builder(this)
                .setContentTitle("Inbound Traps have been rate limited")
                .setContentText(/*from www.  j  a  va 2s.  c  o  m*/
                        "\"The number of traps being relayed to your phone has breeched the rate limit.")
                .setSmallIcon(R.drawable.ic_stat_ratelimit).setVibrate(new long[] { 0, 100, 200, 300 })
                .setAutoCancel(true).setSound(uri).setPriority(Notification.PRIORITY_HIGH)
                .setTicker("Inbound Traps have been rate limited")
                .addAction(R.drawable.ic_download_batch, "Get Batched Traps", pBroadcastDownload)
                .addAction(R.drawable.ic_ignore, "Ignore Batch", pBroadcastIgnore))
                        .setBigContentTitle("Inbound Traps have been rate limited")
                        .setSummaryText("Launch ColdStart.io to Manage These Events")
                        .addLine("The number of traps relayed to you has breeched the rate limit.")
                        .addLine("The current number of items queued is " + rateLimitCount).addLine(" ")
                        .addLine("Tap \"Get Batched Traps\" to download the cached traps")
                        .addLine("Tap \"Ignore Batch\" to delete them from the server.")

                        .build();
    } else {
        notification = new Notification.Builder(this).setContentTitle("Inbound Traps have been rate limited")
                .setContentText(
                        "The number of traps being relayed to your phone has breeched the rate limit. The current number of items queued is "
                                + rateLimitCount
                                + "\nTap \"Get Alerts\" to batch download the outstanding traps or tap \"Ignore\" to delete them from the server.")
                .setSmallIcon(R.drawable.ic_stat_ratelimit).setContentIntent(pIntent)
                .setVibrate(new long[] { 0, 100, 200, 300 }).setAutoCancel(true).setSound(uri).build();
    }

    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    notificationManager.notify(43524, notification);
}

From source file:at.flack.receiver.FacebookReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    Bundle bundle = intent.getExtras();/* w  w w .  java  2s. c om*/
    try {
        if (main instanceof FbMessageOverview && bundle.getString("type").equals("message")) {
            ((FbMessageOverview) main).addNewMessage(
                    new FacebookMessage(bundle.getString("fb_name"), bundle.getString("fb_message"),
                            bundle.getString("fb_img"), bundle.getLong("fb_id"), bundle.getString("fb_tid")));
        } else if (main instanceof FbMessageOverview && bundle.getString("type").equals("readreceipt")) {
            ((FbMessageOverview) main).changeReadReceipt(bundle.getLong("fb_time"),
                    bundle.getLong("fb_reader"));
        } else if (main instanceof FbMessageOverview && bundle.getString("type").equals("typ")) {
            ((FbMessageOverview) main).changeTypingStatus(bundle.getLong("my_id"), bundle.getLong("fb_id"),
                    bundle.getBoolean("fb_from_mobile"), bundle.getInt("fb_status"));
        } else if (main instanceof FbMessageOverview && bundle.getString("type").equals("img_message")) {
            ((FbMessageOverview) main).addNewMessage(new FacebookImageMessage(bundle.getString("fb_name"),
                    bundle.getString("fb_image"), bundle.getString("fb_preview"), bundle.getString("fb_img"),
                    bundle.getLong("fb_id"), bundle.getString("fb_tid")));
        } else if (bundle.getString("type").equals("read")) {
            killNotification(context,
                    new MarkAsRead(bundle.getString("fb_tid"), bundle.getBoolean("fb_markas")));
        } else if (bundle.getString("type").equals("message")
                || bundle.getString("type").equals("img_message")) {
            sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
            if (!sharedPrefs.getBoolean("notification_fbs", true))
                return;
            notify = sharedPrefs.getBoolean("notifications", true);
            vibrate = sharedPrefs.getBoolean("vibration", true);
            headsup = sharedPrefs.getBoolean("headsup", true);
            led_color = sharedPrefs.getInt("notification_light", -16776961);
            boolean all = sharedPrefs.getBoolean("all_fb", true);

            if (notify == false)
                return;
            if (bundle.getLong("fb_id") == bundle.getLong("my_id")) {
                return;
            }

            NotificationCompat.Builder mBuilder = null;
            boolean use_profile_picture = false;
            Bitmap profile_picture = null;

            String origin_name = bundle.getString("fb_name");

            try {
                profile_picture = RoundedImageView.getCroppedBitmap(Bitmap.createScaledBitmap(
                        ProfilePictureCache.getInstance(context).get(origin_name), 200, 200, false), 300);
                use_profile_picture = true;
            } catch (Exception e) {
                use_profile_picture = false;
            }

            Resources res = context.getResources();

            if (bundle.getString("type").equals("img_message")) {
                bundle.putString("fb_message", res.getString(R.string.fb_notification_new_image));
            }

            int lastIndex = bundle.getString("fb_message").lastIndexOf("=");
            if (lastIndex > 0 && Base64.isBase64(bundle.getString("fb_message").substring(0, lastIndex))) {
                mBuilder = new NotificationCompat.Builder(context)
                        .setSmallIcon(R.drawable.raven_notification_icon).setContentTitle(origin_name)
                        .setColor(0xFF175ea2)
                        .setContentText(res.getString(R.string.sms_receiver_new_encrypted_fb))
                        .setAutoCancel(true);
                if (use_profile_picture && profile_picture != null) {
                    mBuilder = mBuilder.setLargeIcon(profile_picture);
                } else {
                    mBuilder = mBuilder.setLargeIcon(convertToBitmap(origin_name,
                            context.getResources().getDrawable(R.drawable.ic_social_person), 200, 200));
                }
            } else { // normal or handshake

                if (bundle.getString("fb_message").charAt(0) == '%'
                        && (bundle.getString("fb_message").length() == 10
                                || bundle.getString("fb_message").length() == 9)) {
                    if (lastIndex > 0
                            && Base64.isBase64(bundle.getString("fb_message").substring(1, lastIndex))) {
                        mBuilder = new NotificationCompat.Builder(context).setContentTitle(origin_name)
                                .setColor(0xFF175ea2)
                                .setContentText(res.getString(R.string.sms_receiver_handshake_received))
                                .setSmallIcon(R.drawable.notification_icon).setAutoCancel(true);
                        if (use_profile_picture && profile_picture != null) {
                            mBuilder = mBuilder.setLargeIcon(profile_picture);
                        } else {
                            mBuilder = mBuilder.setLargeIcon(convertToBitmap(origin_name,
                                    context.getResources().getDrawable(R.drawable.ic_social_person), 200, 200));
                        }
                    } else {
                        return;
                    }
                } else if (bundle.getString("fb_message").charAt(0) == '%'
                        && bundle.getString("fb_message").length() >= 120
                        && bundle.getString("fb_message").length() < 125) {
                    if (lastIndex > 0
                            && Base64.isBase64(bundle.getString("fb_message").substring(1, lastIndex))) {
                        mBuilder = new NotificationCompat.Builder(context).setContentTitle(origin_name)
                                .setColor(0xFF175ea2)
                                .setContentText(res.getString(R.string.sms_receiver_handshake_received))
                                .setSmallIcon(R.drawable.notification_icon).setAutoCancel(true);
                        if (use_profile_picture && profile_picture != null) {
                            mBuilder = mBuilder.setLargeIcon(profile_picture);
                        } else {
                            mBuilder = mBuilder.setLargeIcon(convertToBitmap(origin_name,
                                    context.getResources().getDrawable(R.drawable.ic_social_person), 200, 200));
                        }
                    } else {
                        return;
                    }
                } else if (all) { // normal message
                    mBuilder = new NotificationCompat.Builder(context)
                            .setSmallIcon(R.drawable.raven_notification_icon).setContentTitle(origin_name)
                            .setColor(0xFF175ea2).setContentText(bundle.getString("fb_message"))
                            .setAutoCancel(true).setStyle(new NotificationCompat.BigTextStyle()
                                    .bigText(bundle.getString("fb_message")));

                    if (use_profile_picture && profile_picture != null) {
                        mBuilder = mBuilder.setLargeIcon(profile_picture);
                    } else {
                        mBuilder = mBuilder.setLargeIcon(convertToBitmap(origin_name,
                                context.getResources().getDrawable(R.drawable.ic_social_person), 200, 200));
                    }
                } else {
                    return;
                }
            }
            // }
            Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            mBuilder.setSound(alarmSound);
            mBuilder.setLights(led_color, 750, 4000);
            if (vibrate) {
                mBuilder.setVibrate(new long[] { 0, 100, 200, 300 });
            }

            Intent resultIntent = new Intent(context, MainActivity.class);
            resultIntent.putExtra("FACEBOOK_NAME", origin_name);

            TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
            stackBuilder.addParentStack(MainActivity.class);
            stackBuilder.addNextIntent(resultIntent);
            PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(1,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            mBuilder.setContentIntent(resultPendingIntent);
            if (Build.VERSION.SDK_INT >= 16 && headsup)
                mBuilder.setPriority(Notification.PRIORITY_HIGH);
            if (Build.VERSION.SDK_INT >= 21)
                mBuilder.setCategory(Notification.CATEGORY_MESSAGE);

            final NotificationManager mNotificationManager = (NotificationManager) context
                    .getSystemService(Context.NOTIFICATION_SERVICE);

            if (!MainActivity.isOnTop)
                mNotificationManager.notify(8, mBuilder.build());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.chromium.chrome.browser.download.DownloadNotificationService.java

/**
 * Add a in-progress download notification.
 * @param downloadGuid GUID of the download.
 * @param fileName File name of the download.
 * @param percentage Percentage completed. Value should be between 0 to 100 if
 *        the percentage can be determined, or -1 if it is unknown.
 * @param timeRemainingInMillis Remaining download time in milliseconds.
 * @param startTime Time when download started.
 * @param isOffTheRecord Whether the download is off the record.
 * @param canDownloadWhileMetered Whether the download can happen in metered network.
 *//*  w  w w  .j  a v  a 2  s .  com*/
public void notifyDownloadProgress(String downloadGuid, String fileName, int percentage,
        long timeRemainingInMillis, long startTime, boolean isOffTheRecord, boolean canDownloadWhileMetered,
        boolean isOfflinePage) {
    if (mStopPostingProgressNotifications)
        return;
    boolean indeterminate = percentage == INVALID_DOWNLOAD_PERCENTAGE;
    NotificationCompat.Builder builder = buildNotification(android.R.drawable.stat_sys_download, fileName,
            null);
    builder.setOngoing(true).setProgress(100, percentage, indeterminate);
    builder.setPriority(Notification.PRIORITY_HIGH);
    if (!indeterminate) {
        NumberFormat formatter = NumberFormat.getPercentInstance(Locale.getDefault());
        String percentText = formatter.format(percentage / 100.0);
        String duration = formatRemainingTime(mContext, timeRemainingInMillis);
        builder.setContentText(duration);
        if (Build.VERSION.CODENAME.equals("N") || Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            builder.setSubText(percentText);
        } else {
            builder.setContentInfo(percentText);
        }
    }
    int notificationId = getNotificationId(downloadGuid);
    int itemType = isOfflinePage ? DownloadSharedPreferenceEntry.ITEM_TYPE_OFFLINE_PAGE
            : DownloadSharedPreferenceEntry.ITEM_TYPE_DOWNLOAD;
    addOrReplaceSharedPreferenceEntry(new DownloadSharedPreferenceEntry(notificationId, isOffTheRecord,
            canDownloadWhileMetered, downloadGuid, fileName, itemType));
    if (startTime > 0)
        builder.setWhen(startTime);
    Intent cancelIntent = buildActionIntent(ACTION_DOWNLOAD_CANCEL, notificationId, downloadGuid, fileName,
            isOfflinePage);
    builder.addAction(R.drawable.btn_close_white,
            mContext.getResources().getString(R.string.download_notification_cancel_button),
            buildPendingIntent(cancelIntent, notificationId));
    Intent pauseIntent = buildActionIntent(ACTION_DOWNLOAD_PAUSE, notificationId, downloadGuid, fileName,
            isOfflinePage);
    builder.addAction(R.drawable.ic_vidcontrol_pause,
            mContext.getResources().getString(R.string.download_notification_pause_button),
            buildPendingIntent(pauseIntent, notificationId));
    updateNotification(notificationId, builder.build());
    if (!mDownloadsInProgress.contains(downloadGuid)) {
        mDownloadsInProgress.add(downloadGuid);
    }
}

From source file:com.android.messaging.receiver.SmsReceiver.java

public static void postNewMessageSecondaryUserNotification() {
    final Context context = Factory.get().getApplicationContext();
    final Resources resources = context.getResources();
    final PendingIntent pendingIntent = UIIntents.get()
            .getPendingIntentForSecondaryUserNewMessageNotification(context);

    final NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
    builder.setContentTitle(resources.getString(R.string.secondary_user_new_message_title))
            .setTicker(resources.getString(R.string.secondary_user_new_message_ticker))
            .setSmallIcon(R.drawable.ic_sms_light)
            // Returning PRIORITY_HIGH causes L to put up a HUD notification. Without it, the ticker
            // isn't displayed.
            .setPriority(Notification.PRIORITY_HIGH).setContentIntent(pendingIntent);

    final NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle(builder);
    bigTextStyle.bigText(resources.getString(R.string.secondary_user_new_message_title));
    final Notification notification = bigTextStyle.build();

    final NotificationManagerCompat notificationManager = NotificationManagerCompat
            .from(Factory.get().getApplicationContext());

    int defaults = Notification.DEFAULT_LIGHTS;
    if (BugleNotifications.shouldVibrate(new SecondaryUserNotificationState())) {
        defaults |= Notification.DEFAULT_VIBRATE;
    }/*from  w  w w  . ja  va 2s .c  o  m*/
    notification.defaults = defaults;

    notificationManager.notify(getNotificationTag(), PendingIntentConstants.SMS_SECONDARY_USER_NOTIFICATION_ID,
            notification);
}