Example usage for android.app NotificationManager cancelAll

List of usage examples for android.app NotificationManager cancelAll

Introduction

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

Prototype

public void cancelAll() 

Source Link

Document

Cancel all previously shown notifications.

Usage

From source file:com.xrmaddness.offthegrid.ListActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_list);

    Log.d("onCreate", "Version: " + version_get());

    view_contacts();/* w w  w . j  a v  a 2  s  .  c om*/

    SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

    String email_address = SP.getString("email_address", null);

    create_pgp(email_address);

    check_background();

    /* User entered the app, cancel all notifications (also if user did not get in
     * via the notification) 
     */
    NotificationManager notification_mgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notification_mgr.cancelAll();
}

From source file:com.test.onesignal.GenerateNotificationRunner.java

@Before // Before each test
public void beforeEachTest() throws Exception {
    // Robolectric mocks System.currentTimeMillis() to 0, we need the current real time to match our SQL records.
    ShadowSystemClock.setCurrentTimeMillis(System.currentTimeMillis());

    blankActivityController = Robolectric.buildActivity(BlankActivity.class).create();
    blankActivity = blankActivityController.get();
    blankActivity.getApplicationInfo().name = "UnitTestApp";

    overrideNotificationId = -1;/*from w  w  w . j a v a2s  .  c o m*/

    TestHelpers.betweenTestsCleanup();

    NotificationManager notificationManager = (NotificationManager) blankActivity
            .getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.cancelAll();
}

From source file:org.yuttadhammo.BodhiTimer.TimerReceiver.java

@Override
public void onReceive(Context context, Intent pintent) {
    Log.v(TAG, "ALARM: received alarm");

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

    if (player != null) {
        Log.v(TAG, "Releasing media player...");
        try {//ww w . j av  a  2  s.  co m
            player.release();
            player = null;
        } catch (Exception e) {
            e.printStackTrace();
            player = null;
        } finally {
            // do nothing
        }
    }

    // Cancel notification and return...
    if (CANCEL_NOTIFICATION.equals(pintent.getAction())) {
        Log.v(TAG, "Cancelling notification...");

        mNM.cancelAll();
        return;
    }

    // ...or display a new one

    Log.v(TAG, "Showing notification...");

    player = new MediaPlayer();

    int setTime = pintent.getIntExtra("SetTime", 0);
    String setTimeStr = TimerUtils.time2humanStr(context, setTime);
    Log.v(TAG, "Time: " + setTime);

    CharSequence text = context.getText(R.string.Notification);
    CharSequence textLatest = String.format(context.getString(R.string.timer_for_x), setTimeStr);

    // Load the settings 
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    boolean led = prefs.getBoolean("LED", true);
    boolean vibrate = prefs.getBoolean("Vibrate", true);
    String notificationUri = "";

    boolean useAdvTime = prefs.getBoolean("useAdvTime", false);
    String advTimeString = prefs.getString("advTimeString", "");
    String[] advTime = null;
    int advTimeIndex = 1;

    if (useAdvTime && advTimeString.length() > 0) {
        advTime = advTimeString.split("\\^");
        advTimeIndex = prefs.getInt("advTimeIndex", 1);
        String[] thisAdvTime = advTime[advTimeIndex - 1].split("#"); // will be of format timeInMs#pathToSound

        if (thisAdvTime.length == 3)
            notificationUri = thisAdvTime[1];
        if (notificationUri.equals("sys_def"))
            notificationUri = prefs.getString("NotificationUri",
                    "android.resource://org.yuttadhammo.BodhiTimer/" + R.raw.bell);
    } else
        notificationUri = prefs.getString("NotificationUri",
                "android.resource://org.yuttadhammo.BodhiTimer/" + R.raw.bell);

    Log.v(TAG, "notification uri: " + notificationUri);

    if (notificationUri.equals("system"))
        notificationUri = prefs.getString("SystemUri", "");
    else if (notificationUri.equals("file"))
        notificationUri = prefs.getString("FileUri", "");
    else if (notificationUri.equals("tts")) {
        notificationUri = "";
        final String ttsString = prefs.getString("tts_string", context.getString(R.string.timer_done));
        Intent ttsIntent = new Intent(context, TTSService.class);
        ttsIntent.putExtra("spoken_text", ttsString);
        context.startService(ttsIntent);
    }

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context.getApplicationContext())
            .setSmallIcon(R.drawable.notification).setContentTitle(text).setContentText(textLatest);

    Uri uri = null;

    // Play a sound!
    if (!notificationUri.equals(""))
        uri = Uri.parse(notificationUri);

    // Vibrate
    if (vibrate && uri == null) {
        mBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
    }

    // Have a light
    if (led) {
        mBuilder.setLights(0xff00ff00, 300, 1000);
    }

    mBuilder.setAutoCancel(true);

    // Creates an explicit intent for an Activity in your app
    Intent resultIntent = new Intent(context, TimerActivity.class);

    // The stack builder object will contain an artificial back stack for the
    // started Activity.
    // This ensures that navigating backward from the Activity leads out of
    // your application to the Home screen.
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    // Adds the back stack for the Intent (but not the Intent itself)
    stackBuilder.addParentStack(TimerActivity.class);
    // Adds the Intent that starts the Activity to the top of the stack
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(resultPendingIntent);
    NotificationManager mNotificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);

    // Create intent for cancelling the notification
    Context appContext = context.getApplicationContext();
    Intent intent = new Intent(appContext, TimerReceiver.class);
    intent.setAction(CANCEL_NOTIFICATION);

    // Cancel the pending cancellation and create a new one
    PendingIntent pendingCancelIntent = PendingIntent.getBroadcast(appContext, 0, intent,
            PendingIntent.FLAG_CANCEL_CURRENT);

    if (uri != null) {

        //remove notification sound
        mBuilder.setSound(null);

        try {
            if (player != null && player.isPlaying()) {
                player.release();
                player = new MediaPlayer();
            }

            int currVolume = prefs.getInt("tone_volume", 0);
            if (currVolume != 0) {
                float log1 = (float) (Math.log(100 - currVolume) / Math.log(100));
                player.setVolume(1 - log1, 1 - log1);
            }
            player.setDataSource(context, uri);
            player.prepare();
            player.setLooping(false);
            player.setOnCompletionListener(new OnCompletionListener() {

                @Override
                public void onCompletion(MediaPlayer mp) {
                    // TODO Auto-generated method stub
                    mp.release();
                }

            });
            player.start();
            if (vibrate) {
                Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
                vibrator.vibrate(1000);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    if (prefs.getBoolean("AutoClear", false)) {
        // Determine duration of notification sound
        int duration = 5000;
        if (uri != null) {
            MediaPlayer cancelPlayer = new MediaPlayer();
            try {
                cancelPlayer.setDataSource(context, uri);
                cancelPlayer.prepare();
                duration = Math.max(duration, cancelPlayer.getDuration() + 2000);
            } catch (java.io.IOException ex) {
                Log.e(TAG, "Cannot get sound duration: " + ex);
                duration = 30000; // on error, default to 30 seconds
            } finally {
                cancelPlayer.release();
            }
            cancelPlayer.release();
        }
        Log.v(TAG, "Notification duration: " + duration + " ms");
        // Schedule cancellation
        AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmMgr.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + duration,
                pendingCancelIntent);
    }

    if (useAdvTime && advTimeString.length() > 0) {
        Intent broadcast = new Intent();

        SharedPreferences.Editor editor = prefs.edit();
        if (advTimeIndex < advTime.length) {
            editor.putInt("advTimeIndex", advTimeIndex + 1);

            String[] thisAdvTime = advTime[advTimeIndex].split("#"); // will be of format timeInMs#pathToSound

            int time = Integer.parseInt(thisAdvTime[0]);

            broadcast.putExtra("time", time);

            // Save new time
            editor.putLong("TimeStamp", new Date().getTime() + time);
            editor.putInt("LastTime", time);

            // editor.putString("NotificationUri", thisAdvTime[1]);

            mNM.cancelAll();
            Log.v(TAG, "Starting next iteration of the timer service ...");
            Intent rintent = new Intent(context, TimerReceiver.class);
            rintent.putExtra("SetTime", time);
            PendingIntent mPendingIntent = PendingIntent.getBroadcast(context, 0, rintent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            AlarmManager mAlarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            mAlarmMgr.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + time, mPendingIntent);
        } else {
            broadcast.putExtra("stop", true);
            editor.putInt("advTimeIndex", 1);

        }
        broadcast.setAction(BROADCAST_RESET);
        context.sendBroadcast(broadcast);

        editor.apply();

    } else if (prefs.getBoolean("AutoRestart", false)) {
        int time = pintent.getIntExtra("SetTime", 0);
        if (time != 0) {

            mNM.cancel(0);
            Log.v(TAG, "Restarting the timer service ...");
            Intent rintent = new Intent(context, TimerReceiver.class);
            rintent.putExtra("SetTime", time);
            PendingIntent mPendingIntent = PendingIntent.getBroadcast(context, 0, rintent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            AlarmManager mAlarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            mAlarmMgr.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + time, mPendingIntent);

            // Save new time
            SharedPreferences.Editor editor = prefs.edit();
            editor.putLong("TimeStamp", new Date().getTime() + time);
            editor.putInt("LastTime", time);
            editor.apply();

            Intent broadcast = new Intent();
            broadcast.putExtra("time", time);
            broadcast.setAction(BROADCAST_RESET);
            context.sendBroadcast(broadcast);

        }
    }

    mNotificationManager.notify(0, mBuilder.build());

    Log.d(TAG, "ALARM: alarm finished");

}

From source file:com.dwdesign.tweetings.activity.HomeActivity.java

@Override
public void onResume() {
    super.onResume();
    invalidateSupportOptionsMenu();/*from  ww  w. ja va  2 s. co  m*/

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

    if (!hasStreamLoaded || isStreamChanged()) {
        hasStreamLoaded = false;
        connectToStream();
    }

    if (isPushChanged() && mPushNotifications) {
        mApplication.registerPush();
    }

}

From source file:org.catrobat.catroid.uitest.util.UiTestUtils.java

public static void cancelAllNotifications(Context context) {
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.cancelAll();

    @SuppressWarnings("unchecked")
    SparseArray<NotificationData> notificationMap = (SparseArray<NotificationData>) Reflection.getPrivateField(
            StatusBarNotificationManager.class, StatusBarNotificationManager.getInstance(),
            "notificationDataMap");
    notificationMap.clear();/*from  w  w  w  .  j a  v a2s  . co m*/
}

From source file:im.vector.services.EventStreamService.java

/**
 * Clear any displayed notification./*from   w  w  w .j a  v  a 2 s.co  m*/
 */
private void clearNotification() {
    Log.d(LOG_TAG, "clearNotification " + mNotificationSessionId + " - " + mNotificationRoomId + " - "
            + mNotificationEventId);

    NotificationManager nm = (NotificationManager) EventStreamService.this
            .getSystemService(Context.NOTIFICATION_SERVICE);
    nm.cancelAll();

    // reset the identifiers
    mNotificationSessionId = null;
    mNotificationRoomId = null;
    mNotificationEventId = null;
    mLatestNotification = null;
}

From source file:com.paywith.ibeacon.service.IBeaconService.java

@Override
@TargetApi(18)//from w w w .  j ava  2 s  . co  m
public void onDestroy() {
    Log.e("service", "onDestroy()");
    if (android.os.Build.VERSION.SDK_INT < 18) {
        Log.w(TAG, "Not supported prior to API 18.");
        return;
    }
    setNextLaunchUrl(null);
    bluetoothCrashResolver.stop();
    Log.i(TAG, "onDestroy called.  stopping scanning");
    handler.removeCallbacksAndMessages(null);
    scanLeDevice(false);
    if (bluetoothAdapter != null) {
        bluetoothAdapter.stopLeScan((BluetoothAdapter.LeScanCallback) getLeScanCallback());
        lastScanEndTime = new Date().getTime();
    }
    // remove any remaining system notifications that this service has generated
    NotificationManager notificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);
    notificationManager.cancelAll();

}

From source file:im.neon.services.EventStreamService.java

/**
 * Clear any displayed notification.//  w w w.j  a v a2  s .  c o  m
 */
private void clearNotification() {
    Log.d(LOG_TAG, "clearNotification " + mNotificationSessionId + " - " + mNotificationRoomId + " - "
            + mNotificationEventId);

    NotificationManager nm = (NotificationManager) EventStreamService.this
            .getSystemService(Context.NOTIFICATION_SERVICE);
    try {
        nm.cancelAll();
    } catch (Exception e) {
        Log.e(LOG_TAG, "## clearNotification() failed " + e.getMessage());
    }

    // reset the identifiers
    mNotificationSessionId = null;
    mNotificationRoomId = null;
    mNotificationEventId = null;
    mLatestNotification = null;
}

From source file:com.ibm.mobilefirstplatform.clientsdk.android.push.api.MFPPush.java

private void cancelAllNotification() {
    NotificationManager notificationManager = (NotificationManager) appContext
            .getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.cancelAll();
}

From source file:im.neon.services.EventStreamService.java

/**
 * Trigger the latest prepared notification
 * @param checkNotification true to check if the prepared notification still makes sense.
 */// www  . j  a v  a 2 s .  c  o  m
public void triggerPreparedNotification(boolean checkNotification) {
    if (null != mLatestNotification) {
        if (checkNotification) {
            // check first if the message has not been read
            checkNotification();
        }

        // if it is still defined.
        if (null != mLatestNotification) {
            try {
                NotificationManager nm = (NotificationManager) EventStreamService.this
                        .getSystemService(Context.NOTIFICATION_SERVICE);
                nm.cancelAll();
                nm.notify(NOTIF_ID_MESSAGE, mLatestNotification);

                // turn the screen on
                if (mGcmRegistrationManager.isScreenTurnedOn()) {
                    // turn the screen on for 3 seconds
                    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
                    PowerManager.WakeLock wl = pm.newWakeLock(
                            PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP,
                            "MXEventListener");
                    wl.acquire(3000);
                    wl.release();
                }

            } catch (Exception e) {
                Log.e(LOG_TAG, "onLiveEventsChunkProcessed crashed " + e.getLocalizedMessage());
            }

            mLatestNotification = null;
        }
    }
}