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:be.uhasselt.privacypolice.NotificationHandler.java

/**
 * Asks the user whether it is certain that a network should be currently available
 * @param SSID The name of the network//  w ww  .j av a  2  s .  c  o m
 * @param BSSID The MAC address of the access point that triggered this (only used when we will block the AP)
 */
public void askNetworkPermission(String SSID, String BSSID) {
    Log.d("PrivacyPolice", "Asking permission for " + SSID + " (" + BSSID + ")");
    // Intent that will be used when the user allows the network
    Intent addIntent = new Intent(ctx, PermissionChangeReceiver.class);
    addIntent.putExtra("SSID", SSID).putExtra("BSSID", BSSID).putExtra("enable", true);
    PendingIntent addPendingIntent = PendingIntent.getBroadcast(ctx, 0, addIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);
    // Intent that will be used when the user blocks the network
    Intent disableIntent = new Intent(ctx, PermissionChangeReceiver.class);
    disableIntent.putExtra("SSID", SSID).putExtra("BSSID", BSSID).putExtra("enable", false);
    PendingIntent disablePendingIntent = PendingIntent.getBroadcast(ctx, 1, disableIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);
    // Intent that will be used when the user's OS does not support notification actions
    Intent activityIntent = new Intent(ctx, AskPermissionActivity.class);
    activityIntent.putExtra("SSID", SSID).putExtra("BSSID", BSSID);
    PendingIntent activityPendingIntent = PendingIntent.getActivity(ctx, 2, activityIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);

    // Build the notification dynamically, based on the network name
    Resources res = ctx.getResources();
    String headerString = String.format(res.getString(R.string.permission_header), SSID);
    String permissionString = String.format(res.getString(R.string.ask_permission), SSID);
    String yes = res.getString(R.string.yes);
    String no = res.getString(R.string.no);

    // NotificationCompat makes sure that the notification will also work on Android <4.0
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(ctx)
            .setSmallIcon(R.drawable.ic_notification).setPriority(Notification.PRIORITY_MAX) // To force it to be first in list (and thus, expand)
            .setContentTitle(headerString).setContentText(permissionString)
            .setStyle(new NotificationCompat.BigTextStyle().bigText(permissionString))
            .setContentIntent(activityPendingIntent)
            .addAction(android.R.drawable.ic_delete, no, disablePendingIntent)
            .addAction(android.R.drawable.ic_input_add, yes, addPendingIntent);
    notificationManager.notify(0, mBuilder.build());
}

From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.IMObj.java

public void handleDirectMessage(Context context, Contact from, JSONObject obj) {
    Intent launch = new Intent();
    launch.setAction(Intent.ACTION_MAIN);
    launch.addCategory(Intent.CATEGORY_LAUNCHER);
    launch.setComponent(new ComponentName(context.getPackageName(), HomeActivity.class.getName()));
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, launch,
            PendingIntent.FLAG_CANCEL_CURRENT);
    String msg = obj.optString(TEXT);
    (new PresenceAwareNotify(context)).notify("IM from " + from.name, "IM from " + from.name, "\"" + msg + "\"",
            contentIntent);/* w w w. ja v a  2  s . c om*/
}

From source file:de.appplant.cordova.plugin.notification.NotificationBuilder.java

/**
 * Creates the notification.//  ww  w  .ja v a2 s . co  m
 */
@SuppressLint("NewApi")
public Builder buildNotification() {
    Uri sound = options.getSound();

    //DeleteIntent is called when the user clears a notification manually
    Intent deleteIntent = new Intent(context, deleteIntentReceiver).setAction("" + options.getId())
            .putExtra(OPTIONS, options.getJSONObject().toString());
    PendingIntent dpi = PendingIntent.getBroadcast(context, 0, deleteIntent, PendingIntent.FLAG_CANCEL_CURRENT);

    notification = new NotificationCompat.Builder(context).setDefaults(0) // Do not inherit any defaults
            .setContentTitle(options.getTitle()).setContentText(options.getMessage())
            .setNumber(options.getBadge()).setTicker(options.getMessage()).setSmallIcon(options.getSmallIcon())
            .setLargeIcon(options.getIcon()).setAutoCancel(options.getAutoCancel())
            .setOngoing(options.getOngoing()).setLights(options.getColor(), 500, 500).setDeleteIntent(dpi);

    if (sound != null) {
        notification.setSound(sound);
    }

    if (Build.VERSION.SDK_INT > 16) {
        notification.setStyle(new NotificationCompat.BigTextStyle().bigText(options.getMessage()));
    }

    setClickEvent(notification);

    return notification;
}

From source file:ca.rmen.android.networkmonitor.app.service.NetMonNotification.java

/**
 * A notification which has the following functionalities:
 * 1) Tapping on the notification opens the app in the main activity
 * 2) Tapping on the stop button of the notification stops the service
 * 3) Tapping on the logs button of the notification opens the log activity
 *//*  w ww. j  a v  a 2 s .  co  m*/
static Notification createOngoingNotification(Context context) {
    Log.v(TAG, "createNotification");
    context.registerReceiver(sDisableBroadcastReceiver, new IntentFilter(ACTION_DISABLE));
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
    builder.setOngoing(true);
    builder.setSmallIcon(R.drawable.ic_stat_service_running);
    builder.setTicker(context.getString(R.string.service_notification_ticker));
    builder.setContentTitle(context.getString(R.string.app_name));
    builder.setContentText(context.getString(R.string.service_notification_text));
    builder.setContentIntent(PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class),
            PendingIntent.FLAG_UPDATE_CURRENT));
    builder.addAction(R.drawable.ic_action_stop, context.getString(R.string.service_notification_action_stop),
            PendingIntent.getBroadcast(context, 0, new Intent(ACTION_DISABLE),
                    PendingIntent.FLAG_CANCEL_CURRENT));
    builder.addAction(R.drawable.ic_action_logs, context.getString(R.string.service_notification_action_logs),
            PendingIntent.getActivity(context, 0, new Intent(context, LogActivity.class),
                    PendingIntent.FLAG_UPDATE_CURRENT));
    builder.setColor(context.getResources().getColor(R.color.netmon_color));
    return builder.build();
}

From source file:com.keylesspalace.tusky.util.NotificationMaker.java

public static void make(final Context context, final int notifyId, Notification body) {
    final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    final SharedPreferences notificationPreferences = context.getSharedPreferences("Notifications",
            Context.MODE_PRIVATE);

    if (!filterNotification(preferences, body)) {
        return;//from w  w w .  j a va2  s .  c  o  m
    }

    String rawCurrentNotifications = notificationPreferences.getString("current", "[]");
    JSONArray currentNotifications;

    try {
        currentNotifications = new JSONArray(rawCurrentNotifications);
    } catch (JSONException e) {
        currentNotifications = new JSONArray();
    }

    boolean alreadyContains = false;

    for (int i = 0; i < currentNotifications.length(); i++) {
        try {
            if (currentNotifications.getString(i).equals(body.account.getDisplayName())) {
                alreadyContains = true;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    if (!alreadyContains) {
        currentNotifications.put(body.account.getDisplayName());
    }

    notificationPreferences.edit().putString("current", currentNotifications.toString()).commit();

    Intent resultIntent = new Intent(context, MainActivity.class);
    resultIntent.putExtra("tab_position", 1);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    stackBuilder.addParentStack(MainActivity.class);
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    Intent deleteIntent = new Intent(context, NotificationClearBroadcastReceiver.class);
    PendingIntent deletePendingIntent = PendingIntent.getBroadcast(context, 0, deleteIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);

    final NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.ic_notify).setContentIntent(resultPendingIntent)
            .setDeleteIntent(deletePendingIntent).setDefaults(0); // So it doesn't ring twice, notify only in Target callback

    if (currentNotifications.length() == 1) {
        builder.setContentTitle(titleForType(context, body))
                .setContentText(truncateWithEllipses(bodyForType(body), 40));

        Target mTarget = new Target() {
            @Override
            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                builder.setLargeIcon(bitmap);

                setupPreferences(preferences, builder);

                ((NotificationManager) (context.getSystemService(Context.NOTIFICATION_SERVICE)))
                        .notify(notifyId, builder.build());
            }

            @Override
            public void onBitmapFailed(Drawable errorDrawable) {
            }

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

        Picasso.with(context).load(body.account.avatar).placeholder(R.drawable.avatar_default)
                .transform(new RoundedTransformation(7, 0)).into(mTarget);
    } else {
        setupPreferences(preferences, builder);
        try {
            builder.setContentTitle(String.format(context.getString(R.string.notification_title_summary),
                    currentNotifications.length()))
                    .setContentText(truncateWithEllipses(joinNames(context, currentNotifications), 40));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        builder.setVisibility(android.app.Notification.VISIBILITY_PRIVATE);
        builder.setCategory(android.app.Notification.CATEGORY_SOCIAL);
    }

    ((NotificationManager) (context.getSystemService(Context.NOTIFICATION_SERVICE))).notify(notifyId,
            builder.build());
}

From source file:com.conferenceengineer.android.iosched.gcm.command.SyncCommand.java

private void scheduleSync(Context context, int syncJitter) {
    int jitterMillis = (int) (RANDOM.nextFloat() * syncJitter);
    final String debugMessage = "Scheduling next sync for " + jitterMillis + "ms";
    LOGI(TAG, debugMessage);//from  www  .  ja v  a 2  s.c o  m

    ((AlarmManager) context.getSystemService(Context.ALARM_SERVICE)).set(AlarmManager.RTC,
            System.currentTimeMillis() + jitterMillis, PendingIntent.getBroadcast(context, 0,
                    new Intent(context, TriggerSyncReceiver.class), PendingIntent.FLAG_CANCEL_CURRENT));

}

From source file:me.mcmadbat.laststats.MainActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    //TODO: find a better way to change users
    if (id == R.id.Change_User) {
        user.delete();//from w w  w. j  a v  a  2 s  .  c  o m
        Toast t = Toast.makeText(getApplicationContext(), "Please enter user again", Toast.LENGTH_SHORT);
        t.show();

        Intent mStartActivity = new Intent(getApplicationContext(), MainActivity.class);
        int mPendingIntentId = 123456;
        PendingIntent mPendingIntent = PendingIntent.getActivity(getApplicationContext(), mPendingIntentId,
                mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
        AlarmManager mgr = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
        System.exit(0);

        return true;
    }

    return super.onOptionsItemSelected(item);
}

From source file:es.usc.citius.servando.calendula.activities.PickupNotification.java

/**
 * Shows the notification, or updates a previously shown notification of
 * this type, with the given parameters.
 * <p/>/*w  w  w. j  a  va  2 s  . com*/
 * TODO: Customize this method's arguments to present relevant content in
 * the notification.
 * <p/>
 * TODO: Customize the contents of this method to tweak the behavior and
 * presentation of message notifications. Make
 * sure to follow the
 * <a href="https://developer.android.com/design/patterns/notifications.html">
 * Notification design guidelines</a> when doing so.
 *
 * @see #cancel(android.content.Context)
 */
public static void notify(final Context context, final String title, final String description, Intent intent) {

    final Resources res = context.getResources();

    // if notifications are disabled, exit
    // boolean notifications = PreferenceManager.getDefaultSharedPreferences(context).getBoolean("alarm_notifications", true);
    //        if (!notifications) {
    //            return;
    //        }

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    String delayMinutesStr = prefs.getString("alarm_repeat_frequency", "15");

    // This image is used as the notification's large icon (thumbnail).
    final Bitmap picture = BitmapFactory.decodeResource(res, R.drawable.ic_event_available_black_48dp);
    //final Bitmap largeIcon = BitmapFactory.decodeResource(res, R.drawable.ic_pill_48dp);

    NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
    style.setBigContentTitle(description);
    //style.setSummaryText("Notification Summary");

    final String ticker = title;
    final String text = title;

    PendingIntent defaultIntent = PendingIntent.getActivity(context, 0, intent,
            PendingIntent.FLAG_CANCEL_CURRENT);

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

            // Set appropriate defaults for the notification light, sound,
            // and vibration.
            .setDefaults(Notification.DEFAULT_ALL).setSmallIcon(R.drawable.ic_event_available_white_48dp)
            .setLargeIcon(picture).setContentTitle(title).setContentText(description).setAutoCancel(true)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT).setLargeIcon(picture).setTicker(ticker)
            .setContentIntent(defaultIntent).setStyle(style).setPriority(Notification.PRIORITY_DEFAULT)
            .setVibrate(new long[] { 1000, 200, 500, 200, 100, 200, 1000 })
            //.setSound(ringtoneUri != null ? ringtoneUri : Settings.System.DEFAULT_NOTIFICATION_URI)
            .setAutoCancel(true);

    Notification n = builder.build();
    n.defaults = 0;
    n.ledARGB = 0x00ffa500;
    n.ledOnMS = 1000;
    n.ledOffMS = 2000;
    notify(context, n);
}

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

@AnyThread
@Cat//from   ww w.j av  a  2 s.c o  m
static void showMain(@NonNull RelayService relay, @NonNull String content) {
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
            new Intent(context, WeechatActivity.class), PendingIntent.FLAG_CANCEL_CURRENT);

    boolean authenticated = relay.state.contains(AUTHENTICATED);
    int icon = authenticated ? R.drawable.ic_connected : R.drawable.ic_disconnected;

    Builder builder = new Builder(context, NOTIFICATION_CHANNEL_CONNECTION_STATUS);
    builder.setContentIntent(contentIntent).setSmallIcon(icon)
            .setContentTitle("Weechat-Android " + BuildConfig.VERSION_NAME).setContentText(content)
            .setWhen(System.currentTimeMillis());

    builder.setPriority(Notification.PRIORITY_MIN);

    if (P.notificationTicker)
        builder.setTicker(content);

    String disconnectText = context.getString(authenticated ? R.string.disconnect : R.string.stop_connecting);

    builder.addAction(android.R.drawable.ic_menu_close_clear_cancel, disconnectText, PendingIntent.getService(
            context, 0, new Intent(RelayService.ACTION_STOP, null, context, RelayService.class), 0));

    Notification notification = builder.build();
    notification.flags |= Notification.FLAG_ONGOING_EVENT;

    relay.startForeground(NOTIFICATION_MAIN_ID, notification);
}

From source file:hku.fyp14017.blencode.utils.StatusBarNotificationManager.java

public int createUploadNotification(Context context, String programName) {
    if (context == null || programName == null) {
        return -1;
    }/*from  ww w  .j  av  a  2  s . c  o  m*/
    initNotificationManager(context);

    Intent uploadIntent = new Intent(context, MainMenuActivity.class);
    uploadIntent.setAction(Intent.ACTION_MAIN);
    uploadIntent = uploadIntent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
    PendingIntent pendingIntent = PendingIntent.getActivity(context, notificationId, uploadIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);

    NotificationData data = new NotificationData(context, pendingIntent,
            hku.fyp14017.blencode.R.drawable.ic_stat, programName,
            hku.fyp14017.blencode.R.string.notification_upload_title_pending,
            hku.fyp14017.blencode.R.string.notification_upload_title_finished,
            hku.fyp14017.blencode.R.string.notification_upload_pending,
            hku.fyp14017.blencode.R.string.notification_upload_finished);

    int id = createNotification(context, data);
    showOrUpdateNotification(id, 0);
    return id;
}