Example usage for android.app Notification Notification

List of usage examples for android.app Notification Notification

Introduction

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

Prototype

public Notification() 

Source Link

Document

Constructs a Notification object with default values.

Usage

From source file:com.dmbstream.android.util.Util.java

/**
 * Resolves the default text color for notifications.
 *
 * Based on http://stackoverflow.com/questions/4867338/custom-notification-layouts-and-text-colors/7320604#7320604
 *///from   ww w  .j  ava 2  s.  c  om
private static Pair<Integer, Integer> getNotificationTextColors(Context context) {
    if (NOTIFICATION_TEXT_COLORS.getFirst() == null && NOTIFICATION_TEXT_COLORS.getSecond() == null) {
        try {
            Notification notification = new Notification();
            String title = "title";
            String content = "content";
            notification.setLatestEventInfo(context, title, content, null);
            LinearLayout group = new LinearLayout(context);
            ViewGroup event = (ViewGroup) notification.contentView.apply(context, group);
            findNotificationTextColors(event, title, content);
            group.removeAllViews();
        } catch (Exception x) {
            Log.w(TAG, "Failed to resolve notification text colors.", x);
        }
    }
    return NOTIFICATION_TEXT_COLORS;
}

From source file:com.quran.labs.androidquran.service.AudioService.java

/**
 * Configures service as a foreground service. A foreground service
 * is a service that's doing something the user is actively aware of
 * (such as playing music), and must appear to the user as a notification.
 * That's why we create the notification here.
 */// w w w .  j  a  v a2  s .  co m
private void setUpAsForeground(String text) {
    PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 0,
            new Intent(getApplicationContext(), PagerActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
    mNotification = new Notification();
    mNotification.tickerText = text;
    mNotification.icon = R.drawable.icon;
    mNotification.flags |= Notification.FLAG_ONGOING_EVENT;
    mNotification.setLatestEventInfo(getApplicationContext(), mNotificationName, text, pi);
    startForeground(NOTIFICATION_ID, mNotification);
}

From source file:RhodesService.java

private void updateDownloadNotification(String url, int totalBytes, int currentBytes) {
    Context context = RhodesActivity.getContext();

    Notification n = new Notification();
    n.icon = android.R.drawable.stat_sys_download;
    n.flags |= Notification.FLAG_ONGOING_EVENT;

    RemoteViews expandedView = new RemoteViews(context.getPackageName(),
            R.layout.status_bar_ongoing_event_progress_bar);

    StringBuilder newUrl = new StringBuilder();
    if (url.length() < 17)
        newUrl.append(url);/*from w w w  .j a  v  a2 s.c  om*/
    else {
        newUrl.append(url.substring(0, 7));
        newUrl.append("...");
        newUrl.append(url.substring(url.length() - 7, url.length()));
    }
    expandedView.setTextViewText(R.id.title, newUrl.toString());

    StringBuffer downloadingText = new StringBuffer();
    if (totalBytes > 0) {
        long progress = currentBytes * 100 / totalBytes;
        downloadingText.append(progress);
        downloadingText.append('%');
    }
    expandedView.setTextViewText(R.id.progress_text, downloadingText.toString());
    expandedView.setProgressBar(R.id.progress_bar, totalBytes < 0 ? 100 : totalBytes, currentBytes,
            totalBytes < 0);
    n.contentView = expandedView;

    Intent intent = new Intent(ACTION_ASK_CANCEL_DOWNLOAD);
    n.contentIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
    intent = new Intent(ACTION_CANCEL_DOWNLOAD);
    n.deleteIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

    mNM.notify(DOWNLOAD_PACKAGE_ID, n);
}

From source file:br.com.viniciuscr.notification2android.mediaPlayer.MediaPlaybackService.java

private void updateNotification() {
    RemoteViews views = new RemoteViews(getPackageName(), R.layout.statusbar);
    views.setImageViewResource(R.id.icon, R.drawable.stat_notify_musicplayer);
    if (getAudioId() < 0) {
        // streaming
        views.setTextViewText(R.id.trackname, getPath());
        views.setTextViewText(R.id.artistalbum, null);
    } else {/*from   www  . jav a 2 s.  co m*/
        String artist = getArtistName();
        views.setTextViewText(R.id.trackname, getTrackName());
        if (artist == null || artist.equals(MediaStore.UNKNOWN_STRING)) {
            artist = getString(R.string.unknown_artist_name);
        }
        String album = getAlbumName();
        if (album == null || album.equals(MediaStore.UNKNOWN_STRING)) {
            album = getString(R.string.unknown_album_name);
        }

        views.setTextViewText(R.id.artistalbum, getString(R.string.notification_artist_album, artist, album));
    }
    Notification status = new Notification();
    status.contentView = views;
    status.flags |= Notification.FLAG_ONGOING_EVENT;
    status.icon = R.drawable.stat_notify_musicplayer;
    status.contentIntent = PendingIntent.getActivity(this, 0,
            new Intent("com.android.music.PLAYBACK_VIEWER").addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 0);
    startForeground(PLAYBACKSERVICE_STATUS, status);
}

From source file:com.concentriclivers.mms.com.android.mms.transaction.MessagingNotification.java

private static void notifyFailed(Context context, boolean isDownload, long threadId, boolean noisy) {
    // TODO factor out common code for creating notifications
    boolean enabled = MessagingPreferenceActivity.getNotificationEnabled(context);
    if (!enabled) {
        return;/*from w ww.  j a v  a  2 s .  c om*/
    }

    // Strategy:
    // a. If there is a single failure notification, tapping on the notification goes
    //    to the compose view.
    // b. If there are two failure it stays in the thread view. Selecting one undelivered
    //    thread will dismiss one undelivered notification but will still display the
    //    notification.If you select the 2nd undelivered one it will dismiss the notification.

    long[] msgThreadId = { 0, 1 }; // Dummy initial values, just to initialize the memory
    int totalFailedCount = getUndeliveredMessageCount(context, msgThreadId);
    if (totalFailedCount == 0 && !isDownload) {
        return;
    }
    // The getUndeliveredMessageCount method puts a non-zero value in msgThreadId[1] if all
    // failures are from the same thread.
    // If isDownload is true, we're dealing with 1 specific failure; therefore "all failed" are
    // indeed in the same thread since there's only 1.
    boolean allFailedInSameThread = (msgThreadId[1] != 0) || isDownload;

    Intent failedIntent;
    Notification notification = new Notification();
    String title;
    String description;
    if (totalFailedCount > 1) {
        description = context.getString(R.string.notification_failed_multiple,
                Integer.toString(totalFailedCount));
        title = context.getString(R.string.notification_failed_multiple_title);
    } else {
        title = isDownload ? context.getString(R.string.message_download_failed_title)
                : context.getString(R.string.message_send_failed_title);

        description = context.getString(R.string.message_failed_body);
    }

    TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context);
    if (allFailedInSameThread) {
        failedIntent = new Intent(context, ComposeMessageActivity.class);
        if (isDownload) {
            // When isDownload is true, the valid threadId is passed into this function.
            failedIntent.putExtra("failed_download_flag", true);
        } else {
            threadId = msgThreadId[0];
            failedIntent.putExtra("undelivered_flag", true);
        }
        failedIntent.putExtra("thread_id", threadId);
        taskStackBuilder.addParentStack(ComposeMessageActivity.class);
    } else {
        failedIntent = new Intent(context, ConversationList.class);
    }
    taskStackBuilder.addNextIntent(failedIntent);

    notification.icon = R.drawable.stat_notify_sms_failed;

    notification.tickerText = title;

    notification.setLatestEventInfo(context, title, description,
            taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT));

    if (noisy) {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
        boolean vibrate = sp.getBoolean(MessagingPreferenceActivity.NOTIFICATION_VIBRATE,
                false /* don't vibrate by default */);
        if (vibrate) {
            notification.defaults |= Notification.DEFAULT_VIBRATE;
        }

        String ringtoneStr = sp.getString(MessagingPreferenceActivity.NOTIFICATION_RINGTONE, null);
        notification.sound = TextUtils.isEmpty(ringtoneStr) ? null : Uri.parse(ringtoneStr);
    }

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

    if (isDownload) {
        notificationMgr.notify(DOWNLOAD_FAILED_NOTIFICATION_ID, notification);
    } else {
        notificationMgr.notify(MESSAGE_FAILED_NOTIFICATION_ID, notification);
    }
}

From source file:github.madmarty.madsonic.util.Util.java

/**
 * Resolves the default text color for notifications.
 *
 * Based on http://stackoverflow.com/questions/4867338/custom-notification-layouts-and-text-colors/7320604#7320604
 *//*from w w w.  j  av  a  2s .c om*/
@SuppressWarnings("deprecation")
private static Pair<Integer, Integer> getNotificationTextColors(Context context) {
    if (NOTIFICATION_TEXT_COLORS.getFirst() == null && NOTIFICATION_TEXT_COLORS.getSecond() == null) {
        try {
            Notification notification = new Notification();
            String title = "title";
            String content = "content";
            notification.setLatestEventInfo(context, title, content, null);
            LinearLayout group = new LinearLayout(context);
            ViewGroup event = (ViewGroup) notification.contentView.apply(context, group);
            findNotificationTextColors(event, title, content);
            group.removeAllViews();
        } catch (Exception x) {
            LOG.warn("Failed to resolve notification text colors.", x);
        }
    }
    return NOTIFICATION_TEXT_COLORS;
}

From source file:com.android.mms.transaction.MessagingNotification.java

private static void notifyFailed(Context context, boolean isDownload, long threadId, boolean noisy) {
    // TODO factor out common code for creating notifications
    boolean enabled = MessagingPreferenceActivity.getNotificationEnabled(context);
    if (!enabled) {
        return;//  w w  w .ja  va 2 s .  c o m
    }

    // Strategy:
    // a. If there is a single failure notification, tapping on the notification goes
    //    to the compose view.
    // b. If there are two failure it stays in the thread view. Selecting one undelivered
    //    thread will dismiss one undelivered notification but will still display the
    //    notification.If you select the 2nd undelivered one it will dismiss the notification.
    int totalFailedCount = getUndeliveredMessageCount(context);

    Intent failedIntent;
    Notification notification = new Notification();
    String title;
    String description;
    if (totalFailedCount > 1) {
        description = context.getString(R.string.notification_failed_multiple,
                Integer.toString(totalFailedCount));
        title = context.getString(R.string.notification_failed_multiple_title);
    } else {
        title = isDownload ? context.getString(R.string.message_download_failed_title)
                : context.getString(R.string.message_send_failed_title);

        description = context.getString(R.string.message_failed_body);
    }

    TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context);
    // Get failed intent by folder mode or conversation mode.
    if (MessageUtils.isMailboxMode()) {
        failedIntent = getFailedIntentFromFolderMode(context, totalFailedCount, isDownload);
        if (failedIntent == null) {
            return;
        } else if (isDownload) {
            // When isDownload is true, the valid threadId is passed into this function.
            failedIntent.putExtra(FAILED_DOWNLOAD_FLAG, true);
        } else {
            failedIntent.putExtra(UNDELIVERED_FLAG, true);
        }
    } else {
        failedIntent = getFailedIntentFromConversationMode(context, isDownload, threadId);
    }

    taskStackBuilder.addNextIntent(failedIntent);

    notification.icon = R.drawable.stat_notify_sms_failed;

    notification.tickerText = title;

    notification.setLatestEventInfo(context, title, description,
            taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT));

    if (noisy) {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
        boolean vibrate = sp.getBoolean(MessagingPreferenceActivity.NOTIFICATION_VIBRATE,
                false /* don't vibrate by default */);
        if (vibrate) {
            notification.defaults |= Notification.DEFAULT_VIBRATE;
        }

        String ringtoneStr = sp.getString(MessagingPreferenceActivity.NOTIFICATION_RINGTONE, null);
        notification.sound = TextUtils.isEmpty(ringtoneStr) ? null : Uri.parse(ringtoneStr);
    }

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

    if (isDownload) {
        notificationMgr.notify(DOWNLOAD_FAILED_NOTIFICATION_ID, notification);
    } else {
        notificationMgr.notify(MESSAGE_FAILED_NOTIFICATION_ID, notification);
    }
}

From source file:mp.teardrop.PlaybackService.java

/**
 * Create a song notification. Call through the NotificationManager to
 * display it.//from ww w.  j a  va2  s .  co m
 *
 * @param song The Song to display information about.
 * @param state The state. Determines whether to show paused or playing icon.
 */
public Notification createNotification(Song song, int state) {
    boolean playing = (state & FLAG_PLAYING) != 0;

    RemoteViews views = new RemoteViews(getPackageName(), R.layout.notification);
    RemoteViews expanded = new RemoteViews(getPackageName(), R.layout.notification_expanded);

    Bitmap cover = song.getCover(this);
    if (cover == null) {
        views.setImageViewResource(R.id.cover, R.drawable.fallback_cover);
        expanded.setImageViewResource(R.id.cover, R.drawable.fallback_cover);
    } else {
        views.setImageViewBitmap(R.id.cover, cover);
        expanded.setImageViewBitmap(R.id.cover, cover);
    }

    int playButton = getPlayButtonResource(playing);

    views.setImageViewResource(R.id.play_pause, playButton);
    expanded.setImageViewResource(R.id.play_pause, playButton);

    ComponentName service = new ComponentName(this, PlaybackService.class);

    Intent previous = new Intent(PlaybackService.ACTION_PREVIOUS_SONG);
    previous.setComponent(service);
    expanded.setOnClickPendingIntent(R.id.previous, PendingIntent.getService(this, 0, previous, 0));

    Intent playPause = new Intent(PlaybackService.ACTION_TOGGLE_PLAYBACK_NOTIFICATION);
    playPause.setComponent(service);
    views.setOnClickPendingIntent(R.id.play_pause, PendingIntent.getService(this, 0, playPause, 0));
    expanded.setOnClickPendingIntent(R.id.play_pause, PendingIntent.getService(this, 0, playPause, 0));

    Intent next = new Intent(PlaybackService.ACTION_NEXT_SONG);
    next.setComponent(service);
    views.setOnClickPendingIntent(R.id.next, PendingIntent.getService(this, 0, next, 0));
    expanded.setOnClickPendingIntent(R.id.next, PendingIntent.getService(this, 0, next, 0));

    Intent close = new Intent(PlaybackService.ACTION_CLOSE_NOTIFICATION);
    close.setComponent(service);
    views.setOnClickPendingIntent(R.id.close, PendingIntent.getService(this, 0, close, 0));
    expanded.setOnClickPendingIntent(R.id.close, PendingIntent.getService(this, 0, close, 0));

    views.setTextViewText(R.id.title, song.title);
    views.setTextViewText(R.id.artist, song.artist);
    expanded.setTextViewText(R.id.title, song.title);
    expanded.setTextViewText(R.id.album, song.album);
    expanded.setTextViewText(R.id.artist, song.artist);

    Notification notification = new Notification();
    notification.contentView = views;
    notification.icon = R.drawable.status_icon;
    notification.flags |= Notification.FLAG_ONGOING_EVENT;
    notification.contentIntent = mNotificationAction;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        // expanded view is available since 4.1
        notification.bigContentView = expanded;
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        notification.visibility = Notification.VISIBILITY_PUBLIC;
    }

    //        if(mNotificationNag) {
    //            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    //                notification.priority = Notification.PRIORITY_MAX;
    //                notification.vibrate = new long[0]; // needed to get headsup
    //            } else {
    //                notification.tickerText = song.title + " - " + song.artist;
    //            }
    //        }

    return notification;
}

From source file:com.android.mms.transaction.MessagingNotification.java

/**
 * This method sends a notification to NotificationManager to display
 * an dialog indicating the message memory is full.
 *///from  w  w  w.j a  va  2s.  c  o  m
private static void sendFullNotification(Context context) {
    NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    String title = context.getString(R.string.sms_full_title);
    String description = context.getString(R.string.sms_full_body);
    PendingIntent intent = PendingIntent.getActivity(context, 0, new Intent(), 0);
    Notification notification = new Notification();
    notification.icon = R.drawable.stat_notify_sms_failed;
    notification.tickerText = title;
    notification.setLatestEventInfo(context, title, description, intent);
    nm.notify(FULL_NOTIFICATION_ID, notification);
}