List of usage examples for android.app PendingIntent getService
public static PendingIntent getService(Context context, int requestCode, @NonNull Intent intent, @Flags int flags)
From source file:com.android.mail.utils.NotificationActionUtils.java
/** * Creates a {@link PendingIntent} for the specified notification action. *//* w w w.ja v a2 s . c o m*/ private static PendingIntent getNotificationActionPendingIntent(final Context context, final Account account, final Conversation conversation, final Message message, final Folder folder, final Intent notificationIntent, final NotificationActionType action, final int notificationId, final long when) { final Uri messageUri = message.uri; final NotificationAction notificationAction = new NotificationAction(action, account, conversation, message, folder, conversation.id, message.serverId, message.id, when, NotificationAction.SOURCE_LOCAL, notificationId); switch (action) { case REPLY: { // Build a task stack that forces the conversation view on the stack before the // reply activity. final TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context); final Intent intent = createReplyIntent(context, account, messageUri, false); intent.setPackage(context.getPackageName()); intent.setData(conversation.uri); intent.putExtra(ComposeActivity.EXTRA_NOTIFICATION_FOLDER, folder); taskStackBuilder.addNextIntent(notificationIntent).addNextIntent(intent); return taskStackBuilder.getPendingIntent(notificationId, PendingIntent.FLAG_UPDATE_CURRENT); } case REPLY_ALL: { // Build a task stack that forces the conversation view on the stack before the // reply activity. final TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context); final Intent intent = createReplyIntent(context, account, messageUri, true); intent.setPackage(context.getPackageName()); intent.setData(conversation.uri); intent.putExtra(ComposeActivity.EXTRA_NOTIFICATION_FOLDER, folder); taskStackBuilder.addNextIntent(notificationIntent).addNextIntent(intent); return taskStackBuilder.getPendingIntent(notificationId, PendingIntent.FLAG_UPDATE_CURRENT); } case ARCHIVE_REMOVE_LABEL: { final String intentAction = NotificationActionIntentService.ACTION_ARCHIVE_REMOVE_LABEL; final Intent intent = new Intent(intentAction); intent.setPackage(context.getPackageName()); intent.setData(conversation.uri); putNotificationActionExtra(intent, notificationAction); return PendingIntent.getService(context, notificationId, intent, PendingIntent.FLAG_UPDATE_CURRENT); } case DELETE: { final String intentAction = NotificationActionIntentService.ACTION_DELETE; final Intent intent = new Intent(intentAction); intent.setPackage(context.getPackageName()); intent.setData(conversation.uri); putNotificationActionExtra(intent, notificationAction); return PendingIntent.getService(context, notificationId, intent, PendingIntent.FLAG_UPDATE_CURRENT); } } throw new IllegalArgumentException("Invalid NotificationActionType"); }
From source file:com.devalladolid.musictoday.MusicService.java
@Override public void onCreate() { if (D)//from w ww . ja v a 2 s .c om Log.d(TAG, "Creating service"); super.onCreate(); mNotificationManager = NotificationManagerCompat.from(this); // gets a pointer to the playback state store mPlaybackStateStore = MusicPlaybackState.getInstance(this); mSongPlayCount = SongPlayCount.getInstance(this); mRecentStore = RecentStore.getInstance(this); mHandlerThread = new HandlerThread("MusicPlayerHandler", android.os.Process.THREAD_PRIORITY_BACKGROUND); mHandlerThread.start(); mPlayerHandler = new MusicPlayerHandler(this, mHandlerThread.getLooper()); mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); mMediaButtonReceiverComponent = new ComponentName(getPackageName(), MediaButtonIntentReceiver.class.getName()); mAudioManager.registerMediaButtonEventReceiver(mMediaButtonReceiverComponent); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) setUpMediaSession(); mPreferences = getSharedPreferences("Service", 0); mCardId = getCardId(); registerExternalStorageListener(); mPlayer = new MultiPlayer(this); mPlayer.setHandler(mPlayerHandler); // Initialize the intent filter and each action final IntentFilter filter = new IntentFilter(); filter.addAction(SERVICECMD); filter.addAction(TOGGLEPAUSE_ACTION); filter.addAction(PAUSE_ACTION); filter.addAction(STOP_ACTION); filter.addAction(NEXT_ACTION); filter.addAction(PREVIOUS_ACTION); filter.addAction(PREVIOUS_FORCE_ACTION); filter.addAction(REPEAT_ACTION); filter.addAction(SHUFFLE_ACTION); // Attach the broadcast listener registerReceiver(mIntentReceiver, filter); mMediaStoreObserver = new MediaStoreObserver(mPlayerHandler); getContentResolver().registerContentObserver(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, true, mMediaStoreObserver); getContentResolver().registerContentObserver(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, true, mMediaStoreObserver); // Initialize the wake lock final PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName()); mWakeLock.setReferenceCounted(false); final Intent shutdownIntent = new Intent(this, MusicService.class); shutdownIntent.setAction(SHUTDOWN); mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); mShutdownIntent = PendingIntent.getService(this, 0, shutdownIntent, 0); scheduleDelayedShutdown(); reloadQueueAfterPermissionCheck(); notifyChange(QUEUE_CHANGED); notifyChange(META_CHANGED); }
From source file:com.example.android.wearable.wear.wearnotifications.StandaloneMainActivity.java
private void generateBigPictureStyleNotification() { Log.d(TAG, "generateBigPictureStyleNotification()"); // Main steps for building a BIG_PICTURE_STYLE notification: // 0. Get your data // 1. Build the BIG_PICTURE_STYLE // 2. Set up main Intent for notification // 3. Set up RemoteInput, so users can input (keyboard and voice) from notification // 4. Build and issue the notification // 0. Get your data (everything unique per Notification) MockDatabase.BigPictureStyleSocialAppData bigPictureStyleSocialAppData = MockDatabase .getBigPictureStyleData();/* www. jav a 2 s.c o m*/ // 1. Build the BIG_PICTURE_STYLE BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle() // Provides the bitmap for the BigPicture notification .bigPicture( BitmapFactory.decodeResource(getResources(), bigPictureStyleSocialAppData.getBigImage())) // Overrides ContentTitle in the big form of the template .setBigContentTitle(bigPictureStyleSocialAppData.getBigContentTitle()) // Summary line after the detail section in the big form of the template .setSummaryText(bigPictureStyleSocialAppData.getSummaryText()); // 2. Set up main Intent for notification Intent mainIntent = new Intent(this, BigPictureSocialMainActivity.class); PendingIntent mainPendingIntent = PendingIntent.getActivity(this, 0, mainIntent, PendingIntent.FLAG_UPDATE_CURRENT); // 3. Set up a RemoteInput Action, so users can input (keyboard, drawing, voice) directly // from the notification without entering the app. // Create the RemoteInput. String replyLabel = getString(R.string.reply_label); RemoteInput remoteInput = new RemoteInput.Builder(BigPictureSocialIntentService.EXTRA_COMMENT) .setLabel(replyLabel) // List of quick response choices for any wearables paired with the phone .setChoices(bigPictureStyleSocialAppData.getPossiblePostResponses()).build(); // Create PendingIntent for service that handles input. Intent replyIntent = new Intent(this, BigPictureSocialIntentService.class); replyIntent.setAction(BigPictureSocialIntentService.ACTION_COMMENT); PendingIntent replyActionPendingIntent = PendingIntent.getService(this, 0, replyIntent, 0); // Enable action to appear inline on Wear 2.0 (24+). This means it will appear over the // lower portion of the Notification for easy action (only possible for one action). final NotificationCompat.Action.WearableExtender inlineActionForWear2 = new NotificationCompat.Action.WearableExtender() .setHintDisplayActionInline(true).setHintLaunchesActivity(false); NotificationCompat.Action replyAction = new NotificationCompat.Action.Builder( R.drawable.ic_reply_white_18dp, replyLabel, replyActionPendingIntent).addRemoteInput(remoteInput) // Add WearableExtender to enable inline actions .extend(inlineActionForWear2).build(); // 4. Build and issue the notification // Because we want this to be a new notification (not updating a previous notification), we // create a new Builder. Later, we use the same global builder to get back the notification // we built here for a comment on the post. NotificationCompat.Builder notificationCompatBuilder = new NotificationCompat.Builder( getApplicationContext()); GlobalNotificationBuilder.setNotificationCompatBuilderInstance(notificationCompatBuilder); // Build notification notificationCompatBuilder // BIG_PICTURE_STYLE sets title and content .setStyle(bigPictureStyle).setContentTitle(bigPictureStyleSocialAppData.getContentTitle()) .setContentText(bigPictureStyleSocialAppData.getContentText()).setSmallIcon(R.drawable.ic_launcher) .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_person_black_48dp)) .setContentIntent(mainPendingIntent) // Set primary color (important for Wear 2.0 Notifications) .setColor(getResources().getColor(R.color.colorPrimary)) .setSubText(Integer.toString(1)).addAction(replyAction).setCategory(Notification.CATEGORY_SOCIAL) .setPriority(Notification.PRIORITY_HIGH) // Hides content on the lock-screen .setVisibility(Notification.VISIBILITY_PRIVATE) // Notifies system that the main launch intent is an Activity. .extend(new NotificationCompat.WearableExtender().setHintContentIntentLaunchesActivity(true)); // If the phone is in "Do not disturb mode, the user will still be notified if // the sender(s) is starred as a favorite. for (String name : bigPictureStyleSocialAppData.getParticipants()) { notificationCompatBuilder.addPerson(name); } Notification notification = notificationCompatBuilder.build(); mNotificationManagerCompat.notify(NOTIFICATION_ID, notification); // Close app to demonstrate notification in steam. finish(); }
From source file:com.damageddev.myotaskerplugin.services.BackgroundService.java
private NotificationCompat.Builder buildDisconnectNotification() { Intent disconnectIntent = new Intent(ACTION_DISCONNECT); PendingIntent disconnectPendingIntent = PendingIntent.getService(this, 0, disconnectIntent, PendingIntent.FLAG_UPDATE_CURRENT); return new NotificationCompat.Builder(BackgroundService.this).setSmallIcon(R.drawable.ic_launcher) .setContentTitle(getString(R.string.myo_connected)).setOngoing(true) .addAction(R.drawable.ic_disconnect, getString(R.string.disconnect), disconnectPendingIntent); }
From source file:com.androidinspain.deskclock.data.TimerNotificationBuilder.java
Notification buildMissed(Context context, NotificationModel nm, List<Timer> missedTimers) { final Timer timer = missedTimers.get(0); final int count = missedTimers.size(); // Compute some values required below. final long base = getChronometerBase(timer); final String pname = context.getPackageName(); final Resources res = context.getResources(); final Action action; final CharSequence stateText; if (count == 1) { // Single timer is missed. if (TextUtils.isEmpty(timer.getLabel())) { stateText = res.getString(com.androidinspain.deskclock.R.string.missed_timer_notification_label); } else {/*from w ww . java 2s .c o m*/ stateText = res.getString( com.androidinspain.deskclock.R.string.missed_named_timer_notification_label, timer.getLabel()); } // Reset button final Intent reset = new Intent(context, TimerService.class).setAction(TimerService.ACTION_RESET_TIMER) .putExtra(TimerService.EXTRA_TIMER_ID, timer.getId()); @DrawableRes final int icon1 = com.androidinspain.deskclock.R.drawable.ic_reset_24dp; final CharSequence title1 = res.getText(com.androidinspain.deskclock.R.string.timer_reset); final PendingIntent intent1 = Utils.pendingServiceIntent(context, reset); action = new Action.Builder(icon1, title1, intent1).build(); } else { // Multiple missed timers. stateText = res.getString(com.androidinspain.deskclock.R.string.timer_multi_missed, count); final Intent reset = TimerService.createResetMissedTimersIntent(context); @DrawableRes final int icon1 = com.androidinspain.deskclock.R.drawable.ic_reset_24dp; final CharSequence title1 = res.getText(com.androidinspain.deskclock.R.string.timer_reset_all); final PendingIntent intent1 = Utils.pendingServiceIntent(context, reset); action = new Action.Builder(icon1, title1, intent1).build(); } // Intent to load the app and show the timer when the notification is tapped. final Intent showApp = new Intent(context, TimerService.class).setAction(TimerService.ACTION_SHOW_TIMER) .putExtra(TimerService.EXTRA_TIMER_ID, timer.getId()) .putExtra(Events.EXTRA_EVENT_LABEL, com.androidinspain.deskclock.R.string.label_notification); final PendingIntent pendingShowApp = PendingIntent.getService(context, REQUEST_CODE_MISSING, showApp, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT); final Builder notification = new NotificationCompat.Builder(context).setLocalOnly(true).setShowWhen(false) .setAutoCancel(false).setContentIntent(pendingShowApp).setPriority(Notification.PRIORITY_HIGH) .setCategory(NotificationCompat.CATEGORY_ALARM) .setSmallIcon(com.androidinspain.deskclock.R.drawable.stat_notify_timer) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setSortKey(nm.getTimerNotificationMissedSortKey()) .setStyle(new NotificationCompat.DecoratedCustomViewStyle()).addAction(action) .setColor(ContextCompat.getColor(context, com.androidinspain.deskclock.R.color.default_background)); if (Utils.isNOrLater()) { notification.setCustomContentView(buildChronometer(pname, base, true, stateText)) .setGroup(nm.getTimerNotificationGroupKey()); } else { final CharSequence contentText = AlarmUtils.getFormattedTime(context, timer.getWallClockExpirationTime()); notification.setContentText(contentText).setContentTitle(stateText); } return notification.build(); }
From source file:de.schildbach.wallet.WalletApplication.java
public static void scheduleStartBlockchainService(final Context context) { final Configuration config = new Configuration(PreferenceManager.getDefaultSharedPreferences(context)); final long lastUsedAgo = config.getLastUsedAgo(); // apply some backoff final long alarmInterval; if (lastUsedAgo < Constants.LAST_USAGE_THRESHOLD_JUST_MS) alarmInterval = AlarmManager.INTERVAL_FIFTEEN_MINUTES; else if (lastUsedAgo < Constants.LAST_USAGE_THRESHOLD_RECENTLY_MS) alarmInterval = AlarmManager.INTERVAL_HALF_DAY; else/*from w ww . j a va 2 s . c om*/ alarmInterval = AlarmManager.INTERVAL_DAY; log.info("last used {} minutes ago, rescheduling blockchain sync in roughly {} minutes", lastUsedAgo / DateUtils.MINUTE_IN_MILLIS, alarmInterval / DateUtils.MINUTE_IN_MILLIS); final AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); final PendingIntent alarmIntent = PendingIntent.getService(context, 0, new Intent(context, BlockchainServiceImpl.class), 0); alarmManager.cancel(alarmIntent); // workaround for no inexact set() before KitKat final long now = System.currentTimeMillis(); alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, now + alarmInterval, AlarmManager.INTERVAL_DAY, alarmIntent); }
From source file:uk.bowdlerize.service.CensorCensusService.java
private void onProbeFinish() { AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE); Intent i = new Intent(CensorCensusService.this, CensorCensusService.class); i.putExtra(API.EXTRA_POLL, true);// w ww . j a v a2 s .c o m PendingIntent pi = PendingIntent.getService(CensorCensusService.this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT); //If we are polling lets set our next tick if (getSharedPreferences(MainActivity.class.getSimpleName(), Context.MODE_PRIVATE) .getInt(API.SETTINGS_GCM_PREFERENCE, API.SETTINGS_GCM_FULL) == API.SETTINGS_GCM_DISABLED) { am.cancel(pi); // cancel any existing alarms //TODO Setback to 60000 long repeat = (long) (getPreferences(CensorCensusService.this).getInt(API.SETTINGS_FREQUENCY, 1) * 60000);//60000 or 5000 Log.e("onProbeFinish", Long.toString(repeat)); Log.e("onProbeFinish", " - "); Log.e("onProbeFinish", " - "); Log.e("onProbeFinish", " - "); am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + repeat, pi); } else { Log.e("onProbeFinish", "Cancel everything!"); Log.e("onProbeFinish", " - "); Log.e("onProbeFinish", " - "); Log.e("onProbeFinish", " - "); am.cancel(pi); // cancel any existing alarms stopSelf(); } }
From source file:com.horizondigital.delta.UpdateService.java
private PendingIntent getNotificationIntent(boolean delete) { if (delete) { Intent notificationIntent = new Intent(this, UpdateService.class); notificationIntent.setAction(ACTION_NOTIFICATION_DELETED); return PendingIntent.getService(this, 0, notificationIntent, 0); } else {//from w w w. j a v a 2s .c om Intent notificationIntent = new Intent(this, MainActivity.class); notificationIntent.setAction(ACTION_SYSTEM_UPDATE_SETTINGS); return PendingIntent.getActivity(this, 0, notificationIntent, 0); } }
From source file:com.klinker.android.twitter.ui.MainActivity.java
@Override public void onStart() { super.onStart(); MainActivity.isPopup = false;// ww w . ja v a 2s . co m Log.v("talon_starting", "main activity starting"); sharedPrefs = getSharedPreferences("com.klinker.android.twitter_world_preferences", Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE); // check for night mode switching int theme = AppSettings.getCurrentTheme(sharedPrefs); if (!getWindow().hasFeature(Window.FEATURE_ACTION_BAR_OVERLAY) || sharedPrefs.getBoolean("launcher_frag_switch", false) || (theme != settings.theme && !settings.addonTheme)) { sharedPrefs.edit().putBoolean("launcher_frag_switch", false).putBoolean("dont_refresh", true).commit(); AppSettings.invalidate(); Log.v("talon_theme", "no action bar overlay found, recreating"); finish(); overridePendingTransition(0, 0); startActivity(getRestartIntent()); overridePendingTransition(0, 0); MainActivity.caughtstarting = true; // return so that it doesn't start the background refresh, that is what caused the dups. sharedPrefs.edit().putBoolean("dont_refresh_on_start", true).commit(); return; } else { sharedPrefs.edit().putBoolean("dont_refresh", false).putBoolean("should_refresh", true).commit(); } if (DrawerActivity.settings.pushNotifications) { if (!TalonPullNotificationService.isRunning) { context.startService(new Intent(context, TalonPullNotificationService.class)); } } else { context.sendBroadcast(new Intent("com.klinker.android.twitter.STOP_PUSH_SERVICE")); } // cancel the alarm to start the catchup service AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); PendingIntent pendingIntent = PendingIntent.getService(context, 236, new Intent(context, CatchupPull.class), 0); am.cancel(pendingIntent); // cancel the old one, then start the new one in 1 min // clear the pull unread sharedPrefs.edit().putInt("pull_unread", 0).commit(); UpdateUtils.checkUpdate(this); /*new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(1000); } catch (Exception e) { } NotificationUtils.refreshNotification(context); } }).start();*/ }
From source file:com.wojtechnology.sunami.TheBrain.java
private Notification.Builder getLollipopNotifBuilder(boolean isPlaying) { Intent notificationIntent = new Intent(this, MainActivity.class); notificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 1, notificationIntent, 0); Intent serviceLastIntent = new Intent(getApplicationContext(), TheBrain.class); serviceLastIntent.setAction(TheBrain.PLAY_LAST); serviceLastIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); PendingIntent pendingLastIntent = PendingIntent.getService(mContext, 1, serviceLastIntent, 0); Intent servicePlayIntent = new Intent(getApplicationContext(), TheBrain.class); servicePlayIntent.setAction(TheBrain.TOGGLE_PLAY); servicePlayIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); PendingIntent pendingPlayIntent = PendingIntent.getService(mContext, 1, servicePlayIntent, 0); Intent serviceNextIntent = new Intent(getApplicationContext(), TheBrain.class); serviceNextIntent.setAction(TheBrain.PLAY_NEXT); serviceNextIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); PendingIntent pendingNextIntent = PendingIntent.getService(mContext, 1, serviceNextIntent, 0); Intent serviceStopIntent = new Intent(getApplicationContext(), TheBrain.class); serviceStopIntent.setAction(TheBrain.PLAY_STOP); serviceStopIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); PendingIntent pendingStopIntent = PendingIntent.getService(mContext, 1, serviceStopIntent, 0); Notification.MediaStyle style = new Notification.MediaStyle(); style.setShowActionsInCompactView(1, 2); Notification.Builder builder = new Notification.Builder(this).setSmallIcon(R.mipmap.sunaminotif) .setContentIntent(pendingIntent).setStyle(style); builder.addAction(R.drawable.ic_last_hint, "Last", pendingLastIntent); builder.addAction(isPlaying ? R.drawable.ic_pause_hint : R.drawable.ic_play_hint, "Play", pendingPlayIntent);/*w w w . ja va2 s . c om*/ builder.addAction(R.drawable.ic_next_hint, "Next", pendingNextIntent); builder.addAction(R.drawable.ic_stop_notif, "Stop", pendingStopIntent); return builder; }