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:ch.carteggio.provider.sync.NotificationService.java

private void updateUnreadNotification(boolean newMessage) {

    NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    CarteggioProviderHelper helper = new CarteggioProviderHelper(this);

    int unreadCount = helper.getUnreadCount();

    if (unreadCount == 0) {

        mNotificationManager.cancel(INCOMING_NOTIFICATION_ID);

    } else {/*from  w  w w.ja  va 2  s.c om*/

        String quantityString = getResources().getQuantityString(R.plurals.notification_new_incoming_messages,
                unreadCount);

        NotificationCompat.Builder notifyBuilder = new NotificationCompat.Builder(this)
                .setContentTitle(String.format(quantityString, unreadCount))
                .setSmallIcon(android.R.drawable.stat_notify_chat)
                .setContentText(getString(R.string.notification_text_new_messages));

        Intent resultIntent = new Intent(this, MainActivity.class);

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(MainActivity.class);
        stackBuilder.addNextIntent(resultIntent);

        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

        notifyBuilder.setContentIntent(resultPendingIntent);

        if (newMessage) {

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

            AudioManager manager = (AudioManager) getSystemService(AUDIO_SERVICE);

            long pattern[] = { 1000, 500, 2000 };

            if (manager.getRingerMode() == AudioManager.RINGER_MODE_NORMAL) {
                notifyBuilder.setSound(uri);
                notifyBuilder.setVibrate(pattern);
            } else if (manager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE) {
                notifyBuilder.setVibrate(pattern);
            }
        }

        mNotificationManager.notify(INCOMING_NOTIFICATION_ID, notifyBuilder.build());

    }

}

From source file:nl.sogeti.android.gpstracker.actions.NameTrack.java

private void clearNotification() {

    NotificationManager noticationManager = (NotificationManager) this
            .getSystemService(Context.NOTIFICATION_SERVICE);
    ;/*from   w  ww.  j av a  2  s . c o  m*/
    noticationManager.cancel(R.layout.namedialog);
}

From source file:com.deepak.myclock.alarms.AlarmNotifications.java

public static void showMissedNotification(Context context, AlarmInstance instance) {
    Log.v("Displaying missed notification for alarm instance: " + instance.mId);
    NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    String label = instance.mLabel;
    String alarmTime = AlarmUtils.getFormattedTime(context, instance.getAlarmTime());
    String contextText = instance.mLabel.isEmpty() ? alarmTime
            : context.getString(R.string.alarm_missed_text, alarmTime, label);
    NotificationCompat.Builder notification = new NotificationCompat.Builder(context)
            .setContentTitle(context.getString(R.string.alarm_missed_title)).setContentText(contextText)
            .setSmallIcon(R.drawable.stat_notify_alarm).setPriority(NotificationCompat.PRIORITY_HIGH);

    // Setup dismiss intent
    Intent dismissIntent = AlarmStateManager.createStateChangeIntent(context, "DISMISS_TAG", instance,
            AlarmInstance.DISMISSED_STATE);
    notification.setDeleteIntent(PendingIntent.getBroadcast(context, instance.hashCode(), dismissIntent,
            PendingIntent.FLAG_UPDATE_CURRENT));

    // Setup content intent
    Intent showAndDismiss = AlarmInstance.createIntent(context, AlarmStateManager.class, instance.mId);
    showAndDismiss.setAction(AlarmStateManager.SHOW_AND_DISMISS_ALARM_ACTION);
    notification.setContentIntent(PendingIntent.getBroadcast(context, instance.hashCode(), showAndDismiss,
            PendingIntent.FLAG_UPDATE_CURRENT));

    nm.cancel(instance.hashCode());
    nm.notify(instance.hashCode(), notification.build());
}

From source file:com.kasungunathilaka.sarigama.ui.HomeActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home:
        onBackPressed();/*from   w  ww  .jav  a2 s . c o m*/
        break;
    case R.id.action_search:
        setFragment(new SearchFragment());
        break;
    case R.id.action_about_developer:
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(HomeActivity.this);
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_view_about_developer, null);
        alertDialogBuilder.setView(dialogView);
        ImageView ivClose = (ImageView) dialogView.findViewById(R.id.ivClose);
        TextView tvEmail = (TextView) dialogView.findViewById(R.id.tvEmail);
        final AlertDialog alertDialog = alertDialogBuilder.create();
        tvEmail.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    Intent emailIntent = new Intent(Intent.ACTION_SEND);
                    emailIntent.setType("plain/text");
                    emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
                            new String[] { "developer.kasun.gunathilaka@gmail.com" });
                    emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Sarigama");
                    emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "");
                    startActivity(emailIntent);
                    alertDialog.dismiss();
                }
                return false;
            }
        });
        ivClose.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    alertDialog.dismiss();
                }
                return false;
            }
        });
        alertDialog.show();
        break;
    case R.id.action_exit:
        finish();
        NotificationManager notificationManager = (NotificationManager) getSystemService(
                Context.NOTIFICATION_SERVICE);
        notificationManager.cancel(9999);
        System.exit(0);
        break;
    }
    return super.onOptionsItemSelected(item);
}

From source file:com.daiv.android.twitter.services.SendTweet.java

public void finishedTweetingNotification() {
    // sometimes it just would keep making the notification for some reason...
    // so delay it to insure it clears everything correctly
    try {//  w  w w .j  a  v a2 s. c o m
        Thread.sleep(500);
    } catch (Exception e) {

    }

    try {
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity.sContext)
                .setSmallIcon(R.drawable.ic_stat_icon)
                .setContentTitle(getResources().getString(R.string.tweet_success)).setOngoing(false)
                .setTicker(getResources().getString(R.string.tweet_success));

        if (AppSettings.getInstance(getApplicationContext()).vibrate) {
            Log.v(TAG + "Test_vibrate", "vibrate on compose");
            Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
            long[] pattern = { 0, 50, 500 };
            v.vibrate(pattern, -1);
        }

        stopForeground(true);

        NotificationManager mNotificationManager = (NotificationManager) MainActivity.sContext
                .getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(6, mBuilder.build());
        // cancel it immediately, the ticker will just go off
        mNotificationManager.cancel(6);
    } catch (Exception e) {
        // not attached to activity
    }

}

From source file:com.klinker.android.twitter.services.SendTweet.java

public void finishedTweetingNotification() {
    // sometimes it just would keep making the notification for some reason...
    // so delay it to insure it clears everything correctly
    try {/*  w  ww  .  ja  v a2 s  . c om*/
        Thread.sleep(500);
    } catch (Exception e) {

    }

    try {
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity.sContext)
                .setSmallIcon(R.drawable.ic_stat_icon)
                .setContentTitle(getResources().getString(R.string.tweet_success)).setOngoing(false)
                .setTicker(getResources().getString(R.string.tweet_success));

        if (AppSettings.getInstance(getApplicationContext()).vibrate) {
            Log.v("talon_vibrate", "vibrate on compose");
            Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
            long[] pattern = { 0, 50, 500 };
            v.vibrate(pattern, -1);
        }

        stopForeground(true);

        NotificationManager mNotificationManager = (NotificationManager) MainActivity.sContext
                .getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(6, mBuilder.build());
        // cancel it immediately, the ticker will just go off
        mNotificationManager.cancel(6);
    } catch (Exception e) {
        // not attached to activity
    }

}

From source file:io.github.carlorodriguez.alarmon.AlarmClockService.java

private void refreshNotification() {
    String resolvedString = getString(R.string.no_pending_alarms);

    AlarmTime nextTime = pendingAlarms.nextAlarmTime();

    if (nextTime != null) {
        Map<String, String> values = new HashMap<>();

        values.put("t", nextTime.localizedString(getApplicationContext()));

        values.put("c", nextTime.timeUntilString(getApplicationContext()));

        String templateString = AppSettings.getNotificationTemplate(getApplicationContext());

        StrSubstitutor sub = new StrSubstitutor(values);

        resolvedString = sub.replace(templateString);
    }//w w  w.j av a 2 s .c  om

    // Make the notification launch the UI Activity when clicked.
    final Intent notificationIntent = new Intent(this, ActivityAlarmClock.class);
    final PendingIntent launch = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    Context c = getApplicationContext();

    NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext());

    String notificationTitle = getString(R.string.app_name);

    if (pendingAlarms.nextAlarmId() != AlarmClockServiceBinder.NO_ALARM_ID) {
        DbAccessor db = new DbAccessor(getApplicationContext());

        AlarmInfo alarmInfo = db.readAlarmInfo(pendingAlarms.nextAlarmId());

        if (alarmInfo != null) {
            notificationTitle = alarmInfo.getName() != null && !alarmInfo.getName().isEmpty()
                    ? alarmInfo.getName()
                    : getString(R.string.app_name);
        }

        db.closeConnections();
    }

    Notification notification = builder.setContentIntent(launch).setSmallIcon(R.drawable.ic_stat_notify_alarm)
            .setContentTitle(notificationTitle).setContentText(resolvedString)
            .setColor(ContextCompat.getColor(getApplicationContext(), R.color.notification_color)).build();
    notification.flags |= Notification.FLAG_ONGOING_EVENT;

    final NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    if (pendingAlarms.size() > 0 && AppSettings.displayNotificationIcon(c)) {
        manager.notify(NOTIFICATION_BAR_ID, notification);
    } else {
        manager.cancel(NOTIFICATION_BAR_ID);
    }

    setSystemAlarmStringOnLockScreen(getApplicationContext(), nextTime);
}

From source file:com.racoon.ampdroid.Mp3PlayerService.java

private void play(int id) {
    mediaPlayer.reset();//from   www  .  j  av  a  2 s  .  c  o  m
    try {
        Log.d("bugs", "song url " + playList.get(id).getUrl());
        String pattern = "ssid=([a-z]|[0-9])*&";
        String dataUrl = playList.get(id).getUrl().replaceAll(pattern, "ssid=" + session + "&");
        Log.d("bugs", "session " + session);
        Log.d("bugs", "data url " + dataUrl);
        //mediaPlayer.setDataSource(dataUrl);

        File extStore = Environment.getExternalStorageDirectory();
        String tmpfilename = extStore.getPath() + "/tmp/Ampdroid.mp3";

        File tmpfile = new File(tmpfilename);
        tmpfile.delete();

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_stat_notify)
                .setContentTitle(getResources().getString(R.string.app_name))
                .setContentText(getResources().getString(R.string.downloadinfo));
        int mNotificationId = 1;
        NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        mNotifyMgr.notify(mNotificationId, mBuilder.build());

        DownloadFromUrl(dataUrl, tmpfilename, oCuser, oCpassword);
        mediaPlayer.setDataSource(tmpfilename);

        mNotifyMgr.cancel(mNotificationId);

        mediaPlayer.prepare();
        currentSong = playList.get(id);
        mediaPlayer.start();
        setNotifiction();
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.smedic.tubtub.BackgroundAudioService.java

@Override
public void onTaskRemoved(Intent rootIntent) {
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);
    mNotificationManager.cancel(1);
}

From source file:com.google.samples.apps.sergio.service.SessionAlarmService.java

private void scheduleAlarm(final long sessionStart, final long sessionEnd, final long alarmOffset) {

    NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    nm.cancel(NOTIFICATION_ID);
    final long currentTime = UIUtils.getCurrentTime(this);
    // If the session is already started, do not schedule system notification.
    if (currentTime > sessionStart) {
        LOGD(TAG, "Not scheduling alarm because target time is in the past: " + sessionStart);
        return;/*from  w ww  . ja v a2  s . com*/
    }

    // By default, sets alarm to go off at 10 minutes before session start time.  If alarm
    // offset is provided, alarm is set to go off by that much time from now.
    long alarmTime;
    if (alarmOffset == UNDEFINED_ALARM_OFFSET) {
        alarmTime = sessionStart - MILLI_TEN_MINUTES;
    } else {
        alarmTime = currentTime + alarmOffset;
    }

    LOGD(TAG, "Scheduling alarm for " + alarmTime + " = " + (new Date(alarmTime)).toString());

    final Intent notifIntent = new Intent(ACTION_NOTIFY_SESSION, null, this, SessionAlarmService.class);
    // Setting data to ensure intent's uniqueness for different session start times.
    notifIntent.setData(new Uri.Builder().authority("com.google.samples.apps.sergio")
            .path(String.valueOf(sessionStart)).build());
    notifIntent.putExtra(SessionAlarmService.EXTRA_SESSION_START, sessionStart);
    LOGD(TAG, "-> Intent extra: session start " + sessionStart);
    notifIntent.putExtra(SessionAlarmService.EXTRA_SESSION_END, sessionEnd);
    LOGD(TAG, "-> Intent extra: session end " + sessionEnd);
    notifIntent.putExtra(SessionAlarmService.EXTRA_SESSION_ALARM_OFFSET, alarmOffset);
    LOGD(TAG, "-> Intent extra: session alarm offset " + alarmOffset);
    PendingIntent pi = PendingIntent.getService(this, 0, notifIntent, PendingIntent.FLAG_CANCEL_CURRENT);
    final AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    // Schedule an alarm to be fired to notify user of added sessions are about to begin.
    LOGD(TAG, "-> Scheduling RTC_WAKEUP alarm at " + alarmTime);
    am.set(AlarmManager.RTC_WAKEUP, alarmTime, pi);
}