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:com.google.samples.apps.iosched.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);/*ww  w  .j a v  a2 s.  c  o m*/
    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;
    }

    // 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.iosched")
            .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);
}

From source file:com.razza.apps.iosched.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);/*from   ww w.j a  va 2  s . c om*/
    final long currentTime = UIUtils.getCurrentTime(this);
    // If the session is already started, do not schedule system notification.
    if (currentTime > sessionStart) {
        LogUtils.LOGD(TAG, "Not scheduling alarm because target time is in the past: " + sessionStart);
        return;
    }

    // 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;
    }

    LogUtils.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.razza.apps.iosched").path(String.valueOf(sessionStart)).build());
    notifIntent.putExtra(SessionAlarmService.EXTRA_SESSION_START, sessionStart);
    LogUtils.LOGD(TAG, "-> Intent extra: session start " + sessionStart);
    notifIntent.putExtra(SessionAlarmService.EXTRA_SESSION_END, sessionEnd);
    LogUtils.LOGD(TAG, "-> Intent extra: session end " + sessionEnd);
    notifIntent.putExtra(SessionAlarmService.EXTRA_SESSION_ALARM_OFFSET, alarmOffset);
    LogUtils.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.
    LogUtils.LOGD(TAG, "-> Scheduling RTC_WAKEUP alarm at " + alarmTime);
    am.set(AlarmManager.RTC_WAKEUP, alarmTime, pi);
}

From source file:com.twofours.surespot.services.SurespotGcmListenerService.java

private void generateNotification(Context context, String type, String from, String to, String title,
        String message, String tag, int id) {
    SurespotLog.d(TAG, "generateNotification");
    // get shared prefs
    SharedPreferences pm = context.getSharedPreferences(to, Context.MODE_PRIVATE);
    if (!pm.getBoolean("pref_notifications_enabled", true)) {
        return;/*from w w w. ja v  a  2s .  co m*/
    }

    int icon = R.drawable.surespot_logo;

    // need to use same builder for only alert once to work:
    // http://stackoverflow.com/questions/6406730/updating-an-ongoing-notification-quietly
    mBuilder.setSmallIcon(icon).setContentTitle(title).setAutoCancel(true).setOnlyAlertOnce(false)
            .setContentText(message);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);

    Intent mainIntent = null;
    mainIntent = new Intent(context, MainActivity.class);
    mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    mainIntent.putExtra(SurespotConstants.ExtraNames.MESSAGE_TO, to);
    mainIntent.putExtra(SurespotConstants.ExtraNames.MESSAGE_FROM, from);
    mainIntent.putExtra(SurespotConstants.ExtraNames.NOTIFICATION_TYPE, type);

    stackBuilder.addNextIntent(mainIntent);

    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent((int) new Date().getTime(),
            PendingIntent.FLAG_CANCEL_CURRENT);

    mBuilder.setContentIntent(resultPendingIntent);
    int defaults = 0;

    boolean showLights = pm.getBoolean("pref_notifications_led", true);
    boolean makeSound = pm.getBoolean("pref_notifications_sound", true);
    boolean vibrate = pm.getBoolean("pref_notifications_vibration", true);
    int color = pm.getInt("pref_notification_color", getResources().getColor(R.color.surespotBlue));

    if (showLights) {
        SurespotLog.v(TAG, "showing notification led");
        mBuilder.setLights(color, 500, 5000);
        defaults |= Notification.FLAG_SHOW_LIGHTS; // shouldn't need this - setLights does it.  Just to make sure though...
    } else {
        mBuilder.setLights(color, 0, 0);
    }

    if (makeSound) {
        SurespotLog.v(TAG, "making notification sound");
        defaults |= Notification.DEFAULT_SOUND;
    }

    if (vibrate) {
        SurespotLog.v(TAG, "vibrating notification");
        defaults |= Notification.DEFAULT_VIBRATE;
    }

    mBuilder.setDefaults(defaults);
    mNotificationManager.notify(tag, id, mBuilder.build());
}

From source file:com.example.controller.cast.CastRemoteDisplayActivity.java

private void startCastService(CastDevice castDevice) {
    Intent intent = new Intent(CastRemoteDisplayActivity.this, CastRemoteDisplayActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent notificationPendingIntent = PendingIntent.getActivity(CastRemoteDisplayActivity.this, 0,
            intent, PendingIntent.FLAG_CANCEL_CURRENT);

    CastRemoteDisplayLocalService.NotificationSettings settings = new CastRemoteDisplayLocalService.NotificationSettings.Builder()
            .setNotificationPendingIntent(notificationPendingIntent).build();

    CastRemoteDisplayLocalService.Callbacks callbacks = new CastRemoteDisplayLocalService.Callbacks() {
        @Override/* ww  w. j a  v a 2  s.com*/
        public void onServiceCreated(CastRemoteDisplayLocalService service) {
            //TODO start a certain presentation here

            Log.d(TAG, "onServiceCreated");
        }

        @Override
        public void onRemoteDisplaySessionStarted(CastRemoteDisplayLocalService service) {
            createPresentation((CastServiceController) service);
            Log.d(TAG, "onServiceStarted");
        }

        @Override
        public void onRemoteDisplaySessionError(Status errorReason) {
            int code = errorReason.getStatusCode();
            Log.d(TAG, "onServiceError: " + errorReason.getStatusCode());
            initError();

            mCastDevice = null;
            CastRemoteDisplayActivity.this.finish();
        }
    };

    CastRemoteDisplayLocalService.startService(CastRemoteDisplayActivity.this, RemoteDisplayService.class,
            getString(R.string.app_id), castDevice, settings, callbacks);
}

From source file:com.darshancomputing.alockblock.ALockBlockService.java

private void maximize() {
    mNotificationManager.cancelAll();//from  ww w .j a  v  a 2s  .  c  o m
    stopForeground(true);

    Intent mainWindowIntent = new Intent(context, ALockBlockActivity.class);
    mainWindowPendingIntent = PendingIntent.getActivity(context, 0, mainWindowIntent, 0);

    ComponentName comp = new ComponentName(getPackageName(), ALockBlockService.class.getName());
    Intent reEnableIntent = new Intent().setComponent(comp).putExtra(EXTRA_ACTION, ACTION_REENABLE);
    PendingIntent reEnablePendingIntent = PendingIntent.getService(this, 0, reEnableIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);

    NotificationCompat.Builder kgunb = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.kg_unlocked)
            .setLargeIcon(largeIconU).setContentTitle("Lock Screen Disabled").setContentText("A Lock Block")
            .setContentIntent(mainWindowPendingIntent).setShowWhen(false).setOngoing(true)
            .setPriority(NotificationCompat.PRIORITY_MAX);

    if (settings.getBoolean(SettingsActivity.KEY_REENABLE_FROM_NOTIFICATION, false))
        kgunb.addAction(R.drawable.ic_menu_login, "Re-enable", reEnablePendingIntent);

    startForeground(NOTIFICATION_KG_UNLOCKED, kgunb.build());
}

From source file:com.saarang.samples.apps.iosched.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);/*w  w w .  jav a2 s .  c  o  m*/
    final long currentTime = UIUtils.getCurrentTime(this);
    // If the session is already started, do not schedule system notification.
    if (currentTime > sessionStart) {
        LogUtils.LOGD(TAG, "Not scheduling alarm because target time is in the past: " + sessionStart);
        return;
    }

    // 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;
    }

    LogUtils.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.saarang.samples.apps.iosched")
            .path(String.valueOf(sessionStart)).build());
    notifIntent.putExtra(SessionAlarmService.EXTRA_SESSION_START, sessionStart);
    LogUtils.LOGD(TAG, "-> Intent extra: session start " + sessionStart);
    notifIntent.putExtra(SessionAlarmService.EXTRA_SESSION_END, sessionEnd);
    LogUtils.LOGD(TAG, "-> Intent extra: session end " + sessionEnd);
    notifIntent.putExtra(SessionAlarmService.EXTRA_SESSION_ALARM_OFFSET, alarmOffset);
    LogUtils.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.
    LogUtils.LOGD(TAG, "-> Scheduling RTC_WAKEUP alarm at " + alarmTime);
    am.set(AlarmManager.RTC_WAKEUP, alarmTime, pi);
}

From source file:org.pixmob.freemobile.netstat.MonitorService.java

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override//from ww w.j  a v a2s  .c  o m
public void onCreate() {
    super.onCreate();

    pm = (PowerManager) getSystemService(POWER_SERVICE);
    tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
    cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);

    prefs = getSharedPreferences(SP_NAME, MODE_PRIVATE);
    prefs.registerOnSharedPreferenceChangeListener(this);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        final int largeIconWidth = getResources()
                .getDimensionPixelSize(android.R.dimen.notification_large_icon_width);
        final int largeIconHeight = getResources()
                .getDimensionPixelSize(android.R.dimen.notification_large_icon_height);
        if ((largeIconWidth > 0) && (largeIconHeight > 0)) {
            Bitmap freeLargeIconTmp = BitmapFactory.decodeResource(getResources(),
                    R.drawable.ic_stat_notify_service_free_large);
            if ((freeLargeIconTmp != null) && (freeLargeIconTmp.getWidth() > 0)
                    && (freeLargeIconTmp.getHeight() > 0)) {
                freeLargeIcon = Bitmap.createScaledBitmap(freeLargeIconTmp, largeIconWidth, largeIconHeight,
                        true);
            }

            Bitmap freeFemtoLargeIconTmp = BitmapFactory.decodeResource(getResources(),
                    R.drawable.ic_stat_notify_service_free_femto_large);
            if ((freeFemtoLargeIconTmp != null) && (freeFemtoLargeIconTmp.getHeight() > 0)
                    && (freeFemtoLargeIconTmp.getWidth() > 0)) {
                freeFemtoLargeIcon = Bitmap.createScaledBitmap(freeFemtoLargeIconTmp, largeIconWidth,
                        largeIconHeight, true);
            }

            Bitmap orangeLargeIconTmp = BitmapFactory.decodeResource(getResources(),
                    R.drawable.ic_stat_notify_service_orange_large);
            if ((orangeLargeIconTmp != null) && (orangeLargeIconTmp.getHeight() > 0)
                    && (orangeLargeIconTmp.getWidth() > 0)) {
                orangeLargeIcon = Bitmap.createScaledBitmap(orangeLargeIconTmp, largeIconWidth, largeIconHeight,
                        true);
            }
        }
    }

    // Initialize and start a worker thread for inserting rows into the
    // application database.
    final Context c = getApplicationContext();
    pendingInsert = new ArrayBlockingQueue<>(8);
    new PendingInsertWorker(c, pendingInsert).start();

    // This intent is fired when the application notification is clicked.
    openUIPendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_NOTIFICATION),
            PendingIntent.FLAG_CANCEL_CURRENT);

    // This intent is only available as a Jelly Bean notification action in
    // order to open network operator settings.
    Intent networkSettingsIntent = IntentFactory.networkOperatorSettings(this);
    if (networkSettingsIntent != null) {
        networkOperatorSettingsPendingIntent = PendingIntent.getActivity(this, 0, networkSettingsIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);
    }
    Intent wirelessSettingsIntent = IntentFactory.wirelessSettings(this);
    if (wirelessSettingsIntent != null) {
        wirelessSettingsPendingIntent = PendingIntent.getActivity(this, 0, wirelessSettingsIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);
    }

    // Watch screen light: is the screen on?
    screenMonitor = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            updateEventDatabase();
        }
    };

    final IntentFilter screenIntentFilter = new IntentFilter();
    screenIntentFilter.addAction(Intent.ACTION_SCREEN_ON);
    screenIntentFilter.addAction(Intent.ACTION_SCREEN_OFF);
    registerReceiver(screenMonitor, screenIntentFilter);

    // Watch Wi-Fi connections.
    connectionMonitor = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (onConnectivityUpdated()) {
                updateEventDatabase();
            }
        }
    };

    final IntentFilter connectionIntentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
    registerReceiver(connectionMonitor, connectionIntentFilter);

    // Watch mobile connections.
    phoneMonitor = new PhoneStateListener() {
        @Override
        public void onDataConnectionStateChanged(int state, int networkType) {
            updateService();
        }

        @Override
        public void onServiceStateChanged(ServiceState serviceState) {
            if (stopServiceIfSimOperatorIsNotFreeMobile())
                return;

            mobileNetworkConnected = (serviceState != null)
                    && (serviceState.getState() == ServiceState.STATE_IN_SERVICE);

            updateService();
        }

        @Override
        public void onCellInfoChanged(List<CellInfo> cellInfo) {
            updateService();
        }

        private void updateService() {
            if (tm != null) { // Fix NPE - found by Acralyzer
                mobileNetworkType = tm.getNetworkType(); //update the network type to have the latest
            }
            final int phoneStateUpdated = onPhoneStateUpdated();
            if (phoneStateUpdated >= 0)
                updateEventDatabase();

            updateNotification(true, phoneStateUpdated == 1);
        }
    };
    int events = PhoneStateListener.LISTEN_SERVICE_STATE | PhoneStateListener.LISTEN_DATA_CONNECTION_STATE;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
        events |= PhoneStateListener.LISTEN_CELL_INFO;

    tm.listen(phoneMonitor, events);

    // Watch battery level.
    batteryMonitor = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            updateEventDatabase();
        }
    };

    batteryIntentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    registerReceiver(batteryMonitor, batteryIntentFilter);

    shutdownMonitor = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            onDeviceShutdown();
        }
    };
    final IntentFilter shutdownIntentFilter = new IntentFilter();
    shutdownIntentFilter.addAction(Intent.ACTION_SHUTDOWN);
    // HTC devices use a different Intent action:
    // http://stackoverflow.com/q/5076410/422906
    shutdownIntentFilter.addAction("android.intent.action.QUICKBOOT_POWEROFF");
    registerReceiver(shutdownMonitor, shutdownIntentFilter);

    if (prefs.getBoolean(SP_KEY_ENABLE_AUTO_RESTART_SERVICE, false) && Arrays
            .asList(ANDROID_VERSIONS_ALLOWED_TO_AUTO_RESTART_SERVICE).contains(Build.VERSION.RELEASE)) {
        // Kitkat and JellyBean auto-kill service workaround
        // http://stackoverflow.com/a/20735519/1527491
        ensureServiceStaysRunning();
    }
}

From source file:com.atlas.mars.weatherradar.MainActivity.java

void morningAlarmCancel() {
    if (pIntent2 != null && alarmManagerMorning != null) {
        pIntent2 = PendingIntent.getBroadcast(this, 0, morningIntent, PendingIntent.FLAG_CANCEL_CURRENT);
        alarmManagerMorning.cancel(pIntent1);
    }// w w w  .ja va2 s .co m
}

From source file:com.ksk.droidbatterybooster.provider.TimeSchedule.java

/**
 * @param id Schedule ID./*from  ww w  .  ja  v  a 2  s.  c  o m*/
 * 
 */
static void disableAction(Context context) {
    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    PendingIntent sender = PendingIntent.getBroadcast(context, 0, new Intent(EXECUTE_SCHEDULE_ACTION),
            PendingIntent.FLAG_CANCEL_CURRENT);
    am.cancel(sender);
    saveNextAlarm(context, "");
}

From source file:com.sean.takeastand.storage.ScheduleEditor.java

private void setDailyRepeatingAlarm(int UID, String time) {
    Intent intent = new Intent(mContext, StartScheduleReceiver.class);
    intent.putExtra(Constants.ALARM_UID, UID);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, UID, intent,
            PendingIntent.FLAG_CANCEL_CURRENT);
    ((AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE)).setRepeating(AlarmManager.RTC_WAKEUP,
            nextAlarmTime(time).getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
    Log.i(TAG, "Set Daily Repeating alarm for " + Long.toString(nextAlarmTime(time).getTimeInMillis())
            + " current time " + Long.toString(System.currentTimeMillis()));
}