Example usage for android.app Notification FLAG_AUTO_CANCEL

List of usage examples for android.app Notification FLAG_AUTO_CANCEL

Introduction

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

Prototype

int FLAG_AUTO_CANCEL

To view the source code for android.app Notification FLAG_AUTO_CANCEL.

Click Source Link

Document

Bit to be bitwise-ored into the #flags field that should be set if the notification should be canceled when it is clicked by the user.

Usage

From source file:com.quarterfull.newsAndroid.reader.owncloud.AsyncTask_GetItems.java

private void ShowDownloadImageWithoutWifiQuestion() {
    Bitmap bm = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher);

    Intent intent = new Intent(context, DownloadImagesActivity.class);
    intent.putExtra("highestItemIdBeforeSync", highestItemIdBeforeSync);
    PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent, 0);

    Notification notification = new NotificationCompat.Builder(context)
            .setContentTitle(context.getString(R.string.no_wifi_available))
            .setContentText(context.getString(R.string.do_you_want_to_download_without_wifi))
            .setSmallIcon(R.drawable.ic_notification).setLargeIcon(bm).setContentIntent(pIntent)
            .setAutoCancel(true).build();

    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    // hide the notification after its selected
    notification.flags |= Notification.FLAG_AUTO_CANCEL;

    notificationManager.notify(0, notification);
}

From source file:de.luhmer.owncloudnewsreader.reader.owncloud.AsyncTask_GetItems.java

private void ShowDownloadImageWithoutWifiQuestion() {
    Bitmap bm = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher);

    Intent intent = new Intent(context, DownloadImagesActivity.class);
    intent.putExtra("highestItemIdBeforeSync", highestItemIdBeforeSync);
    PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent, 0);

    Notification notification = new NotificationCompat.Builder(context)
            .setContentTitle(context.getString(R.string.no_wifi_available))
            .setContentText(context.getString(R.string.do_you_want_to_download_without_wifi))
            .setSmallIcon(R.drawable.ic_notification).setLargeIcon(bm).setContentIntent(pIntent)
            .setAutoCancel(true).build();

    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    // hide the notification after its selected
    notification.flags |= Notification.FLAG_AUTO_CANCEL;

    notificationManager.notify(0, notification);
}

From source file:org.croudtrip.location.LocationUploadTimerReceiver.java

private void handleSuccess(Context context) {
    int fc = failureCount.getAndSet(0);
    Timber.d("Failure Count is " + fc);
    if (fc >= MAX_FAILURE_COUNT) {
        // show a notification that no position upload was possible
        NotificationManager notificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);

        Notification notification = new NotificationCompat.Builder(context)
                .setSmallIcon(R.drawable.ic_directions_car_white)
                .setContentTitle(context.getString(R.string.success_position_update_title))
                .setStyle(new NotificationCompat.BigTextStyle()
                        .bigText(context.getString(R.string.success_position_update_message)))
                .setContentText(context.getString(R.string.success_position_update_message)).build();

        notification.flags |= Notification.FLAG_AUTO_CANCEL;

        notificationManager.notify(NOTIFICATION_UPLOAD_TIMER, notification);
    }// w  w  w  . j  a v a  2 s .c  o m
}

From source file:com.arisprung.tailgate.GCMIntentService.java

/**
 * Issues a notification to inform the user that server has sent a message.
 *///w  ww  .  j  a v a  2 s .  c  om
private static void generateNotification(Context context, MessageBean message) {
    //      Intent notificationIntent = new Intent(ctx, MainActivity.class);
    //      PendingIntent contentIntent = PendingIntent.getActivity(ctx,
    //              10, notificationIntent,
    //              PendingIntent.FLAG_CANCEL_CURRENT);
    //
    //      NotificationManager nm = (NotificationManager) ctx
    //              .getSystemService(Context.NOTIFICATION_SERVICE);
    //
    //      Resources res = ctx.getResources();
    //      Notification.Builder builder = new Notification.Builder(ctx);
    //      
    //      Bitmap profile = TailGateUtility.getUserPic(message.getFaceID());
    //
    //      builder.setContentIntent(contentIntent)
    //                  .setSmallIcon(R.drawable.ic_launcher)
    //                  .setLargeIcon(profile)
    //                  .setTicker(res.getString(R.string.app_name))
    //                  .setWhen(System.currentTimeMillis())
    //                  .setAutoCancel(true)
    //                  .setContentTitle(message.getUserName())
    //                  .setContentText(message.getMessage());
    //      Notification n = builder.build();
    //
    //      nm.notify(0, n);
    int icon = R.drawable.fanatic_icon_72px;
    long when = System.currentTimeMillis();
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(icon, message.getMessage(), when);

    String name = message.getUserName();
    Intent notificationIntent = new Intent(context, MainActivity.class);
    // set intent so it does not start a new activity
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
    notification.setLatestEventInfo(context, name, message.getMessage(), intent);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notificationManager.notify(0, notification);

}

From source file:net.helff.wificonnector.WifiConnectivityService.java

protected void sendNotification(String msg) {
    Log.i(TAG, "send notification: " + msg);
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    Notification notification = new Notification(R.drawable.launchericon, msg, System.currentTimeMillis());

    Intent intent = new Intent(this, WifiConnectorActivity.class);
    intent.setAction("android.intent.action.MAIN");
    intent.addCategory("android.intent.category.LAUNCHER");
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

    notification.setLatestEventInfo(this.getApplicationContext(), "WifiConnector", msg, pendingIntent);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notificationManager.notify(1, notification);

}

From source file:com.akop.bach.service.XboxLiveServiceClient.java

private void notifyFriends(XboxLiveAccount account, long[] friendsOnline, List<Long> lastFriendsOnline) {
    NotificationManager mgr = getNotificationManager();
    Context context = getContext();

    int notificationId = 0x2000000 | ((int) account.getId() & 0xffffff);

    if (App.getConfig().logToConsole()) {
        String s = "";
        for (Object unr : lastFriendsOnline)
            s += unr.toString() + ",";

        App.logv("Currently online (%d): %s", lastFriendsOnline.size(), s);

        s = "";// w w  w  .j  a va2s  .  c  om
        for (Object unr : friendsOnline)
            s += unr.toString() + ",";

        App.logv("New online (%d): %s", friendsOnline.length, s);
    }

    if (friendsOnline.length > 0) {
        int newOnlineCount = 0;
        for (Object online : friendsOnline)
            if (!lastFriendsOnline.contains(online))
                newOnlineCount++;

        if (App.getConfig().logToConsole())
            App.logv("%d computed new; %d online now; %d online before", newOnlineCount, friendsOnline.length,
                    lastFriendsOnline.size());

        if (newOnlineCount > 0) {
            // Prepare notification objects
            String tickerTitle;
            String tickerText;

            if (friendsOnline.length == 1) {
                tickerTitle = context.getString(R.string.friend_online);
                tickerText = context.getString(R.string.notify_friend_online_f,
                        Friends.getGamertag(context, friendsOnline[0]), account.getDescription());
            } else {
                tickerTitle = context.getString(R.string.friends_online);
                tickerText = context.getString(R.string.notify_friends_online_f, account.getScreenName(),
                        friendsOnline.length, account.getDescription());
            }

            Notification notification = new Notification(R.drawable.xbox_stat_notify_friend, tickerText,
                    System.currentTimeMillis());
            notification.flags |= Notification.FLAG_AUTO_CANCEL;

            Intent intent = new Intent(context, FriendList.class);
            intent.putExtra("account", account);

            PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, 0);

            notification.setLatestEventInfo(context, tickerTitle, tickerText, contentIntent);

            // New users online

            if (friendsOnline.length > 1)
                notification.number = friendsOnline.length;

            notification.flags |= Notification.FLAG_SHOW_LIGHTS;
            notification.ledOnMS = DEFAULT_LIGHTS_ON_MS;
            notification.ledOffMS = DEFAULT_LIGHTS_OFF_MS;
            notification.ledARGB = DEFAULT_LIGHTS_COLOR;
            notification.sound = account.getRingtoneUri();

            if (account.isVibrationEnabled())
                notification.defaults |= Notification.DEFAULT_VIBRATE;

            mgr.notify(notificationId, notification);
        }
    } else // No unread messages
    {
        mgr.cancel(notificationId);
    }
}

From source file:net.digitalfeed.pdroidalternative.intenthandler.PackageChangeHandler.java

private void displayNotification(Context context, NotificationType notificationType, String packageName,
        String label) {//from   w w w . j  av  a  2 s . c  om
    //This pattern is essentially taken from
    //https://developer.android.com/guide/topics/ui/notifiers/notifications.html

    Resources res = context.getResources();

    //TODO: Fix the icon in the notification bar            
    Notification.Builder builder = new Notification.Builder(context).setPriority(Notification.PRIORITY_MAX)
            .setSmallIcon(R.drawable.notification_icon);
    //.setLargeIcon(res.getDrawable(R.drawable.allow_icon))

    String appLabel = DBInterface.getInstance(context).getApplicationLabel(packageName);
    Log.d("PDroidAlternative", "new packagename is " + packageName);
    Log.d("PDroidAlternative", "app label is " + appLabel);
    switch (notificationType) {
    case newinstall:
        builder.setContentTitle(appLabel + " " + res.getString(R.string.notification_newinstall_title))
                .setContentText(res.getString(R.string.notification_newinstall_text));
        break;
    case update:
        builder.setContentTitle(appLabel + " " + res.getString(R.string.notification_update_title))
                .setContentText(res.getString(R.string.notification_update_text));
        break;
    }

    Intent packageDetailIntent = new Intent(context, AppDetailActivity.class);
    packageDetailIntent.putExtra(AppDetailActivity.BUNDLE_PACKAGE_NAME, packageName);
    packageDetailIntent.putExtra(AppDetailActivity.BUNDLE_IN_APP, false);
    packageDetailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK & Intent.FLAG_ACTIVITY_CLEAR_TASK);

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    stackBuilder.addParentStack(AppDetailActivity.class);
    stackBuilder.addNextIntent(packageDetailIntent);

    PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(pendingIntent);

    Notification builtNotification = builder.build();
    builtNotification.flags = builtNotification.flags | Notification.FLAG_AUTO_CANCEL
            | Notification.FLAG_NO_CLEAR;

    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0, builtNotification);
}

From source file:com.unfc.choicecustomercare.gcmservices.MyGcmListenerService.java

/**
 * Create and show a simple notification containing the received GCM
 * message.//from   www . j  av a  2 s. c  om
 *
 * @param message GCM message received.
 */

private void sendNotificationForTakeBreak(String message, String fromId, String toId) {

    Intent intent = new Intent(this, MainActivity.class);
    intent.setAction("takeBreak");
    intent.putExtra("fromId", fromId);
    intent.putExtra("toId", toId);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);

    Intent intentAccept = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingAccept = PendingIntent.getActivity(this, 1, intentAccept, PendingIntent.FLAG_ONE_SHOT);
    //
    Intent intentDecline = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingDecline = PendingIntent.getActivity(this, 2, intentDecline,
            PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.ic_launcher).setContentTitle(getString(R.string.app_name))
            .setContentText(message).setAutoCancel(true).setSound(defaultSoundUri)
            .setContentIntent(pendingIntent).setAutoCancel(true);

    notificationBuilder.getNotification().flags |= Notification.FLAG_AUTO_CANCEL;
    notificationBuilder.setAutoCancel(true);

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

    notificationManager.notify((int) new Date().getTime(), notificationBuilder.build());

}

From source file:com.testpush.notification.GcmIntentService.java

private void sendNotification(String titre, String message, String image, String id) {
    mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

    Log.d("GCM", "NOTIFICATION");

    //afficher la notif

    try {//from   w  w  w .ja  va2s . co m
        //Vibrator v = (Vibrator) this.getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
        // Vibrate for 500 milliseconds
        //v.vibrate(new long[]{0,100,300,200},-1);
    } catch (Exception e) {
    }

    PackageManager pm = getPackageManager();
    Intent lancement = new Intent(this.getApplicationContext(), MainActivity.class);
    lancement.putExtra("LAUNCH_NOTIFICATION", true);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, lancement, 0);

    Bitmap bitmap = getBitmapFromURL(image);

    Notification notif;
    {
        notif = new NotificationCompat.Builder(this).setSmallIcon(R.mipmap.ic_launcher).setLargeIcon(bitmap)
                .setColor(Color.GRAY).setContentTitle(titre).setContentText(message)
                .setContentIntent(contentIntent).build();

        notif.ledARGB = Color.GRAY;
        notif.flags = Notification.FLAG_SHOW_LIGHTS;
        notif.ledOnMS = 750;
        notif.ledOffMS = 2000;

    }

    //TODO mettre le nombre et un id diffrent
    notif.flags |= Notification.FLAG_AUTO_CANCEL;

    if (id == null)
        id = "";

    mNotificationManager.notify(id, id.hashCode(), notif);

}

From source file:com.evandroid.musica.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)))
        return;

    String artist = extras.getString("artist");
    String track = extras.getString("track");
    long position = extras.containsKey("position") ? extras.getLong("position") : -1;
    if (extras.get("position") instanceof Double)
        position = Double.valueOf(extras.getDouble("position")).longValue();
    boolean isPlaying = extras.getBoolean("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);
    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);
    }

    SQLiteDatabase db = new DatabaseHelper(context).getReadableDatabase();
    boolean inDatabase = DatabaseHelper.presenceCheck(db, new String[] { artist, track, artist, track });
    db.close();

    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);

        if ("0".equals(sharedPref.getString("pref_theme", "0")))
            notifBuilder.setColor(context.getResources().getColor(R.color.primary));

        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").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).setGroupSummary(false)
                .extend(new NotificationCompat.WearableExtender().addAction(wearableAction));

        if (notificationPref == 2) {
            notifBuilder.setOngoing(true).setPriority(-2); // Notification.PRIORITY_MIN
        } 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);
}