List of usage examples for android.app PendingIntent FLAG_CANCEL_CURRENT
int FLAG_CANCEL_CURRENT
To view the source code for android.app PendingIntent FLAG_CANCEL_CURRENT.
Click Source Link
From source file:org.hansel.myAlert.Rastreo.java
private PendingIntent getPendingAlarm() { Intent intent = new Intent(getActivity().getApplicationContext(), AlarmReceiver.class); PendingIntent pendingIntent = PendingIntent.getActivity(getActivity(), RQS_1, intent, PendingIntent.FLAG_CANCEL_CURRENT); return pendingIntent; }
From source file:com.google.android.apps.iosched.calendar.SessionAlarmService.java
/** * Constructs and triggers system notification for when starred sessions are about to begin. *//* w w w . java 2 s .c om*/ @TargetApi(Build.VERSION_CODES.JELLY_BEAN) private void notifySession(final long sessionStart, final long sessionEnd, final long alarmOffset) { long currentTime = System.currentTimeMillis(); if (sessionStart < currentTime) { return; } // Avoid repeated notifications. if (alarmOffset == UNDEFINED_ALARM_OFFSET && UIUtils.isNotificationFiredForBlock(this, ScheduleContract.Blocks.generateBlockId(sessionStart, sessionEnd))) { return; } final ContentResolver resolver = getContentResolver(); final Uri starredBlockUri = ScheduleContract.Blocks .buildStarredSessionsUri(ScheduleContract.Blocks.generateBlockId(sessionStart, sessionEnd)); Cursor cursor = resolver.query(starredBlockUri, new String[] { ScheduleContract.Blocks.NUM_STARRED_SESSIONS, ScheduleContract.Sessions.SESSION_TITLE }, null, null, null); int starredCount = 0; ArrayList<String> starredSessionTitles = new ArrayList<String>(); while (cursor.moveToNext()) { starredSessionTitles.add(cursor.getString(1)); starredCount = cursor.getInt(0); } if (starredCount < 1) { return; } // Generates the pending intent which gets fired when the user touches on the notification. Intent sessionIntent = new Intent(Intent.ACTION_VIEW, starredBlockUri); sessionIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pi = PendingIntent.getActivity(this, 0, sessionIntent, PendingIntent.FLAG_CANCEL_CURRENT); final Resources res = getResources(); String contentText; int minutesLeft = (int) (sessionStart - currentTime + 59000) / 60000; if (minutesLeft < 1) { minutesLeft = 1; } if (starredCount == 1) { contentText = res.getString(R.string.session_notification_text_1, minutesLeft); } else { contentText = res.getQuantityString(R.plurals.session_notification_text, starredCount - 1, minutesLeft, starredCount - 1); } // Construct a notification. Use Jelly Bean (API 16) rich notifications if possible. Notification notification; if (UIUtils.hasJellyBean()) { // Rich notifications Notification.Builder builder = new Notification.Builder(this) .setContentTitle(starredSessionTitles.get(0)).setContentText(contentText) .setTicker(res .getQuantityString(R.plurals.session_notification_ticker, starredCount, starredCount)) .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE) .setLights(SessionAlarmService.NOTIFICATION_ARGB_COLOR, SessionAlarmService.NOTIFICATION_LED_ON_MS, SessionAlarmService.NOTIFICATION_LED_OFF_MS) .setSmallIcon(R.drawable.ic_stat_notification).setContentIntent(pi) .setPriority(Notification.PRIORITY_MAX).setAutoCancel(true); if (minutesLeft > 5) { builder.addAction(R.drawable.ic_alarm_holo_dark, String.format(res.getString(R.string.snooze_x_min), 5), createSnoozeIntent(sessionStart, sessionEnd, 5)); } Notification.InboxStyle richNotification = new Notification.InboxStyle(builder) .setBigContentTitle(res.getQuantityString(R.plurals.session_notification_title, starredCount, minutesLeft, starredCount)); // Adds starred sessions starting at this time block to the notification. for (int i = 0; i < starredCount; i++) { richNotification.addLine(starredSessionTitles.get(i)); } notification = richNotification.build(); } else { // Pre-Jelly Bean non-rich notifications notification = new NotificationCompat.Builder(this).setContentTitle(starredSessionTitles.get(0)) .setContentText(contentText) .setTicker(res .getQuantityString(R.plurals.session_notification_ticker, starredCount, starredCount)) .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE) .setLights(SessionAlarmService.NOTIFICATION_ARGB_COLOR, SessionAlarmService.NOTIFICATION_LED_ON_MS, SessionAlarmService.NOTIFICATION_LED_OFF_MS) .setSmallIcon(R.drawable.ic_stat_notification).setContentIntent(pi).getNotification(); } NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); nm.notify(NOTIFICATION_ID, notification); }
From source file:com.customprogrammingsolutions.MediaStreamer.MediaStreamerService.java
private void startNotification() { NotificationCompat.Builder builder = new NotificationCompat.Builder(this); RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custom_notification_layout); contentView.setImageViewResource(R.id.notification_icon, R.drawable.notification_icon); contentView.setTextViewText(R.id.notification_title, getString(R.string.notification_title)); contentView.setTextViewText(R.id.notification_text, urlToStream); if (isPreparing) { contentView.setImageViewResource(R.id.media_state_indicator_icon, R.drawable.notification_playback_loading); contentView.setOnClickPendingIntent(R.id.media_state_indicator_icon, PendingIntent.getActivity(getApplicationContext(), 0, new Intent(), 0)); } else if (isStreamError) { contentView.setImageViewResource(R.id.media_state_indicator_icon, R.drawable.notification_playback_error); contentView.setOnClickPendingIntent(R.id.media_state_indicator_icon, PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0)); } else if (isPlaying) { contentView.setImageViewResource(R.id.media_state_indicator_icon, R.drawable.stop_button); PendingIntent stopIntentPending = PendingIntent.getService(this, 0, new Intent(MainActivity.STOP_INTENT), PendingIntent.FLAG_CANCEL_CURRENT); contentView.setOnClickPendingIntent(R.id.media_state_indicator_icon, stopIntentPending); } else {/*from w w w .j a va2 s . c o m*/ contentView.setImageViewResource(R.id.media_state_indicator_icon, R.drawable.play_button); Intent playIntent = new Intent(MainActivity.PLAY_INTENT); playIntent.putExtra(MainActivity.URL_EXTRA, urlToStream); PendingIntent playIntentPending = PendingIntent.getService(this, 0, playIntent, PendingIntent.FLAG_CANCEL_CURRENT); contentView.setOnClickPendingIntent(R.id.media_state_indicator_icon, playIntentPending); } PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0); contentView.setOnClickPendingIntent(R.id.notification_layout, contentIntent); PendingIntent killIntentPending = PendingIntent.getService(this, 0, new Intent(MainActivity.KILL_SERVICE_INTENT), 0); contentView.setOnClickPendingIntent(R.id.close_notification_icon, killIntentPending); builder.setContent(contentView); builder.setSmallIcon(R.drawable.notification_icon); builder.setAutoCancel(false); startForeground(NOTIFICATION_ID, builder.build()); }
From source file:com.drinviewer.droiddrinviewer.DrinViewerBroadcastReceiver.java
/** * Starts the alarm repeater after a disconnection from a WiFi network. * The alarm is firing request to discover server at regular time interval * // ww w . j a v a 2 s .c om * @param context The context to use * @return true on success */ private boolean startAlarmRepeater(Context context) { boolean returnValue = false; // Gets the Binder to the DiscoverServerService IBinder b = peekService(context, new Intent(context, DiscoverServerService.class)); DiscoverServerApi discoverServerApi = DiscoverServerApi.Stub.asInterface(b); // start the alarm repeater only if the api exists and the discover process in not running try { if (b != null && discoverServerApi != null && !discoverServerApi.isRunning()) { // Get the alarm manager if (alarmManager == null) alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); // Instantiate the intent and set its action Intent i = new Intent(context, this.getClass()); i.setAction(context.getResources().getString(R.string.broadcast_startdiscovery)); // send the wifiBroadcastAddress together with the intent i.putExtra("wifiBroadcastAddress", wifiBroadcastAddress); // Get the broadcast PendingIntent pending = PendingIntent.getBroadcast(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT); if (pending != null) { Calendar cal = Calendar.getInstance(); // cancel the alarm alarmManager.cancel(pending); // Run the intent immediately and schedule repeating at fixed time intervals context.sendBroadcast(i); alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis() + DroidDrinViewerConstants.DISCOVER_REPEAT_TIME, DroidDrinViewerConstants.DISCOVER_REPEAT_TIME, pending); returnValue = true; } } } catch (RemoteException e) { e.printStackTrace(); returnValue = false; } return returnValue; }
From source file:org.leopub.mat.service.MessageService.java
public static void cancelUpdate(Context context) { Intent i = new Intent(context, MessageService.class); PendingIntent pi = PendingIntent.getService(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT); AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); alarmManager.cancel(pi);//from w ww .j a va 2 s .c o m pi.cancel(); }
From source file:org.totschnig.myexpenses.sync.SyncAdapter.java
@Override public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {/*from w ww . ja va 2 s .c o m*/ categoryToId = new HashMap<>(); payeeToId = new HashMap<>(); methodToId = new HashMap<>(); accountUuidToId = new HashMap<>(); String uuidFromExtras = extras.getString(KEY_UUID); Timber.i("onPerformSync " + extras.toString()); AccountManager accountManager = AccountManager.get(getContext()); Exceptional<SyncBackendProvider> backendProviderExceptional = SyncBackendProviderFactory.get(getContext(), account); SyncBackendProvider backend; try { backend = backendProviderExceptional.getOrThrow(); } catch (Throwable throwable) { syncResult.databaseError = true; AcraHelper.report(throwable instanceof Exception ? ((Exception) throwable) : new Exception(throwable)); GenericAccountService.deactivateSync(account); accountManager.setUserData(account, GenericAccountService.KEY_BROKEN, "1"); String content = String.format(Locale.ROOT, "The backend could not be instantiated.Reason: %s. Please try to delete and recreate it.", throwable.getMessage()); Intent manageIntent = new Intent(getContext(), ManageSyncBackends.class); NotificationBuilderWrapper builder = NotificationBuilderWrapper .defaultBigTextStyleBuilder(getContext(), "Synchronization backend deactivated", content) .setContentIntent(PendingIntent.getActivity(getContext(), 0, manageIntent, PendingIntent.FLAG_CANCEL_CURRENT)); Notification notification = builder.build(); notification.flags = Notification.FLAG_AUTO_CANCEL; ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(0, notification); return; } if (!backend.setUp()) { syncResult.stats.numIoExceptions++; syncResult.delayUntil = 300; return; } String autoBackupFileUri = extras.getString(KEY_UPLOAD_AUTO_BACKUP); if (autoBackupFileUri != null) { try { backend.storeBackup(Uri.parse(autoBackupFileUri)); } catch (IOException e) { String content = getContext().getString(R.string.auto_backup_cloud_failure, autoBackupFileUri, account.name) + " " + e.getMessage(); Notification notification = NotificationBuilderWrapper.defaultBigTextStyleBuilder(getContext(), getContext().getString(R.string.pref_auto_backup_title), content).build(); notification.flags = Notification.FLAG_AUTO_CANCEL; ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(0, notification); } return; } Cursor c; String[] selectionArgs; String selection = KEY_SYNC_ACCOUNT_NAME + " = ?"; if (uuidFromExtras != null) { selection += " AND " + KEY_UUID + " = ?"; selectionArgs = new String[] { account.name, uuidFromExtras }; } else { selectionArgs = new String[] { account.name }; } String[] projection = { KEY_ROWID }; try { c = provider.query(TransactionProvider.ACCOUNTS_URI, projection, selection + " AND " + KEY_SYNC_SEQUENCE_LOCAL + " = 0", selectionArgs, null); } catch (RemoteException e) { syncResult.databaseError = true; AcraHelper.report(e); return; } if (c == null) { syncResult.databaseError = true; AcraHelper.report("Cursor is null"); return; } if (c.moveToFirst()) { do { long accountId = c.getLong(0); try { provider.update(buildInitializationUri(accountId), new ContentValues(0), null, null); } catch (RemoteException e) { syncResult.databaseError = true; AcraHelper.report(e); return; } } while (c.moveToNext()); } try { c = provider.query(TransactionProvider.ACCOUNTS_URI, projection, selection, selectionArgs, null); } catch (RemoteException e) { syncResult.databaseError = true; AcraHelper.report(e); return; } if (c != null) { if (c.moveToFirst()) { do { long accountId = c.getLong(0); String lastLocalSyncKey = KEY_LAST_SYNCED_LOCAL(accountId); String lastRemoteSyncKey = KEY_LAST_SYNCED_REMOTE(accountId); long lastSyncedLocal = Long .parseLong(getUserDataWithDefault(accountManager, account, lastLocalSyncKey, "0")); long lastSyncedRemote = Long .parseLong(getUserDataWithDefault(accountManager, account, lastRemoteSyncKey, "0")); dbAccount.set(org.totschnig.myexpenses.model.Account.getInstanceFromDb(accountId)); Timber.i("now syncing " + dbAccount.get().label); if (uuidFromExtras != null && extras.getBoolean(KEY_RESET_REMOTE_ACCOUNT)) { if (!backend.resetAccountData(uuidFromExtras)) { syncResult.stats.numIoExceptions++; Timber.e("error resetting account data"); } continue; } if (!backend.withAccount(dbAccount.get())) { syncResult.stats.numIoExceptions++; Timber.e("error withAccount"); continue; } if (backend.lock()) { try { ChangeSet changeSetSince = backend.getChangeSetSince(lastSyncedRemote, getContext()); if (changeSetSince.isFailed()) { syncResult.stats.numIoExceptions++; Timber.e("error getting changeset"); continue; } List<TransactionChange> remoteChanges; lastSyncedRemote = changeSetSince.sequenceNumber; remoteChanges = changeSetSince.changes; List<TransactionChange> localChanges = new ArrayList<>(); long sequenceToTest = lastSyncedLocal + 1; while (true) { List<TransactionChange> nextChanges = getLocalChanges(provider, accountId, sequenceToTest); if (nextChanges.size() > 0) { localChanges.addAll( Stream.of(nextChanges).filter(change -> !change.isEmpty()).toList()); lastSyncedLocal = sequenceToTest; sequenceToTest++; } else { break; } } if (localChanges.size() == 0 && remoteChanges.size() == 0) { continue; } if (localChanges.size() > 0) { localChanges = collectSplits(localChanges); } Pair<List<TransactionChange>, List<TransactionChange>> mergeResult = mergeChangeSets( localChanges, remoteChanges); localChanges = mergeResult.first; remoteChanges = mergeResult.second; if (remoteChanges.size() > 0) { writeRemoteChangesToDb(provider, Stream.of(remoteChanges) .filter(change -> !(change.isCreate() && uuidExists(change.uuid()))) .toList(), accountId); accountManager.setUserData(account, lastRemoteSyncKey, String.valueOf(lastSyncedRemote)); } if (localChanges.size() > 0) { lastSyncedRemote = backend.writeChangeSet(localChanges, getContext()); if (lastSyncedRemote != ChangeSet.FAILED) { if (!BuildConfig.DEBUG) { // on debug build for auditing purposes, we keep changes in the table provider.delete(TransactionProvider.CHANGES_URI, KEY_ACCOUNTID + " = ? AND " + KEY_SYNC_SEQUENCE_LOCAL + " <= ?", new String[] { String.valueOf(accountId), String.valueOf(lastSyncedLocal) }); } accountManager.setUserData(account, lastLocalSyncKey, String.valueOf(lastSyncedLocal)); accountManager.setUserData(account, lastRemoteSyncKey, String.valueOf(lastSyncedRemote)); } } } catch (IOException e) { Timber.e(e, "Error while syncing "); syncResult.stats.numIoExceptions++; } catch (RemoteException | OperationApplicationException | SQLiteException e) { Timber.e(e, "Error while syncing "); syncResult.databaseError = true; AcraHelper.report(e); } finally { if (!backend.unlock()) { Timber.e("Unlocking backend failed"); syncResult.stats.numIoExceptions++; } } } else { //TODO syncResult.delayUntil = ??? syncResult.stats.numIoExceptions++; } } while (c.moveToNext()); } c.close(); } backend.tearDown(); }
From source file:com.atlas.mars.weatherradar.MainActivity.java
@Override protected void onResume() { super.onResume(); if (forecast == null) { //frLayoutCurrent = (FrameLayout) findViewById(R.id.frLayoutCurrent); forecast = new Forecast(this, forecastLinearLayout); } else if (updateForecastIsNeeded()) { if (forecast != null) { forecast.onRegen();/* w ww. j a va 2s . co m*/ } else { // frLayoutCurrent = (FrameLayout) findViewById(R.id.frLayoutCurrent); forecast = new Forecast(this, forecastLinearLayout); } } // startService(new Intent(this, MyService.class)); onCreateMyReceiver(); //setMyTitle(pager.getCurrentItem()); Bundle extras = getIntent().getExtras(); if (pager.getCurrentItem() == 0) { alarmRegenBorispol = (AlarmManager) getSystemService(Context.ALARM_SERVICE); borispolRegenIntent = createIntent("borispolAction", "regetExtras", RegenBorispolBroadCast.class); pIntent3 = PendingIntent.getBroadcast(this, 0, borispolRegenIntent, PendingIntent.FLAG_CANCEL_CURRENT); alarmRegenBorispol.cancel(pIntent3); alarmRegenBorispol.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 2 * 60 * 1000, 2 * 60 * 1000, pIntent3); } Log.d(TAG, "Current page: " + pager.getCurrentItem()); fragmentWeather = new CurrentWeather(); fragmentImageAction = new FragmentImageAction(); fragmentManager = getFragmentManager(); if (!isActivityLeave) { fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.add(R.id.frLayoutCurrent, fragmentWeather); fragmentTransaction.commit(); } ; }
From source file:com.keylesspalace.tusky.MyFirebaseMessagingService.java
private void buildNotification(Notification body) { final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); final SharedPreferences notificationPreferences = getApplicationContext() .getSharedPreferences("Notifications", MODE_PRIVATE); if (!filterNotification(preferences, body)) { return;/*from w ww. j ava 2 s. c o m*/ } String rawCurrentNotifications = notificationPreferences.getString("current", "[]"); JSONArray currentNotifications; try { currentNotifications = new JSONArray(rawCurrentNotifications); } catch (JSONException e) { currentNotifications = new JSONArray(); } boolean alreadyContains = false; for (int i = 0; i < currentNotifications.length(); i++) { try { if (currentNotifications.getString(i).equals(body.account.displayName)) { alreadyContains = true; } } catch (JSONException e) { e.printStackTrace(); } } if (!alreadyContains) { currentNotifications.put(body.account.displayName); } SharedPreferences.Editor editor = notificationPreferences.edit(); editor.putString("current", currentNotifications.toString()); editor.commit(); Intent resultIntent = new Intent(this, MainActivity.class); resultIntent.putExtra("tab_position", 1); TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); stackBuilder.addParentStack(MainActivity.class); stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); Intent deleteIntent = new Intent(this, NotificationClearBroadcastReceiver.class); PendingIntent deletePendingIntent = PendingIntent.getBroadcast(this, 0, deleteIntent, PendingIntent.FLAG_CANCEL_CURRENT); final NotificationCompat.Builder builder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_notify).setContentIntent(resultPendingIntent) .setDeleteIntent(deletePendingIntent).setDefaults(0); // So it doesn't ring twice, notify only in Target callback if (currentNotifications.length() == 1) { builder.setContentTitle(titleForType(body)).setContentText(truncateWithEllipses(bodyForType(body), 40)); Target mTarget = new Target() { @Override public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) { builder.setLargeIcon(bitmap); setupPreferences(preferences, builder); ((NotificationManager) (getSystemService(NOTIFICATION_SERVICE))).notify(NOTIFY_ID, builder.build()); } @Override public void onBitmapFailed(Drawable errorDrawable) { } @Override public void onPrepareLoad(Drawable placeHolderDrawable) { } }; Picasso.with(this).load(body.account.avatar).placeholder(R.drawable.avatar_default) .transform(new RoundedTransformation(7, 0)).into(mTarget); } else { setupPreferences(preferences, builder); try { builder.setContentTitle(String.format(getString(R.string.notification_title_summary), currentNotifications.length())) .setContentText(truncateWithEllipses(joinNames(currentNotifications), 40)); } catch (JSONException e) { e.printStackTrace(); } } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { builder.setVisibility(android.app.Notification.VISIBILITY_PRIVATE); builder.setCategory(android.app.Notification.CATEGORY_SOCIAL); } ((NotificationManager) (getSystemService(NOTIFICATION_SERVICE))).notify(NOTIFY_ID, builder.build()); }
From source file:com.example.android.supportv4.media.MediaNotificationManager.java
private PendingIntent createContentIntent() { Intent openUI = new Intent(mService, MediaBrowserSupport.class); openUI.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); return PendingIntent.getActivity(mService, REQUEST_CODE, openUI, PendingIntent.FLAG_CANCEL_CURRENT); }
From source file:com.kyloth.serleena.sensors.BackgroundLocationManager.java
private void acquireResources() { context.registerReceiver(this, new IntentFilter("SERLEENA_ALARM")); Intent intentToFire = new Intent("SERLEENA_ALARM"); if (pendingIntent != null) am.cancel(pendingIntent);/* w w w .java2 s .c o m*/ pendingIntent = PendingIntent.getBroadcast(context, new Random().nextInt(), intentToFire, PendingIntent.FLAG_CANCEL_CURRENT); am.setInexactRepeating(AlarmManager.RTC_WAKEUP, 0, updateInterval * 1000, pendingIntent); }