Example usage for android.app PendingIntent FLAG_CANCEL_CURRENT

List of usage examples for android.app PendingIntent FLAG_CANCEL_CURRENT

Introduction

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

Prototype

int FLAG_CANCEL_CURRENT

To view the source code for android.app PendingIntent FLAG_CANCEL_CURRENT.

Click Source Link

Document

Flag indicating that if the described PendingIntent already exists, the current one should be canceled before generating a new one.

Usage

From source file:com.geecko.QuickLyric.broadcastReceiver.MusicBroadcastReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    /** Google Play Music
     //bool streaming            long position
     //long albumId               String album
     //bool currentSongLoaded      String track
     //long ListPosition         long ListSize
     //long id                  bool playing
     //long duration            int previewPlayType
     //bool supportsRating         int domain
     //bool albumArtFromService      String artist
     //int rating               bool local
     //bool preparing            bool inErrorState
     */// w w  w.j  a v a 2  s.c o  m

    Bundle extras = intent.getExtras();
    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
    boolean lengthFilter = sharedPref.getBoolean("pref_filter_20min", true);

    if (extras != null)
        try {
            extras.getInt("state");
        } catch (BadParcelableException e) {
            return;
        }

    if (extras == null || extras.getInt("state") > 1 //Tracks longer than 20min are presumably not songs
            || (lengthFilter && (extras.get("duration") instanceof Long && extras.getLong("duration") > 1200000)
                    || (extras.get("duration") instanceof Double && extras.getDouble("duration") > 1200000)
                    || (extras.get("duration") instanceof Integer && extras.getInt("duration") > 1200))
            || (lengthFilter && (extras.get("secs") instanceof Long && extras.getLong("secs") > 1200000)
                    || (extras.get("secs") instanceof Double && extras.getDouble("secs") > 1200000)
                    || (extras.get("secs") instanceof Integer && extras.getInt("secs") > 1200))
            || (extras.containsKey("com.maxmpz.audioplayer.source") && Build.VERSION.SDK_INT >= 19))
        return;

    String artist = extras.getString("artist");
    String track = extras.getString("track");
    long position = extras.containsKey("position") && extras.get("position") instanceof Long
            ? extras.getLong("position")
            : -1;
    if (extras.get("position") instanceof Double)
        position = Double.valueOf(extras.getDouble("position")).longValue();
    boolean isPlaying = extras.getBoolean(extras.containsKey("playstate") ? "playstate" : "playing", true);

    if (intent.getAction().equals("com.amazon.mp3.metachanged")) {
        artist = extras.getString("com.amazon.mp3.artist");
        track = extras.getString("com.amazon.mp3.track");
    } else if (intent.getAction().equals("com.spotify.music.metadatachanged"))
        isPlaying = spotifyPlaying;
    else if (intent.getAction().equals("com.spotify.music.playbackstatechanged"))
        spotifyPlaying = isPlaying;

    if ((artist == null || "".equals(artist)) //Could be problematic
            || (track == null || "".equals(track) || track.startsWith("DTNS"))) // Ignore one of my favorite podcasts
        return;

    SharedPreferences current = context.getSharedPreferences("current_music", Context.MODE_PRIVATE);
    String currentArtist = current.getString("artist", "");
    String currentTrack = current.getString("track", "");

    SharedPreferences.Editor editor = current.edit();
    editor.putString("artist", artist);
    editor.putString("track", track);
    if (!(artist.equals(currentArtist) && track.equals(currentTrack) && position == -1))
        editor.putLong("position", position);
    editor.putBoolean("playing", isPlaying);
    if (isPlaying) {
        long currentTime = System.currentTimeMillis();
        editor.putLong("startTime", currentTime);
    }
    editor.apply();

    autoUpdate = autoUpdate || sharedPref.getBoolean("pref_auto_refresh", false);
    int notificationPref = Integer.valueOf(sharedPref.getString("pref_notifications", "0"));

    if (autoUpdate && App.isActivityVisible()) {
        Intent internalIntent = new Intent("Broadcast");
        internalIntent.putExtra("artist", artist).putExtra("track", track);
        LyricsViewFragment.sendIntent(context, internalIntent);
        forceAutoUpdate(false);
    }

    boolean inDatabase = DatabaseHelper.getInstance(context)
            .presenceCheck(new String[] { artist, track, artist, track });

    if (notificationPref != 0 && isPlaying && (inDatabase || OnlineAccessVerifier.check(context))) {
        Intent activityIntent = new Intent("com.geecko.QuickLyric.getLyrics").putExtra("TAGS",
                new String[] { artist, track });
        Intent wearableIntent = new Intent("com.geecko.QuickLyric.SEND_TO_WEARABLE").putExtra("artist", artist)
                .putExtra("track", track);
        PendingIntent openAppPending = PendingIntent.getActivity(context, 0, activityIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);
        PendingIntent wearablePending = PendingIntent.getBroadcast(context, 8, wearableIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        NotificationCompat.Action wearableAction = new NotificationCompat.Action.Builder(R.drawable.ic_watch,
                context.getString(R.string.wearable_prompt), wearablePending).build();

        NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(context);
        NotificationCompat.Builder wearableNotifBuilder = new NotificationCompat.Builder(context);

        int[] themes = new int[] { R.style.Theme_QuickLyric, R.style.Theme_QuickLyric_Red,
                R.style.Theme_QuickLyric_Purple, R.style.Theme_QuickLyric_Indigo,
                R.style.Theme_QuickLyric_Green, R.style.Theme_QuickLyric_Lime, R.style.Theme_QuickLyric_Brown,
                R.style.Theme_QuickLyric_Dark };
        int themeNum = Integer.valueOf(sharedPref.getString("pref_theme", "0"));

        TypedValue primaryColorValue = new TypedValue();
        context.setTheme(themes[themeNum]);
        context.getTheme().resolveAttribute(R.attr.colorPrimary, primaryColorValue, true);

        notifBuilder.setSmallIcon(R.drawable.ic_notif).setContentTitle(context.getString(R.string.app_name))
                .setContentText(String.format("%s - %s", artist, track)).setContentIntent(openAppPending)
                .setVisibility(-1) // Notification.VISIBILITY_SECRET
                .setGroup("Lyrics_Notification").setColor(primaryColorValue.data).setGroupSummary(true);

        wearableNotifBuilder.setSmallIcon(R.drawable.ic_notif)
                .setContentTitle(context.getString(R.string.app_name))
                .setContentText(String.format("%s - %s", artist, track)).setContentIntent(openAppPending)
                .setVisibility(-1) // Notification.VISIBILITY_SECRET
                .setGroup("Lyrics_Notification").setOngoing(false).setColor(primaryColorValue.data)
                .setGroupSummary(false)
                .extend(new NotificationCompat.WearableExtender().addAction(wearableAction));

        if (notificationPref == 2) {
            notifBuilder.setOngoing(true).setPriority(-2); // Notification.PRIORITY_MIN
            wearableNotifBuilder.setPriority(-2);
        } else
            notifBuilder.setPriority(-1); // Notification.PRIORITY_LOW

        Notification notif = notifBuilder.build();
        Notification wearableNotif = wearableNotifBuilder.build();

        if (notificationPref == 2)
            notif.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;
        else
            notif.flags |= Notification.FLAG_AUTO_CANCEL;

        NotificationManagerCompat.from(context).notify(0, notif);
        try {
            context.getPackageManager().getPackageInfo("com.google.android.wearable.app",
                    PackageManager.GET_META_DATA);
            NotificationManagerCompat.from(context).notify(8, wearableNotif);
        } catch (PackageManager.NameNotFoundException ignored) {
        }
    } else if (track.equals(current.getString("track", "")))
        NotificationManagerCompat.from(context).cancel(0);
}

From source file:com.maass.android.imgur_uploader.ImgurUpload.java

private void handleResponse() {
    Log.i(this.getClass().getName(), "in handleResponse()");
    // close progress notification
    mNotificationManager.cancel(NOTIFICATION_ID);

    String notificationMessage = getString(R.string.upload_success);

    // notification intent with result
    final Intent notificationIntent = new Intent(getBaseContext(), ImageDetails.class);

    if (mImgurResponse == null) {
        notificationMessage = getString(R.string.connection_failed);
    } else if (mImgurResponse.get("error") != null) {
        notificationMessage = getString(R.string.unknown_error) + mImgurResponse.get("error");
    } else {/*from   ww w  .java  2  s  .c  om*/
        // create thumbnail
        if (mImgurResponse.get("image_hash").length() > 0) {
            createThumbnail(imageLocation);
        }

        // store result in database
        final HistoryDatabase histData = new HistoryDatabase(getBaseContext());
        final SQLiteDatabase data = histData.getWritableDatabase();

        final HashMap<String, String> dataToSave = new HashMap<String, String>();
        dataToSave.put("delete_hash", mImgurResponse.get("delete_hash"));
        dataToSave.put("image_url", mImgurResponse.get("original"));
        final Uri imageUri = Uri
                .parse(getFilesDir() + "/" + mImgurResponse.get("image_hash") + THUMBNAIL_POSTFIX);
        dataToSave.put("local_thumbnail", imageUri.toString());
        dataToSave.put("upload_time", "" + System.currentTimeMillis());

        for (final Map.Entry<String, String> entry : dataToSave.entrySet()) {
            final ContentValues content = new ContentValues();
            content.put("hash", mImgurResponse.get("image_hash"));
            content.put("key", entry.getKey());
            content.put("value", entry.getValue());
            data.insert("imgur_history", null, content);
        }

        //set intent to go to image details
        notificationIntent.putExtra("hash", mImgurResponse.get("image_hash"));
        notificationIntent.putExtra("image_url", mImgurResponse.get("original"));
        notificationIntent.putExtra("delete_hash", mImgurResponse.get("delete_hash"));
        notificationIntent.putExtra("local_thumbnail", imageUri.toString());

        data.close();
        histData.close();

        // if the main activity is already open then refresh the gridview
        sendBroadcast(new Intent(BROADCAST_ACTION));
    }

    //assemble notification
    final Notification notification = new Notification(R.drawable.icon, notificationMessage,
            System.currentTimeMillis());
    notification.setLatestEventInfo(this, getString(R.string.app_name), notificationMessage, PendingIntent
            .getActivity(getBaseContext(), 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT));
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    mNotificationManager.notify(NOTIFICATION_ID, notification);

}

From source file:com.commontime.plugin.notification.notification.Builder.java

/**
 * Set intent to handle the action click event. Will bring the app to
 * foreground.//www.j a  v  a  2  s .c  o m
 *
 * @param builder
 *      Local notification builder instance
 */
private void applyActionReceiver(NotificationCompat.Builder builder) {

    if (actionClickActivity == null)
        return;

    try {
        for (int i = 0; i < options.getCategoryActionCount(); i++) {
            JSONObject action = options.getCategoryAction(i);

            Intent intent = new Intent(context, actionClickActivity).putExtra(Options.EXTRA, options.toString())
                    .putExtra(ActionClickActivity.ACTION_PARAM, action.toString())
                    .setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

            int requestCode = new Random().nextInt();

            PendingIntent actionIntent = PendingIntent.getActivity(context, requestCode, intent,
                    PendingIntent.FLAG_CANCEL_CURRENT);

            builder.addAction(new NotificationCompat.Action(
                    context.getResources().getIdentifier("action_hand", "drawable", context.getPackageName()),
                    action.getString("title"), actionIntent));
        }
    } catch (Exception e) {
    }
}

From source file:org.servDroid.server.service.ServerService.java

/**
 * This function displays the notifications
 *//* w  w  w  .  ja va2s.c om*/
private void showRunningNotification() {
    if (null == mNotificationManager) {
        mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    }
    if (!mPreferenceHelper.getShowNotification()) {
        return;
    }

    Context context = getApplicationContext();

    Intent notificationIntent = new Intent(context, StartActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(context, START_NOTIFICATION_ID, notificationIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);

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

    Resources res = context.getResources();
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);

    builder.setContentIntent(contentIntent).setSmallIcon(R.drawable.icon).setOngoing(true).setAutoCancel(false)
            .setWhen(System.currentTimeMillis()).setContentTitle(res.getString(R.string.app_name))
            .setContentText(res.getString(R.string.text_running));
    Notification n = builder.build();

    nm.notify(START_NOTIFICATION_ID, n);

}

From source file:com.nsqre.insquare.Utilities.PushNotification.MyGcmListenerService.java

/**
 * Create and show a simple notification containing the received GCM message.
 * Manages how the notification will be shown in the notification bar.
 * @param message GCM message received.//w ww .  j a  v a  2  s  .  co m
 */
private void sendNotification(String message, String squareName, String squareId) {
    Intent intent = new Intent(this, BottomNavActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

    SharedPreferences notificationPreferences = getSharedPreferences("NOTIFICATION_MAP", MODE_PRIVATE);
    int notificationCount = 0;
    int squareCount = notificationPreferences.getInt("squareCount", 0);

    if (squareId.equals(notificationPreferences.getString("actualSquare", ""))) {
        return;
    }

    if (!notificationPreferences.contains(squareId)) {
        notificationPreferences.edit().putInt("squareCount", squareCount + 1).apply();
    }
    notificationPreferences.edit().putInt(squareId, notificationPreferences.getInt(squareId, 0) + 1).apply();

    for (String square : notificationPreferences.getAll().keySet()) {
        if (!"squareCount".equals(square) && !"actualSquare".equals(square)) {
            notificationCount += notificationPreferences.getInt(square, 0);
        }
    }

    squareCount = notificationPreferences.getInt("squareCount", 0);

    Log.d(TAG, notificationPreferences.getAll().toString());

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

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
    notificationBuilder.setSmallIcon(R.drawable.nsqre_map_pin_empty_inside);
    notificationBuilder.setColor(ContextCompat.getColor(getApplicationContext(), R.color.colorAccent));

    if (squareCount == 1) {
        SharedPreferences messagePreferences = getSharedPreferences(squareId, MODE_PRIVATE);
        intent.putExtra("squareId", squareId);
        NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
        messagePreferences.edit().putString(String.valueOf(notificationCount), message).commit();
        if (messagePreferences.getAll().size() <= 6) {
            for (int i = 1; i <= messagePreferences.getAll().keySet().size(); i++) {
                inboxStyle.addLine(messagePreferences.getString(String.valueOf(i), ""));
            }
        } else {
            for (int i = messagePreferences.getAll().size() - 6; i <= messagePreferences.getAll().keySet()
                    .size(); i++) {
                inboxStyle.addLine(messagePreferences.getString(String.valueOf(i), ""));
            }
        }
        notificationBuilder.setContentTitle(squareName);
        notificationBuilder.setStyle(inboxStyle.setBigContentTitle(squareName).setSummaryText("inSquare"));
        notificationBuilder.setContentText(
                notificationCount > 1 ? "Hai " + notificationCount + " nuovi messaggi" : message);
    } else {
        intent.putExtra("map", 0);
        intent.removeExtra("squareId");
        notificationBuilder.setContentTitle("inSquare");
        notificationBuilder
                .setContentText("Hai " + (notificationCount) + " nuovi messaggi in " + squareCount + " piazze");
    }
    notificationBuilder.setAutoCancel(true);
    notificationBuilder.setSound(defaultSoundUri);
    notificationBuilder.setVibrate(new long[] { 300, 300, 300, 300, 300 });
    notificationBuilder.setLights(Color.RED, 1000, 3000);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_CANCEL_CURRENT);
    notificationBuilder.setContentIntent(pendingIntent);

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

    updateSquares("", "", "update");

    SharedPreferences mutePreferences = getSharedPreferences("NOTIFICATION_MUTE_MAP", MODE_PRIVATE);

    if (mutePreferences.contains(squareId)) {

        String expireDate = mutePreferences.getString(squareId, "");

        long myExpireDate = Long.parseLong(expireDate, 10);
        if (myExpireDate < (new Date().getTime())) {
            mutePreferences.edit().remove(squareId).apply();
            notificationManager.notify(0, notificationBuilder.build());
        }

    } else {

        notificationManager.notify(0, notificationBuilder.build());
    }

}

From source file:com.ayogo.cordova.notification.ScheduledNotificationManager.java

public ScheduledNotification cancelNotification(String tag) {
    LOG.v(NotificationPlugin.TAG, "cancelNotification: " + tag);
    SharedPreferences prefs = getPrefs();
    SharedPreferences.Editor editor = prefs.edit();

    Map<String, ?> notifications = prefs.getAll();
    ScheduledNotification notification = null;

    for (String key : notifications.keySet()) {
        try {/* w w  w. ja va 2  s .c  o m*/
            JSONObject value = new JSONObject(notifications.get(key).toString());
            String ntag = value.optString("tag");
            LOG.v(NotificationPlugin.TAG, "checking Notification: " + value.toString());
            if (ntag != null && ntag.equals(tag)) {
                LOG.v(NotificationPlugin.TAG, "found Notification: " + value.toString());
                notification = new ScheduledNotification(value.optString("title", null), value);

                editor.remove(key);

                LOG.v(NotificationPlugin.TAG, "unscheduling Notification: ");
                //unschedule the alarm
                Intent intent = new Intent(context, TriggerReceiver.class);
                intent.setAction(ntag);

                PendingIntent pi = PendingIntent.getBroadcast(context, INTENT_REQUEST_CODE, intent,
                        PendingIntent.FLAG_CANCEL_CURRENT);

                AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
                alarmManager.cancel(pi);
            }
        } catch (JSONException e) {
        }
    }

    editor.commit();

    if (notification != null) {
        LOG.v(NotificationPlugin.TAG, "returning Notification " + notification.toString());
    } else {
        LOG.v(NotificationPlugin.TAG, "could not find Notification " + tag);
    }

    return notification;
}

From source file:net.pmarks.chromadoze.NoiseService.java

private void addButtonToNotification(Notification n) {
    // Create a new RV with a Stop button.
    RemoteViews rv = new RemoteViews(getPackageName(), R.layout.notification_with_stop_button);
    PendingIntent pendingIntent = PendingIntent.getService(this, 0,
            newStopIntent(this, R.string.stop_reason_notification), PendingIntent.FLAG_CANCEL_CURRENT);
    rv.setOnClickPendingIntent(R.id.stop_button, pendingIntent);

    // Pre-render the original RV, and copy some of the colors.
    final View inflated = n.contentView.apply(this, new FrameLayout(this));
    final TextView titleText = findTextView(inflated, getString(R.string.app_name));
    final TextView defaultText = findTextView(inflated, getString(R.string.notification_text));
    rv.setInt(R.id.divider, "setBackgroundColor", defaultText.getTextColors().getDefaultColor());
    rv.setInt(R.id.stop_button_square, "setBackgroundColor", titleText.getTextColors().getDefaultColor());

    // Insert a copy of the original RV into the new one.
    rv.addView(R.id.notification_insert, n.contentView.clone());

    // Splice everything back into the original's root view.
    int id = Resources.getSystem().getIdentifier("status_bar_latest_event_content", "id", "android");
    n.contentView.removeAllViews(id);/* w w w. j  av  a2s . co  m*/
    n.contentView.addView(id, rv);
}

From source file:it.unicaradio.android.services.StreamingService.java

private Notification buildNotification(String title, String message) {
    Intent intent = new Intent(this, MainActivity.class);
    PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

    Builder b = new NotificationCompat.Builder(this);
    b.setContentTitle(title);/*from   w  ww . j  a  v a2s.c  o  m*/
    b.setContentText(message);
    b.setSmallIcon(R.drawable.ic_stat_notify);
    b.setTicker(MessageFormat.format("{0}\n{1}", message, title));
    b.setContentIntent(pIntent);
    b.setWhen(System.currentTimeMillis());
    b.setOngoing(true);

    return b.build();
}

From source file:org.tomahawk.tomahawk_android.utils.MediaNotification.java

public MediaNotification(PlaybackService service) throws RemoteException {
    mService = service;/*from   w  w w . j  a v a  2 s.  c om*/
    updateSessionToken();

    mNotificationColor = mService.getResources().getColor(R.color.notification_bg);

    mNotificationManager = NotificationManagerCompat.from(mService);
    stopNotification();

    String pkg = mService.getPackageName();
    //        mIntents.put(R.drawable.ic_action_favorites_small, PendingIntent.getBroadcast(mService, 100,
    //                new Intent(ACTION_FAVORITE).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT));
    //        mIntents.put(R.drawable.ic_action_favorites_small_underlined,
    //                PendingIntent.getBroadcast(mService, 100, new Intent(ACTION_UNFAVORITE)
    //                        .setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT));
    mIntents.put(R.drawable.ic_av_pause, PendingIntent.getBroadcast(mService, 100,
            new Intent(ACTION_PAUSE).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT));
    mIntents.put(R.drawable.ic_av_play_arrow, PendingIntent.getBroadcast(mService, 100,
            new Intent(ACTION_PLAY).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT));
    mIntents.put(R.drawable.ic_player_previous_light, PendingIntent.getBroadcast(mService, 100,
            new Intent(ACTION_PREV).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT));
    mIntents.put(R.drawable.ic_player_next_light, PendingIntent.getBroadcast(mService, 100,
            new Intent(ACTION_NEXT).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT));
}

From source file:com.devbrackets.android.playlistcore.helper.MediaControlsHelper.java

@NonNull
protected PendingIntent getMediaButtonReceiverPendingIntent(@NonNull ComponentName componentName,
        @NonNull Class<? extends Service> serviceClass) {
    Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
    mediaButtonIntent.setComponent(componentName);

    mediaButtonIntent.putExtra(RECEIVER_EXTRA_CLASS, serviceClass.getName());
    return PendingIntent.getBroadcast(context, 0, mediaButtonIntent, PendingIntent.FLAG_CANCEL_CURRENT);
}