Example usage for android.support.v4.app NotificationManagerCompat from

List of usage examples for android.support.v4.app NotificationManagerCompat from

Introduction

In this page you can find the example usage for android.support.v4.app NotificationManagerCompat from.

Prototype

public static NotificationManagerCompat from(Context context) 

Source Link

Usage

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

/**
 * Validate the notifications for the specified account.
 *///from  w  ww.  j a v a  2s . c  om
public static void validateAccountNotifications(Context context, Account account) {
    final String email = account.getEmailAddress();
    LogUtils.d(LOG_TAG, "validateAccountNotifications - %s", email);

    List<NotificationKey> notificationsToCancel = Lists.newArrayList();
    // Iterate through the notification map to see if there are any entries that correspond to
    // labels that are not in the sync set.
    final NotificationMap notificationMap = getNotificationMap(context);
    Set<NotificationKey> keys = notificationMap.keySet();
    final AccountPreferences accountPreferences = new AccountPreferences(context, account.getAccountId());
    final boolean enabled = accountPreferences.areNotificationsEnabled();
    if (!enabled) {
        // Cancel all notifications for this account
        for (NotificationKey notification : keys) {
            if (notification.account.getAccountManagerAccount().name.equals(email)) {
                notificationsToCancel.add(notification);
            }
        }
    } else {
        // Iterate through the notification map to see if there are any entries that
        // correspond to labels that are not in the notification set.
        for (NotificationKey notification : keys) {
            if (notification.account.getAccountManagerAccount().name.equals(email)) {
                // If notification is not enabled for this label, remember this NotificationKey
                // to later cancel the notification, and remove the entry from the map
                final Folder folder = notification.folder;
                final boolean isInbox = folder.folderUri.equals(notification.account.settings.defaultInbox);
                final FolderPreferences folderPreferences = new FolderPreferences(context,
                        notification.account.getAccountId(), folder, isInbox);

                if (!folderPreferences.areNotificationsEnabled()) {
                    notificationsToCancel.add(notification);
                }
            }
        }
    }

    // Cancel & remove the invalid notifications.
    if (notificationsToCancel.size() > 0) {
        NotificationManagerCompat nm = NotificationManagerCompat.from(context);
        for (NotificationKey notification : notificationsToCancel) {
            final Folder folder = notification.folder;
            final int notificationId = getNotificationId(notification.account.getAccountManagerAccount(),
                    folder);
            LogUtils.d(LOG_TAG, "validateAccountNotifications - cancelling %s / %s",
                    notification.account.getEmailAddress(), folder.persistentId);
            nm.cancel(notificationId);
            notificationMap.remove(notification);
            NotificationActionUtils.sUndoNotifications.remove(notificationId);
            NotificationActionUtils.sNotificationTimestamps.delete(notificationId);

            cancelConversationNotifications(notification, nm);
        }
        notificationMap.saveNotificationMap(context);
    }
}

From source file:com.irccloud.android.Notifications.java

public synchronized void excludeBid(int bid) {
    excludeBid = -1;// www.ja v  a 2 s.com
    ArrayList<Notification> notifications = getOtherNotifications();

    if (notifications.size() > 0) {
        for (Notification n : notifications) {
            NotificationManagerCompat.from(IRCCloudApplication.getInstance().getApplicationContext())
                    .cancel((int) (n.eid / 1000));
        }
    }
    NotificationManagerCompat.from(IRCCloudApplication.getInstance().getApplicationContext()).cancel(bid);
    excludeBid = bid;
}

From source file:com.androidinspain.deskclock.alarms.AlarmNotifications.java

static synchronized void clearNotification(Context context, AlarmInstance instance) {
    LogUtils.v("Clearing notifications for alarm instance: " + instance.mId);
    NotificationManagerCompat nm = NotificationManagerCompat.from(context);
    final int id = instance.hashCode();
    nm.cancel(id);/*  w  w  w  . j  a v  a 2  s.co m*/
    updateUpcomingAlarmGroupNotification(context, id, null);
    updateMissedAlarmGroupNotification(context, id, null);
}

From source file:uk.org.ngo.squeezer.service.SqueezeService.java

/**
 * Manages the state of any ongoing notification based on the player and connection state.
 *//*from   w  w  w.java  2s.  com*/
private void updateOngoingNotification() {
    Player activePlayer = this.mActivePlayer.get();
    PlayerState activePlayerState = getActivePlayerState();

    // Update scrobble state, if either we're currently scrobbling, or we
    // were (to catch the case where we started scrobbling a song, and the
    // user went in to settings to disable scrobbling).
    if (scrobblingEnabled || scrobblingPreviouslyEnabled) {
        scrobblingPreviouslyEnabled = scrobblingEnabled;
        Scrobble.scrobbleFromPlayerState(this, activePlayerState);
    }

    // If there's no active player then kill the notification and get out.
    // TODO: Have a "There are no connected players" notification text.
    if (activePlayer == null || activePlayerState == null) {
        clearOngoingNotification();
        return;
    }

    boolean playing = activePlayerState.isPlaying();

    // If the song is not playing and the user wants notifications only when playing then
    // kill the notification and get out.
    if (!playing && !mShowNotificationWhenNotPlaying) {
        clearOngoingNotification();
        return;
    }

    // If there's no current song then kill the notification and get out.
    // TODO: Have a "There's nothing playing" notification text.
    final Song currentSong = activePlayerState.getCurrentSong();
    if (currentSong == null) {
        clearOngoingNotification();
        return;
    }

    // Compare the current state with the state when the notification was last updated.
    // If there are no changes (same song, same playing state) then there's nothing to do.
    String songName = currentSong.getName();
    String albumName = currentSong.getAlbumName();
    String artistName = currentSong.getArtist();
    Uri url = currentSong.getArtworkUrl();
    String playerName = activePlayer.getName();

    if (mNotifiedPlayerState == null) {
        mNotifiedPlayerState = new PlayerState();
    } else {
        boolean lastPlaying = mNotifiedPlayerState.isPlaying();
        Song lastNotifiedSong = mNotifiedPlayerState.getCurrentSong();

        // No change in state
        if (playing == lastPlaying && currentSong.equals(lastNotifiedSong)) {
            return;
        }
    }

    mNotifiedPlayerState.setCurrentSong(currentSong);
    mNotifiedPlayerState.setPlayStatus(activePlayerState.getPlayStatus());
    final NotificationManagerCompat nm = NotificationManagerCompat.from(this);

    PendingIntent nextPendingIntent = getPendingIntent(ACTION_NEXT_TRACK);
    PendingIntent prevPendingIntent = getPendingIntent(ACTION_PREV_TRACK);
    PendingIntent playPendingIntent = getPendingIntent(ACTION_PLAY);
    PendingIntent pausePendingIntent = getPendingIntent(ACTION_PAUSE);
    PendingIntent closePendingIntent = getPendingIntent(ACTION_CLOSE);

    Intent showNowPlaying = new Intent(this, NowPlayingActivity.class)
            .setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    PendingIntent pIntent = PendingIntent.getActivity(this, 0, showNowPlaying, 0);
    Notification notification;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        final Notification.Builder builder = new Notification.Builder(this);
        builder.setContentIntent(pIntent);
        builder.setSmallIcon(R.drawable.squeezer_notification);
        builder.setVisibility(Notification.VISIBILITY_PUBLIC);
        builder.setShowWhen(false);
        builder.setContentTitle(songName);
        builder.setContentText(albumName);
        builder.setSubText(playerName);
        builder.setStyle(new Notification.MediaStyle().setShowActionsInCompactView(1, 2)
                .setMediaSession(mMediaSession.getSessionToken()));

        final MediaMetadata.Builder metaBuilder = new MediaMetadata.Builder();
        metaBuilder.putString(MediaMetadata.METADATA_KEY_ARTIST, artistName);
        metaBuilder.putString(MediaMetadata.METADATA_KEY_ALBUM, albumName);
        metaBuilder.putString(MediaMetadata.METADATA_KEY_TITLE, songName);
        mMediaSession.setMetadata(metaBuilder.build());

        // Don't set an ongoing notification, otherwise wearable's won't show it.
        builder.setOngoing(false);

        builder.setDeleteIntent(closePendingIntent);
        if (playing) {
            builder.addAction(
                    new Notification.Action(R.drawable.ic_action_previous, "Previous", prevPendingIntent))
                    .addAction(new Notification.Action(R.drawable.ic_action_pause, "Pause", pausePendingIntent))
                    .addAction(new Notification.Action(R.drawable.ic_action_next, "Next", nextPendingIntent));
        } else {
            builder.addAction(
                    new Notification.Action(R.drawable.ic_action_previous, "Previous", prevPendingIntent))
                    .addAction(new Notification.Action(R.drawable.ic_action_play, "Play", playPendingIntent))
                    .addAction(new Notification.Action(R.drawable.ic_action_next, "Next", nextPendingIntent));
        }

        ImageFetcher.getInstance(this).loadImage(url,
                getResources().getDimensionPixelSize(android.R.dimen.notification_large_icon_width),
                getResources().getDimensionPixelSize(android.R.dimen.notification_large_icon_height),
                new ImageWorker.ImageWorkerCallback() {
                    @Override
                    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
                    public void process(Object data, @Nullable Bitmap bitmap) {
                        if (bitmap == null) {
                            bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon_album_noart);
                        }

                        metaBuilder.putBitmap(MediaMetadata.METADATA_KEY_ALBUM_ART, bitmap);
                        metaBuilder.putBitmap(MediaMetadata.METADATA_KEY_ART, bitmap);
                        mMediaSession.setMetadata(metaBuilder.build());
                        builder.setLargeIcon(bitmap);
                        nm.notify(PLAYBACKSERVICE_STATUS, builder.build());
                    }
                });
    } else {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

        builder.setOngoing(true);
        builder.setCategory(NotificationCompat.CATEGORY_SERVICE);
        builder.setSmallIcon(R.drawable.squeezer_notification);

        RemoteViews normalView = new RemoteViews(this.getPackageName(), R.layout.notification_player_normal);
        RemoteViews expandedView = new RemoteViews(this.getPackageName(),
                R.layout.notification_player_expanded);

        normalView.setOnClickPendingIntent(R.id.next, nextPendingIntent);

        expandedView.setOnClickPendingIntent(R.id.previous, prevPendingIntent);
        expandedView.setOnClickPendingIntent(R.id.next, nextPendingIntent);

        builder.setContent(normalView);

        normalView.setTextViewText(R.id.trackname, songName);
        normalView.setTextViewText(R.id.albumname, albumName);

        expandedView.setTextViewText(R.id.trackname, songName);
        expandedView.setTextViewText(R.id.albumname, albumName);
        expandedView.setTextViewText(R.id.player_name, playerName);

        if (playing) {
            normalView.setImageViewResource(R.id.pause, R.drawable.ic_action_pause);
            normalView.setOnClickPendingIntent(R.id.pause, pausePendingIntent);

            expandedView.setImageViewResource(R.id.pause, R.drawable.ic_action_pause);
            expandedView.setOnClickPendingIntent(R.id.pause, pausePendingIntent);
        } else {
            normalView.setImageViewResource(R.id.pause, R.drawable.ic_action_play);
            normalView.setOnClickPendingIntent(R.id.pause, playPendingIntent);

            expandedView.setImageViewResource(R.id.pause, R.drawable.ic_action_play);
            expandedView.setOnClickPendingIntent(R.id.pause, playPendingIntent);
        }

        builder.setContentTitle(songName);
        builder.setContentText(getString(R.string.notification_playing_text, playerName));
        builder.setContentIntent(pIntent);

        notification = builder.build();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            notification.bigContentView = expandedView;
        }

        nm.notify(PLAYBACKSERVICE_STATUS, notification);

        ImageFetcher.getInstance(this).loadImage(this, url, normalView, R.id.album,
                getResources().getDimensionPixelSize(R.dimen.album_art_icon_normal_notification_width),
                getResources().getDimensionPixelSize(R.dimen.album_art_icon_normal_notification_height), nm,
                PLAYBACKSERVICE_STATUS, notification);
        ImageFetcher.getInstance(this).loadImage(this, url, expandedView, R.id.album,
                getResources().getDimensionPixelSize(R.dimen.album_art_icon_expanded_notification_width),
                getResources().getDimensionPixelSize(R.dimen.album_art_icon_expanded_notification_height), nm,
                PLAYBACKSERVICE_STATUS, notification);
    }
}

From source file:com.mylovemhz.simplay.MusicService.java

private void removeNotification() {
    NotificationManagerCompat manager = NotificationManagerCompat.from(getApplicationContext());
    manager.cancel(ID_NOTIFICATION);
}

From source file:com.onesignal.GenerateNotification.java

static void createSummaryNotification(Context inContext, boolean updateSummary, JSONObject gcmBundle) {
    if (updateSummary)
        setStatics(inContext);/*from  w w  w  .  ja  v  a 2 s  .  co  m*/

    String group = null;
    try {
        group = gcmBundle.getString("grp");
    } catch (Throwable t) {
    }

    Random random = new Random();
    PendingIntent summaryDeleteIntent = getNewActionPendingIntent(random.nextInt(),
            getNewBaseDeleteIntent(0).putExtra("summary", group));

    OneSignalDbHelper dbHelper = new OneSignalDbHelper(currentContext);
    SQLiteDatabase writableDb = dbHelper.getWritableDatabase();

    String[] retColumn = { NotificationTable.COLUMN_NAME_ANDROID_NOTIFICATION_ID,
            NotificationTable.COLUMN_NAME_FULL_DATA, NotificationTable.COLUMN_NAME_IS_SUMMARY,
            NotificationTable.COLUMN_NAME_TITLE, NotificationTable.COLUMN_NAME_MESSAGE };

    String[] whereArgs = { group };

    Cursor cursor = writableDb.query(NotificationTable.TABLE_NAME, retColumn,
            NotificationTable.COLUMN_NAME_GROUP_ID + " = ? AND " + // Where String
                    NotificationTable.COLUMN_NAME_DISMISSED + " = 0 AND " + NotificationTable.COLUMN_NAME_OPENED
                    + " = 0",
            whereArgs, null, // group by
            null, // filter by row groups
            NotificationTable._ID + " DESC" // sort order, new to old
    );

    Notification summaryNotification;
    int summaryNotificationId = random.nextInt();

    String firstFullData = null;
    Collection<SpannableString> summeryList = null;

    if (cursor.moveToFirst()) {
        SpannableString spannableString;
        summeryList = new ArrayList<SpannableString>();

        do {
            if (cursor.getInt(cursor.getColumnIndex(NotificationTable.COLUMN_NAME_IS_SUMMARY)) == 1)
                summaryNotificationId = cursor
                        .getInt(cursor.getColumnIndex(NotificationTable.COLUMN_NAME_ANDROID_NOTIFICATION_ID));
            else {
                String title = cursor.getString(cursor.getColumnIndex(NotificationTable.COLUMN_NAME_TITLE));
                if (title == null)
                    title = "";
                else
                    title += " ";

                // Html.fromHtml("<strong>" + line1Title + "</strong> " + gcmBundle.getString("alert"));

                String msg = cursor.getString(cursor.getColumnIndex(NotificationTable.COLUMN_NAME_MESSAGE));
                spannableString = new SpannableString(title + msg);
                if (title.length() > 0)
                    spannableString.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, title.length(),
                            0);
                summeryList.add(spannableString);

                if (firstFullData == null)
                    firstFullData = cursor
                            .getString(cursor.getColumnIndex(NotificationTable.COLUMN_NAME_FULL_DATA));
            }
        } while (cursor.moveToNext());

        if (updateSummary) {
            try {
                gcmBundle = new JSONObject(firstFullData);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    if (summeryList != null && (!updateSummary || summeryList.size() > 1)) {
        int notificationCount = summeryList.size() + (updateSummary ? 0 : 1);

        String summaryMessage = null;

        if (gcmBundle.has("grp_msg")) {
            try {
                summaryMessage = gcmBundle.getString("grp_msg").replace("$[notif_count]",
                        "" + notificationCount);
            } catch (Throwable t) {
            }
        }
        if (summaryMessage == null)
            summaryMessage = notificationCount + " new messages";

        JSONObject summaryDataBundle = new JSONObject();
        try {
            summaryDataBundle.put("alert", summaryMessage);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Intent summaryIntent = getNewBaseIntent(summaryNotificationId).putExtra("summary", group)
                .putExtra("onesignal_data", summaryDataBundle.toString());

        PendingIntent summaryContentIntent = getNewActionPendingIntent(random.nextInt(), summaryIntent);

        NotificationCompat.Builder summeryBuilder = getBaseNotificationCompatBuilder(gcmBundle, !updateSummary);

        summeryBuilder.setContentIntent(summaryContentIntent).setDeleteIntent(summaryDeleteIntent)
                .setContentTitle(currentContext.getPackageManager()
                        .getApplicationLabel(currentContext.getApplicationInfo()))
                .setContentText(summaryMessage).setNumber(notificationCount).setOnlyAlertOnce(updateSummary)
                .setGroup(group).setGroupSummary(true);

        if (!updateSummary)
            summeryBuilder.setTicker(summaryMessage);

        NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
        String line1Title = null;

        // Add the latest notification to the summary
        if (!updateSummary) {
            try {
                line1Title = gcmBundle.getString("title");
            } catch (Throwable t) {
            }

            if (line1Title == null)
                line1Title = "";
            else
                line1Title += " ";

            String message = "";
            try {
                message = gcmBundle.getString("alert");
            } catch (Throwable t) {
            }

            SpannableString spannableString = new SpannableString(line1Title + message);
            if (line1Title.length() > 0)
                spannableString.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, line1Title.length(),
                        0);
            inboxStyle.addLine(spannableString);
        }

        for (SpannableString line : summeryList)
            inboxStyle.addLine(line);
        inboxStyle.setBigContentTitle(summaryMessage);
        summeryBuilder.setStyle(inboxStyle);

        summaryNotification = summeryBuilder.build();
    } else {
        // There currently isn't a visible notification from this group, save the group summary notification id and post it so it looks like a normal notification.
        ContentValues values = new ContentValues();
        values.put(NotificationTable.COLUMN_NAME_ANDROID_NOTIFICATION_ID, summaryNotificationId);
        values.put(NotificationTable.COLUMN_NAME_GROUP_ID, group);
        values.put(NotificationTable.COLUMN_NAME_IS_SUMMARY, 1);

        writableDb.insert(NotificationTable.TABLE_NAME, null, values);

        NotificationCompat.Builder notifBuilder = getBaseNotificationCompatBuilder(gcmBundle, !updateSummary);

        PendingIntent summaryContentIntent = getNewActionPendingIntent(random.nextInt(),
                getNewBaseIntent(summaryNotificationId).putExtra("onesignal_data", gcmBundle.toString())
                        .putExtra("summary", group));

        addNotificationActionButtons(gcmBundle, notifBuilder, summaryNotificationId, group);
        notifBuilder.setContentIntent(summaryContentIntent).setDeleteIntent(summaryDeleteIntent)
                .setOnlyAlertOnce(updateSummary).setGroup(group).setGroupSummary(true);

        summaryNotification = notifBuilder.build();
    }

    NotificationManagerCompat.from(currentContext).notify(summaryNotificationId, summaryNotification);

    cursor.close();
    writableDb.close();
}

From source file:com.android.deskclock.timer.TimerReceiver.java

private void showTimesUpNotification(final Context context, TimerObj timerObj) {
    // Content Intent. When clicked will show the timer full screen
    PendingIntent contentIntent = PendingIntent.getActivity(context, timerObj.mTimerId,
            new Intent(context, TimerAlertFullScreen.class).putExtra(Timers.TIMER_INTENT_EXTRA,
                    timerObj.mTimerId),/*from  ww w  .ja  v a  2 s .c o m*/
            PendingIntent.FLAG_UPDATE_CURRENT);

    // Add one minute action button
    PendingIntent addOneMinuteAction = PendingIntent.getBroadcast(context, timerObj.mTimerId,
            new Intent(Timers.NOTIF_TIMES_UP_PLUS_ONE).putExtra(Timers.TIMER_INTENT_EXTRA, timerObj.mTimerId),
            PendingIntent.FLAG_UPDATE_CURRENT);

    // Add stop/done action button
    PendingIntent stopIntent = PendingIntent.getBroadcast(context, timerObj.mTimerId,
            new Intent(Timers.NOTIF_TIMES_UP_STOP).putExtra(Timers.TIMER_INTENT_EXTRA, timerObj.mTimerId),
            PendingIntent.FLAG_UPDATE_CURRENT);

    // Notification creation
    final NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
            .setContentIntent(contentIntent)
            .addAction(R.drawable.ic_add_24dp, context.getResources().getString(R.string.timer_plus_1_min),
                    addOneMinuteAction)
            .addAction(
                    timerObj.getDeleteAfterUse() ? android.R.drawable.ic_menu_close_clear_cancel
                            : R.drawable.ic_stop_24dp,
                    timerObj.getDeleteAfterUse() ? context.getResources().getString(R.string.timer_done)
                            : context.getResources().getString(R.string.timer_stop),
                    stopIntent)
            .setContentTitle(timerObj.getLabelOrDefault(context))
            .setContentText(context.getResources().getString(R.string.timer_times_up))
            .setSmallIcon(R.drawable.stat_notify_timer).setOngoing(true).setAutoCancel(false)
            .setPriority(NotificationCompat.PRIORITY_MAX).setDefaults(NotificationCompat.DEFAULT_LIGHTS)
            .setWhen(0);

    // Send the notification using the timer's id to identify the
    // correct notification
    NotificationManagerCompat.from(context).notify(timerObj.mTimerId, builder.build());
    if (Timers.LOGGING) {
        Log.v(TAG, "Setting times-up notification for " + timerObj.getLabelOrDefault(context) + " #"
                + timerObj.mTimerId);
    }
}

From source file:com.adkdevelopment.earthquakesurvival.data.syncadapter.SyncAdapter.java

/**
 * Raises a notification with a biggest earthquake with each sync
 *
 * @param notifyValues data with the biggest recent earthquake
 *///from  ww  w.  j a  v  a  2s  .  co m
private void sendNotification(ContentValues notifyValues) {

    Context context = getContext();

    if (Utilities.getNotificationsPrefs(context) && !Utilities.checkForeground(context)) {

        //checking the last update and notify if it' the first of the day
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        String lastNotificationKey = context.getString(R.string.sharedprefs_key_lastnotification);
        long lastSync = prefs.getLong(lastNotificationKey, 0);

        if (System.currentTimeMillis() - lastSync >= DateUtils.DAY_IN_MILLIS) {
            Intent intent = new Intent(context, DetailActivity.class);

            double latitude = notifyValues.getAsDouble(EarthquakeColumns.LATITUDE);
            double longitude = notifyValues.getAsDouble(EarthquakeColumns.LONGITUDE);
            LatLng latLng = new LatLng(latitude, longitude);

            String distance = context.getString(R.string.earthquake_distance,
                    LocationUtils.getDistance(latLng, LocationUtils.getLocation(context)));

            String magnitude = context.getString(R.string.earthquake_magnitude,
                    notifyValues.getAsDouble(EarthquakeColumns.MAG));
            String date = Utilities.getRelativeDate(notifyValues.getAsLong(EarthquakeColumns.TIME));

            double depth = notifyValues.getAsDouble(EarthquakeColumns.DEPTH);

            intent.putExtra(Feature.MAGNITUDE, notifyValues.getAsDouble(EarthquakeColumns.MAG));
            intent.putExtra(Feature.PLACE, notifyValues.getAsString(EarthquakeColumns.PLACE));
            intent.putExtra(Feature.DATE, date);
            intent.putExtra(Feature.LINK, notifyValues.getAsString(EarthquakeColumns.URL));
            intent.putExtra(Feature.LATLNG, latLng);
            intent.putExtra(Feature.DISTANCE, distance);
            intent.putExtra(Feature.DEPTH, depth);
            intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

            PendingIntent pendingIntent = PendingIntent.getActivity(context, EarthquakeObject.NOTIFICATION_ID_1,
                    intent, PendingIntent.FLAG_UPDATE_CURRENT);

            NotificationCompat.Builder builder = new NotificationCompat.Builder(context);

            Bitmap largeIcon = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher);

            builder.setDefaults(Notification.DEFAULT_ALL).setAutoCancel(true)
                    .setContentTitle(context.getString(R.string.earthquake_statistics_largest))
                    .setContentText(context.getString(R.string.earthquake_magnitude,
                            notifyValues.get(EarthquakeColumns.MAG)))
                    .setContentIntent(pendingIntent).setSmallIcon(R.drawable.ic_info_black_24dp)
                    .setLargeIcon(largeIcon).setTicker(context.getString(R.string.app_name))
                    .setStyle(new NotificationCompat.BigTextStyle()
                            .bigText(notifyValues.get(EarthquakeColumns.PLACE).toString() + "\n" + magnitude
                                    + "\n" + context.getString(R.string.earthquake_depth, depth) + "\n"
                                    + distance + "\n" + date))
                    .setGroup(EarthquakeObject.NOTIFICATION_GROUP).setGroupSummary(true);

            NotificationManagerCompat managerCompat = NotificationManagerCompat.from(context);
            managerCompat.notify(EarthquakeObject.NOTIFICATION_ID_1, builder.build());

            //refreshing last sync
            boolean success = prefs.edit().putLong(lastNotificationKey, System.currentTimeMillis()).commit();
        }
    }
}

From source file:com.android.deskclock.timer.TimerReceiver.java

private void cancelTimesUpNotification(final Context context, TimerObj timerObj) {
    NotificationManagerCompat.from(context).cancel(timerObj.mTimerId);
    if (Timers.LOGGING) {
        Log.v(TAG, "Canceling times-up notification for " + timerObj.getLabelOrDefault(context) + " #"
                + timerObj.mTimerId);/* www  . j  av a  2  s .  com*/
    }
}

From source file:com.irccloud.android.data.collection.NotificationsList.java

private void showOtherNotifications() {
    String title = "";
    String text = "";
    String ticker;/*from w  ww.  ja  va2 s . co  m*/
    NotificationCompat.Action action = null;
    SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext());
    final List<Notification> notifications = getOtherNotifications();

    int notify_type = Integer.parseInt(prefs.getString("notify_type", "1"));
    boolean notify = false;
    if (notify_type == 1 || (notify_type == 2 && NetworkConnection.getInstance().isVisible()))
        notify = true;

    if (notifications.size() > 0 && notify) {
        for (Notification n : notifications) {
            if (!n.shown) {
                Crashlytics.log(Log.DEBUG, "IRCCloud", "Posting notification for type " + n.message_type);
                if (n.message_type.equals("callerid")) {
                    title = n.network;
                    text = n.nick + " is trying to contact you";
                    ticker = n.nick + " is trying to contact you on " + n.network;

                    Intent i = new Intent(RemoteInputService.ACTION_REPLY);
                    i.setComponent(new ComponentName(
                            IRCCloudApplication.getInstance().getApplicationContext().getPackageName(),
                            RemoteInputService.class.getName()));
                    i.putExtra("cid", n.cid);
                    i.putExtra("eid", n.eid);
                    i.putExtra("chan", n.chan);
                    i.putExtra("buffer_type", n.buffer_type);
                    i.putExtra("network", n.network);
                    i.putExtra("to", n.nick);
                    i.putExtra("reply", "/accept " + n.nick);
                    action = new NotificationCompat.Action(R.drawable.ic_wearable_add, "Accept",
                            PendingIntent.getService(IRCCloudApplication.getInstance().getApplicationContext(),
                                    (int) (n.eid / 1000), i, PendingIntent.FLAG_UPDATE_CURRENT));
                } else if (n.message_type.equals("callerid_success")) {
                    title = n.network;
                    text = n.nick + " has been added to your accept list";
                    ticker = n.nick + " has been added to your accept list on " + n.network;
                    Intent i = new Intent(RemoteInputService.ACTION_REPLY);
                    i.setComponent(new ComponentName(
                            IRCCloudApplication.getInstance().getApplicationContext().getPackageName(),
                            RemoteInputService.class.getName()));
                    i.putExtra("cid", n.cid);
                    i.putExtra("eid", n.eid);
                    i.putExtra("chan", n.chan);
                    i.putExtra("buffer_type", n.buffer_type);
                    i.putExtra("network", n.network);
                    i.putExtra("to", n.nick);
                    action = new NotificationCompat.Action.Builder(R.drawable.ic_wearable_reply, "Message",
                            PendingIntent.getService(IRCCloudApplication.getInstance().getApplicationContext(),
                                    (int) (n.eid / 1000), i, PendingIntent.FLAG_UPDATE_CURRENT))
                                            .setAllowGeneratedReplies(true)
                                            .addRemoteInput(new RemoteInput.Builder("extra_reply")
                                                    .setLabel("Message to " + n.nick).build())
                                            .build();
                } else if (n.message_type.equals("channel_invite")) {
                    title = n.network;
                    text = n.nick + " invited you to join " + n.chan;
                    ticker = text;
                    try {
                        Intent i = new Intent();
                        i.setComponent(new ComponentName(
                                IRCCloudApplication.getInstance().getApplicationContext().getPackageName(),
                                "com.irccloud.android.MainActivity"));
                        i.setData(Uri.parse(IRCCloudApplication.getInstance().getResources()
                                .getString(R.string.IRCCLOUD_SCHEME) + "://cid/" + n.cid + "/"
                                + URLEncoder.encode(n.chan, "UTF-8")));
                        i.putExtra("eid", n.eid);
                        action = new NotificationCompat.Action(R.drawable.ic_wearable_add, "Join",
                                PendingIntent.getActivity(
                                        IRCCloudApplication.getInstance().getApplicationContext(),
                                        (int) (n.eid / 1000), i, PendingIntent.FLAG_UPDATE_CURRENT));
                    } catch (Exception e) {
                        action = null;
                    }
                } else {
                    title = n.nick;
                    text = n.message;
                    ticker = n.message;
                    action = null;
                }
                if (title != null && text != null)
                    NotificationManagerCompat.from(IRCCloudApplication.getInstance().getApplicationContext())
                            .notify((int) (n.eid / 1000), buildNotification(ticker, n.cid, n.bid,
                                    new long[] { n.eid }, title, text, 1, null, n.network, null, action,
                                    AvatarsList.getInstance().getAvatar(n.cid, n.nick).getBitmap(false,
                                            (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 64,
                                                    IRCCloudApplication.getInstance().getApplicationContext()
                                                            .getResources().getDisplayMetrics()),
                                            false, Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP),
                                    AvatarsList.getInstance().getAvatar(n.cid, n.nick).getBitmap(false, 400,
                                            false, false)));
            }
        }
        TransactionManager.transact(IRCCloudDatabase.NAME, new Runnable() {
            @Override
            public void run() {
                for (Notification n : notifications) {
                    n.delete();
                }
            }
        });
    }
}