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:org.videolan.vlc.gui.video.PopupManager.java

private void showNotification() {
    PendingIntent piStop = PendingIntent.getBroadcast(mService, 0,
            new Intent(PlaybackService.ACTION_REMOTE_STOP), PendingIntent.FLAG_UPDATE_CURRENT);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(mService)
            .setSmallIcon(R.drawable.ic_stat_vlc).setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setContentTitle(mService.getTitle()).setContentText(mService.getString(R.string.popup_playback))
            .setAutoCancel(false).setOngoing(true).setDeleteIntent(piStop);

    //Switch//from www  .j a  v  a  2  s.  co  m
    final Intent notificationIntent = new Intent(PlaybackService.ACTION_REMOTE_SWITCH_VIDEO);
    PendingIntent piExpand = PendingIntent.getBroadcast(mService, 0, notificationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    //PLay Pause
    PendingIntent piPlay = PendingIntent.getBroadcast(mService, 0,
            new Intent(PlaybackService.ACTION_REMOTE_PLAYPAUSE), PendingIntent.FLAG_UPDATE_CURRENT);

    if (mService.isPlaying())
        builder.addAction(R.drawable.ic_popup_pause, mService.getString(R.string.pause), piPlay);
    else
        builder.addAction(R.drawable.ic_popup_play, mService.getString(R.string.play), piPlay);
    builder.addAction(R.drawable.ic_popup_expand_w, mService.getString(R.string.popup_expand), piExpand);

    Notification notification = builder.build();
    try {
        NotificationManagerCompat.from(mService).notify(42, notification);
    } catch (IllegalArgumentException e) {
    }
}

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  ww. j av  a 2s. c  o  m
    notification.defaults = defaults;

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

From source file:org.videolan.vlc.gui.video.PopupManager.java

private void hideNotification() {
    NotificationManagerCompat.from(mService).cancel(42);
}

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

public void deleteNotificationsForBid(int bid) {
    Log.d("IRCCloud", "Removing all notifications for bid" + bid);
    List<Notification> notifications = getOtherNotifications();

    if (notifications.size() > 0) {
        for (Notification n : notifications) {
            NotificationManagerCompat.from(IRCCloudApplication.getInstance().getApplicationContext())
                    .cancel((int) (n.eid / 1000));
        }/* ww w.  java 2s  .co  m*/
    }
    NotificationManagerCompat.from(IRCCloudApplication.getInstance().getApplicationContext()).cancel(bid);

    synchronized (dbLock) {
        notifications = getNotifications();
        for (Notification n : notifications) {
            if (n.bid == bid) {
                n.delete();
            }
        }
        new Delete().from(Notification_LastSeenEID.class)
                .where(Condition.column(Notification_LastSeenEID$Table.BID).is(bid)).queryClose();
    }
    IRCCloudApplication.getInstance().getApplicationContext()
            .sendBroadcast(new Intent(DashClock.REFRESH_INTENT));
    try {
        if (PreferenceManager
                .getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext())
                .getBoolean("notify_sony", false))
            NotificationUtil.deleteEvents(IRCCloudApplication.getInstance().getApplicationContext(),
                    com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.FRIEND_KEY
                            + " = ?",
                    new String[] { String.valueOf(bid) });
    } catch (Exception e) {
        //User has probably uninstalled Sony Liveware
    }
    updateTeslaUnreadCount();
}

From source file:com.somexapps.wyre.services.MediaService.java

private void buildNotification(android.support.v4.app.NotificationCompat.Action action) {
    // Initialize style
    NotificationCompat.MediaStyle style = new NotificationCompat.MediaStyle();

    // Build intent/pending intent
    Intent intent = new Intent(getApplicationContext(), MediaService.class);
    intent.setAction(ACTION_STOP);//from w ww  . j a  v a 2 s  .c o  m
    // TODO: Should this have 0 as the flag?
    PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(),
            MEDIA_NOTIFICATION_REQUEST_CODE, intent, 0);

    // Get notification manager
    final NotificationManagerCompat managerCompat = NotificationManagerCompat.from(getApplicationContext());

    // Create media notification
    final android.support.v4.app.NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_album_white_48dp))
            .setContentTitle(playingSong.getTitle()).setContentText(playingSong.getArtist())
            .setDeleteIntent(pendingIntent).setStyle(style);

    // Check to see if we have a next or previous song to play
    boolean previousDisabled = false;
    boolean nextDisabled = false;

    if (songsList.size() == 1) {
        previousDisabled = true;
        nextDisabled = true;
    } else if (playingSongIndex == 0) {
        previousDisabled = true;
    } else if (playingSongIndex == songsList.size() - 1) {
        nextDisabled = true;
    }

    // Add previous action if there is previous media
    if (!previousDisabled) {
        builder.addAction(generateAction(R.drawable.ic_skip_previous_white_36dp,
                getString(R.string.media_service_notification_prev), ACTION_PREVIOUS));
    }

    // Add play/pause action
    builder.addAction(action);

    // Add next action if there is next media
    if (!nextDisabled) {
        builder.addAction(generateAction(R.drawable.ic_skip_next_white_36dp,
                getString(R.string.media_service_notification_next), ACTION_NEXT));
    }

    // Show buttons based on state
    if (previousDisabled && nextDisabled) {
        style.setShowActionsInCompactView(0);
    } else if (previousDisabled || nextDisabled) {
        style.setShowActionsInCompactView(0, 1);
    } else {
        style.setShowActionsInCompactView(0, 1, 2);
    }

    /**
     * Check if we are going to a play state by checking to see if the middle
     * action is getting set to Pause
     */
    if (action.getTitle().equals(getString(R.string.media_service_notification_pause))) {
        builder.setOngoing(true);
    } else {
        builder.setOngoing(false);
    }

    // Check if we have a image path
    if (playingSong.getAlbumArtPath() != null && playingSong.getAlbumArtPath().startsWith("http")) {
        // Set up image target
        Target iconTarget = new Target() {
            @Override
            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                // Set icon
                builder.setLargeIcon(bitmap);

                // Update notification
                managerCompat.notify(MEDIA_NOTIFICATION_REQUEST_CODE, builder.build());
            }

            @Override
            public void onBitmapFailed(Drawable errorDrawable) {
                // do nothing
            }

            @Override
            public void onPrepareLoad(Drawable placeHolderDrawable) {
                // do nothing
            }
        };

        // Start the image load
        Picasso.with(getApplicationContext()).load(Uri.parse(playingSong.getAlbumArtPath())).into(iconTarget);
    }

    // Update the notification
    managerCompat.notify(MEDIA_NOTIFICATION_REQUEST_CODE, builder.build());
}

From source file:id.satusatudua.sigap.service.NotificationService.java

private void showNewMessageNotif(DataSnapshot dataSnapshot, boolean isGuarding) {
    if (!BenihUtils.isMyAppRunning(getApplicationContext(), getPackageName())) {
        String content = dataSnapshot.child("content").getValue().toString();
        boolean danger = false;
        if (content.startsWith("[DANGER]") && content.endsWith("[/DANGER]")) {
            danger = true;/*from  www.  j  a  v  a  2  s.  c o m*/
            content = content.replace("[DANGER]", "").replace("[/DANGER]", "");
        } else if (content.startsWith("[CLOSED]") && content.endsWith("[/CLOSED]")) {
            content = content.replace("[CLOSED]", "").replace("[/CLOSED]", "");
        } else if (content.startsWith("[INITIAL]") && content.endsWith("[/INITIAL]")) {
            content = content.replace("[INITIAL]", "").replace("[/INITIAL]", "");
        }
        PendingIntent pendingIntent;
        if (isGuarding) {
            pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0,
                    GuardingActivity.generateIntent(this), PendingIntent.FLAG_UPDATE_CURRENT);
        } else {
            pendingIntent = PendingIntent
                    .getActivity(getApplicationContext(), 0,
                            HelpingActivity.generateIntent(this, CacheManager.pluck().getLastHelpingCase(),
                                    CacheManager.pluck().getLastCaseReporter()),
                            PendingIntent.FLAG_UPDATE_CURRENT);
        }
        Notification notification = new NotificationCompat.Builder(getApplicationContext())
                .setContentTitle("Sigap")
                .setContentText(danger ? content : "Seseorang mengirimkan pesan baru kedalam percakapan!")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                .setVibrate(
                        CacheManager.pluck().isVibrate() ? new long[] { 100, 300, 500, 1000 } : new long[] {})
                .setSound(Uri.parse(CacheManager.pluck().getRingtone())).setAutoCancel(true)
                .setStyle(new android.support.v4.app.NotificationCompat.BigTextStyle().bigText(danger ? content
                        : "Seseorang mengirimkan pesan baru kedalam percakapan\nIsi pesan: " + content))
                .setContentIntent(pendingIntent).build();

        NotificationManagerCompat.from(SigapApp.pluck().getApplicationContext()).notify(396, notification);
    }
}

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

/**
 * Cancel the notification/*from w w w  . j av a  2s .c  o  m*/
 */
public static void cancelSecondaryUserNotification() {
    final NotificationManagerCompat notificationManager = NotificationManagerCompat
            .from(Factory.get().getApplicationContext());
    notificationManager.cancel(getNotificationTag(), PendingIntentConstants.SMS_SECONDARY_USER_NOTIFICATION_ID);
}

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

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

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

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

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

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

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

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

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

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

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

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

From source file:org.smssecure.smssecure.notifications.MessageNotifier.java

private static void sendSingleThreadNotification(Context context, MasterSecret masterSecret,
        NotificationState notificationState, int flags, boolean bundled) {
    if (notificationState.getNotifications().isEmpty()) {
        if (!bundled)
            cancelActiveNotifications(context);
        return;/*www .  j  ava  2s.  c  o  m*/
    }

    SingleRecipientNotificationBuilder builder = new SingleRecipientNotificationBuilder(context, masterSecret,
            SilencePreferences.getNotificationPrivacy(context));
    List<NotificationItem> notifications = notificationState.getNotifications();
    Recipients recipients = notifications.get(0).getRecipients();
    int notificationId = (int) (SUMMARY_NOTIFICATION_ID + (bundled ? notifications.get(0).getThreadId() : 0));

    builder.setThread(notifications.get(0).getRecipients());
    builder.setMessageCount(notificationState.getMessageCount());
    builder.setPrimaryMessageBody(recipients, notifications.get(0).getIndividualRecipient(),
            notifications.get(0).getText(), notifications.get(0).getSlideDeck());
    builder.setContentIntent(notifications.get(0).getPendingIntent(context));
    builder.setGroup(NOTIFICATION_GROUP);
    builder.setDeleteIntent(notificationState.getDeleteIntent(context));

    long timestamp = notifications.get(0).getTimestamp();
    if (timestamp != 0)
        builder.setWhen(timestamp);

    builder.addActions(masterSecret, notificationState.getMarkAsReadIntent(context, notificationId),
            notificationState.getQuickReplyIntent(context, notifications.get(0).getRecipients()),
            notificationState.getRemoteReplyIntent(context, notifications.get(0).getRecipients()));

    ListIterator<NotificationItem> iterator = notifications.listIterator(notifications.size());

    while (iterator.hasPrevious()) {
        NotificationItem item = iterator.previous();
        builder.addMessageBody(item.getRecipients(), item.getIndividualRecipient(), item.getText());
    }

    if (notificationsRequested(flags)) {
        triggerNotificationAlarms(builder, notificationState, flags);

        builder.setTicker(notifications.get(0).getIndividualRecipient(), notifications.get(0).getText());
    }

    if (!bundled) {
        builder.setGroupSummary(true);
    }

    NotificationManagerCompat.from(context).notify(notificationId, builder.build());
}

From source file:cx.ring.service.LocalService.java

@Override
public void onCreate() {
    Log.e(TAG, "onCreate");
    super.onCreate();

    mediaManager = new MediaManager(this);

    notificationManager = NotificationManagerCompat.from(this);

    final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
    final int cacheSize = maxMemory / 8;
    mMemoryCache = new LruCache<Long, Bitmap>(cacheSize) {
        @Override/*  w  w w.  j  a  v a2  s .c  om*/
        protected int sizeOf(Long key, Bitmap bitmap) {
            return bitmap.getByteCount() / 1024;
        }
    };

    historyManager = new HistoryManager(this);
    Intent intent = new Intent(this, DRingService.class);
    startService(intent);
    bindService(intent, mConnection, BIND_AUTO_CREATE | BIND_IMPORTANT | BIND_ABOVE_CLIENT);

    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo ni = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    isWifiConn = ni != null && ni.isConnected();
    ni = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    isMobileConn = ni != null && ni.isConnected();

    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    canUseContacts = sharedPreferences.getBoolean(SettingsFragment.KEY_PREF_CONTACTS, true);
    canUseMobile = sharedPreferences.getBoolean(SettingsFragment.KEY_PREF_MOBILE, true);
    sharedPreferences.registerOnSharedPreferenceChangeListener(this);
}