Example usage for android.app NotificationManager cancel

List of usage examples for android.app NotificationManager cancel

Introduction

In this page you can find the example usage for android.app NotificationManager cancel.

Prototype

public void cancel(int id) 

Source Link

Document

Cancel a previously shown notification.

Usage

From source file:me.myatminsoe.myansms.SmsReceiver.java

/**
 * Update new message {@link Notification}.
 *
 * @param context {@link Context}/*from  w ww  .  j  a v a2s.  c  o m*/
 * @param text    text of the last assumed unread message
 * @return number of unread messages
 */
static int updateNewMessageNotification(final Context context, final String text) {
    final NotificationManager mNotificationMgr = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    final boolean enableNotifications = prefs.getBoolean(PreferencesActivity.PREFS_NOTIFICATION_ENABLE, true);
    final boolean privateNotification = prefs.getBoolean(PreferencesActivity.PREFS_NOTIFICATION_PRIVACY, false);
    final boolean showPhoto = !privateNotification
            && prefs.getBoolean(PreferencesActivity.PREFS_CONTACT_PHOTO, true);
    if (!enableNotifications) {
        mNotificationMgr.cancelAll();
        Log.d(TAG, "no notification needed!");
    }
    final int[] status = getUnread(context.getContentResolver(), text);
    final int l = status[ID_COUNT];
    final int tid = status[ID_TID];

    // FIXME l is always -1..
    if (l < 0) {
        return l;
    }

    if (enableNotifications && (text != null || l == 0)) {
        mNotificationMgr.cancel(NOTIFICATION_ID_NEW);
    }
    Uri uri;
    PendingIntent pIntent;
    if (l == 0) {
        final Intent i = new Intent(context, ConversationListActivity.class);
        // add pending intent
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        pIntent = PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
    } else {
        final NotificationCompat.Builder nb = new NotificationCompat.Builder(context);
        boolean showNotification = true;
        Intent i;
        if (tid >= 0) {
            uri = Uri.parse(MessageListActivity.URI + tid);
            i = new Intent(Intent.ACTION_VIEW, uri, context, MessageListActivity.class);
            pIntent = PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);

            if (enableNotifications) {
                final Conversation conv = Conversation.getConversation(context, tid, true);
                if (conv != null) {
                    String a;
                    if (privateNotification) {
                        if (l == 1) {
                            a = context.getString(R.string.new_message_);
                        } else {
                            a = context.getString(R.string.new_messages_);
                        }
                    } else {
                        a = conv.getContact().getDisplayName();
                    }
                    showNotification = true;
                    nb.setSmallIcon(PreferencesActivity.getNotificationIcon(context));
                    nb.setTicker(a);
                    nb.setWhen(lastUnreadDate);
                    if (l == 1) {
                        String body;
                        if (privateNotification) {
                            body = context.getString(R.string.new_message);
                        } else {
                            body = lastUnreadBody;
                        }
                        if (body == null) {
                            body = context.getString(R.string.mms_conversation);
                        }
                        nb.setContentTitle(a);
                        nb.setContentText(body);
                        nb.setContentIntent(pIntent);
                        // add long text
                        nb.setStyle(new NotificationCompat.BigTextStyle().bigText(body));

                        // add actions
                        Intent nextIntent = new Intent(NotificationBroadcastReceiver.ACTION_MARK_READ);
                        nextIntent.putExtra(NotificationBroadcastReceiver.EXTRA_MURI, uri.toString());
                        PendingIntent nextPendingIntent = PendingIntent.getBroadcast(context, 0, nextIntent,
                                PendingIntent.FLAG_UPDATE_CURRENT);

                        nb.addAction(R.drawable.ic_done_24dp, context.getString(R.string.mark_read_),
                                nextPendingIntent);
                        nb.addAction(R.drawable.ic_reply_24dp, context.getString(R.string.reply), pIntent);
                    } else {
                        nb.setContentTitle(a);
                        nb.setContentText(context.getString(R.string.new_messages, l));
                        nb.setContentIntent(pIntent);
                    }
                    if (showPhoto // just for the speeeeed
                            && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                        try {
                            conv.getContact().update(context, false, true);
                        } catch (NullPointerException e) {
                            Log.e(TAG, "updating contact failed", e);
                        }
                        Drawable d = conv.getContact().getAvatar(context, null);
                        if (d instanceof BitmapDrawable) {
                            Bitmap bitmap = ((BitmapDrawable) d).getBitmap();
                            // 24x24 dp according to android iconography  ->
                            // http://developer.android.com/design/style/iconography.html#notification
                            int px = Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 64,
                                    context.getResources().getDisplayMetrics()));
                            nb.setLargeIcon(Bitmap.createScaledBitmap(bitmap, px, px, false));
                        }
                    }
                }
            }
        } else {
            uri = Uri.parse(MessageListActivity.URI);
            i = new Intent(Intent.ACTION_VIEW, uri, context, ConversationListActivity.class);
            pIntent = PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);

            if (enableNotifications) {
                showNotification = true;
                nb.setSmallIcon(PreferencesActivity.getNotificationIcon(context));
                nb.setTicker(context.getString(R.string.new_messages_));
                nb.setWhen(lastUnreadDate);
                nb.setContentTitle(context.getString(R.string.new_messages_));
                nb.setContentText(context.getString(R.string.new_messages, l));
                nb.setContentIntent(pIntent);
                nb.setNumber(l);
            }
        }
        // add pending intent
        i.setFlags(i.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);

        if (enableNotifications && showNotification) {
            int[] ledFlash = PreferencesActivity.getLEDflash(context);
            nb.setLights(PreferencesActivity.getLEDcolor(context), ledFlash[0], ledFlash[1]);
            final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(context);
            if (text != null) {
                final boolean vibrate = p.getBoolean(PreferencesActivity.PREFS_VIBRATE, false);
                final String s = p.getString(PreferencesActivity.PREFS_SOUND, null);
                Uri sound;
                if (s == null || s.length() <= 0) {
                    sound = null;
                } else {
                    sound = Uri.parse(s);
                }
                if (vibrate) {
                    final long[] pattern = PreferencesActivity.getVibratorPattern(context);
                    if (pattern.length == 1 && pattern[0] == 0) {
                        nb.setDefaults(Notification.DEFAULT_VIBRATE);
                    } else {
                        nb.setVibrate(pattern);
                    }
                }
                nb.setSound(sound);
            }
        }

        mNotificationMgr.cancel(NOTIFICATION_ID_NEW);
        if (enableNotifications && showNotification) {
            try {
                mNotificationMgr.notify(NOTIFICATION_ID_NEW, nb.getNotification());
            } catch (IllegalArgumentException e) {

            }
        }
    }
    //noinspection ConstantConditions
    return l;
}

From source file:com.baruckis.nanodegree.spotifystreamer.PlayerService.java

private void showCancelNotification(boolean visible) {
    NotificationManager notificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);
    if (mNotification == null)
        return;//from   w  w  w . j  a  va2s .  c o m
    if (visible) {
        notificationManager.notify(1, mNotification);
    } else {
        notificationManager.cancel(1);
    }
}

From source file:org.deviceconnect.android.deviceplugin.host.camera.CameraOverlay.java

/**
 * Notification?./*ww  w.j a v  a2s. c om*/
 */
private void hideNotification() {
    NotificationManager manager = (NotificationManager) mContext.getSystemService(Service.NOTIFICATION_SERVICE);
    manager.cancel(NOTIFICATION_ID);
}

From source file:org.deviceconnect.android.deviceplugin.host.camera.CameraOverlay.java

/**
 * Notification??.//from  ww w . j  a  v  a  2s .co m
 */
private void sendNotification() {
    PendingIntent contentIntent = createPendingIntent();
    Notification notification = createNotification(contentIntent);
    notification.flags = Notification.FLAG_NO_CLEAR;
    NotificationManager manager = (NotificationManager) mContext.getSystemService(Service.NOTIFICATION_SERVICE);
    manager.cancel(NOTIFICATION_ID);
    manager.notify(NOTIFICATION_ID, notification);
}

From source file:menion.android.whereyougo.gui.extension.activity.CustomActivity.java

public static void setStatusbar(Activity activity) {
    try {//from   w ww.  j  av a2  s  .  c  o  m
        NotificationManager mNotificationManager = (NotificationManager) activity
                .getSystemService(Context.NOTIFICATION_SERVICE);
        // set statusbar
        if (Preferences.APPEARANCE_STATUSBAR) {
            Context context = activity.getApplicationContext();
            Intent intent = new Intent(context, menion.android.whereyougo.gui.activity.MainActivity.class);
            // intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            intent.setAction(Intent.ACTION_MAIN);
            PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent, 0);
            final int sdkVersion = Integer.parseInt(android.os.Build.VERSION.SDK);
            Notification notif = null;
            if (sdkVersion < android.os.Build.VERSION_CODES.HONEYCOMB) {
                notif = new Notification(R.drawable.ic_title_logo, A.getAppName(), System.currentTimeMillis());
                notif.setLatestEventInfo(activity, A.getAppName(), "", pIntent);
            } else {
                NotificationCompat.Builder builder = new NotificationCompat.Builder(activity)
                        .setContentTitle(A.getAppName()).setSmallIcon(R.drawable.ic_title_logo)
                        .setContentIntent(pIntent);
                notif = builder.build();
            }
            notif.flags = Notification.FLAG_ONGOING_EVENT;
            mNotificationManager.notify(0, notif);
        } else {
            mNotificationManager.cancel(0);
        }
    } catch (Exception e) {
        // Logger.e(TAG, "setStatusbar(" + activity + ")", e);
    }
}

From source file:org.telegram.ui.ApplicationActivity.java

@Override
protected void onResume() {
    super.onResume();
    if (notificationView == null && getLayoutInflater() != null) {
        notificationView = (NotificationView) getLayoutInflater().inflate(R.layout.notification_layout, null);
    }// w  w w  .ja va2 s .  co  m
    fixLayout();
    checkForCrashes();
    checkForUpdates();
    ApplicationLoader.resetLastPauseTime();
    supportInvalidateOptionsMenu();
    updateActionBar();
    try {
        NotificationManager mNotificationManager = (NotificationManager) this
                .getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.cancel(1);
    } catch (Exception e) {
        FileLog.e("tmessages", e);
    }
}

From source file:de.tubs.ibr.dtn.service.DaemonService.java

/**
 * Called on stopSelf() or stopService()
 *//*w  w w  .j  a  v a 2  s . co  m*/
@Override
public void onDestroy() {
    // unlisten to preference changes
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    prefs.unregisterOnSharedPreferenceChangeListener(_pref_listener);

    // disable P2P manager
    if (mP2pManager != null)
        mP2pManager.destroy();

    // stop looper that handles incoming intents
    mServiceLooper.quit();

    // close all sessions
    mSessionManager.destroy();

    // shutdown daemon completely
    mDaemonProcess.destroy();
    mDaemonProcess = null;

    // dereference P2P Manager
    mP2pManager = null;

    // remove notification
    NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    nm.cancel(1);

    // close statistic database
    mStatsDatabase.close();

    // call super method
    super.onDestroy();
}

From source file:com.android.email.EmailNotificationController.java

/**
 * Cancels all notifications for the specified account id. This includes new mail notifications,
 * as well as special login/security notifications.
 *//*w ww .j a v  a2 s. co  m*/
@Override
public void cancelNotifications(final Context context, final Account account) {
    final EmailServiceUtils.EmailServiceInfo serviceInfo = EmailServiceUtils.getServiceInfoForAccount(context,
            account.mId);
    if (serviceInfo == null) {
        LogUtils.d(LOG_TAG, "Can't cancel notification for missing account %d", account.mId);
        return;
    }
    final android.accounts.Account notifAccount = account.getAccountManagerAccount(serviceInfo.accountType);

    NotificationUtils.clearAccountNotifications(context, notifAccount);

    final NotificationManager notificationManager = getInstance(context).mNotificationManager;

    notificationManager.cancel((int) (NOTIFICATION_ID_BASE_LOGIN_WARNING + account.mId));
    notificationManager.cancel((int) (NOTIFICATION_ID_BASE_SECURITY_NEEDED + account.mId));
    notificationManager.cancel((int) (NOTIFICATION_ID_BASE_SECURITY_CHANGED + account.mId));
}

From source file:org.spinsuite.bchat.view.FV_Thread.java

/**
 * Clear Notification/*from  w  w  w. j a va2  s .c  o m*/
 * @author Yamel Senih, ysenih@erpcya.com, ERPCyA http://www.erpcya.com
 * @return void
 */
private void clearNotification() {
    NotificationManager m_NotificationManager = (NotificationManager) m_ctx
            .getSystemService(Context.NOTIFICATION_SERVICE);
    m_NotificationManager.cancel(MQTTDefaultValues.NOTIFICATION_ID);
}

From source file:net.lp.hivawareness.v4.HIVAwarenessActivity.java

@Override
public void onResume() {
    super.onResume();

    if (!HIVAwarenessActivity.DEBUG)
        FlurryAgent.onEvent("window_displayed");
    if (!HIVAwarenessActivity.DEBUG)
        FlurryAgent.onPageView();/* w ww .j  a va 2s .  c o m*/
    AnalyticsUtils.getInstance().trackGAPageView("/" + this.getLocalClassName(), "");

    // Check to see that the Activity started due to an Android Beam
    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
        processIntent(getIntent());
    }

    // TODO sending messages at the same time do not work !race condition
    if (!(DEBUG && mNfcAdapter == null)) {
        mNfcAdapter.enableForegroundNdefPush(this, createNdefMessage());
        mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, mIntentFiltersArray, mTechListsArray);
    }

    NotificationManager nm = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
    nm.cancel(1);

    if (caught != -1) {
        goToStartedFragment();
    }
}