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.gpsmobitrack.gpstracker.MenuItems.SettingsPage.java
/** * Start the alarm service /*from w w w .jav a 2 s .c om*/ * @param pos */ private void startAlarmService(int pos) { editor.putLong(AppConstants.FREQ_UPDATE_PREF, updateDurationValue[pos]); editor.commit(); int updateTimeint = updateDurationValue[pos]; AlarmManager alarm = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE); Calendar cal = Calendar.getInstance(); Intent intent2 = new Intent(getActivity(), BackgroundService.class); PendingIntent pintent = PendingIntent.getService(getActivity(), 0, intent2, 0); if (PendingIntent.getService(getActivity(), 0, intent2, PendingIntent.FLAG_NO_CREATE) != null) { alarm.cancel(pintent); } alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), (updateTimeint * 1000 * 60), pintent); }
From source file:com.baruckis.nanodegree.spotifystreamer.PlayerService.java
private NotificationCompat.Action generateAction(int icon, String title, String intentAction) { Intent intent = new Intent(getApplicationContext(), PlayerService.class); intent.setAction(intentAction);// ww w .j a v a2s . c om PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 1, intent, 0); return new NotificationCompat.Action.Builder(icon, title, pendingIntent).build(); }
From source file:biz.wiz.android.wallet.WalletApplication.java
public static void scheduleStartBlockchainService(@Nonnull 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/*ww w.ja va 2 s. c o m*/ 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:com.bluros.music.MusicService.java
@Override public void onCreate() { if (D)/*from w ww . j a va 2 s . c o m*/ 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(SLEEP_MODE_STOP_ACTION); filter.addAction(NEXT_ACTION); filter.addAction(PREVIOUS_ACTION); filter.addAction(PREVIOUS_FORCE_ACTION); filter.addAction(REPEAT_ACTION); filter.addAction(SHUFFLE_ACTION); filter.addAction(RemoteSelectDialog.REMOTE_START_SCAN); filter.addAction(RemoteSelectDialog.REMOTE_STOP_SCAN); filter.addAction(RemoteSelectDialog.REMOTE_CONNECT); // 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.androidinspain.deskclock.alarms.AlarmNotifications.java
static synchronized void showAlarmNotification(Service service, AlarmInstance instance) { LogUtils.v("Displaying alarm notification for alarm instance: " + instance.mId); Resources resources = service.getResources(); NotificationCompat.Builder notification = new NotificationCompat.Builder(service) .setContentTitle(instance.getLabelOrDefault(service)) .setContentText(AlarmUtils.getFormattedTime(service, instance.getAlarmTime())) .setColor(ContextCompat.getColor(service, com.androidinspain.deskclock.R.color.default_background)) .setSmallIcon(com.androidinspain.deskclock.R.drawable.stat_notify_alarm).setOngoing(true) .setAutoCancel(false).setDefaults(NotificationCompat.DEFAULT_LIGHTS).setWhen(0) .setCategory(NotificationCompat.CATEGORY_ALARM).setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setLocalOnly(true);/*from w w w . java 2 s . c o m*/ // Setup Snooze Action Intent snoozeIntent = AlarmStateManager.createStateChangeIntent(service, AlarmStateManager.ALARM_SNOOZE_TAG, instance, AlarmInstance.SNOOZE_STATE); snoozeIntent.putExtra(AlarmStateManager.FROM_NOTIFICATION_EXTRA, true); PendingIntent snoozePendingIntent = PendingIntent.getService(service, ALARM_FIRING_NOTIFICATION_ID, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT); notification.addAction(com.androidinspain.deskclock.R.drawable.ic_snooze_24dp, resources.getString(com.androidinspain.deskclock.R.string.alarm_alert_snooze_text), snoozePendingIntent); // Setup Dismiss Action Intent dismissIntent = AlarmStateManager.createStateChangeIntent(service, AlarmStateManager.ALARM_DISMISS_TAG, instance, AlarmInstance.DISMISSED_STATE); dismissIntent.putExtra(AlarmStateManager.FROM_NOTIFICATION_EXTRA, true); PendingIntent dismissPendingIntent = PendingIntent.getService(service, ALARM_FIRING_NOTIFICATION_ID, dismissIntent, PendingIntent.FLAG_UPDATE_CURRENT); notification.addAction(com.androidinspain.deskclock.R.drawable.ic_alarm_off_24dp, resources.getString(com.androidinspain.deskclock.R.string.alarm_alert_dismiss_text), dismissPendingIntent); // Setup Content Action Intent contentIntent = AlarmInstance.createIntent(service, AlarmActivity.class, instance.mId); notification.setContentIntent(PendingIntent.getActivity(service, ALARM_FIRING_NOTIFICATION_ID, contentIntent, PendingIntent.FLAG_UPDATE_CURRENT)); // Setup fullscreen intent Intent fullScreenIntent = AlarmInstance.createIntent(service, AlarmActivity.class, instance.mId); // set action, so we can be different then content pending intent fullScreenIntent.setAction("fullscreen_activity"); fullScreenIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_USER_ACTION); notification.setFullScreenIntent(PendingIntent.getActivity(service, ALARM_FIRING_NOTIFICATION_ID, fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT), true); notification.setPriority(NotificationCompat.PRIORITY_MAX); clearNotification(service, instance); service.startForeground(ALARM_FIRING_NOTIFICATION_ID, notification.build()); }
From source file:com.lannbox.rfduinotest.RFduinoService.java
private NotificationCompat.Builder buildServiceNotification() { Intent notificationIntent = new Intent(RFduinoService.this, MainActivity.class); notificationIntent.setAction("RFduinoTest_CallToMain"); notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); PendingIntent pendingIntent = PendingIntent.getActivity(RFduinoService.this, 0, notificationIntent, 0); Intent discoIntent = new Intent(RFduinoService.this, RFduinoService.class); discoIntent.setAction("ACTION_DISCONNECT"); PendingIntent pDiscoIntent = PendingIntent.getService(RFduinoService.this, 0, discoIntent, 0); Intent connIntent = new Intent(RFduinoService.this, RFduinoService.class); connIntent.setAction("ACTION_CONNECT"); PendingIntent pConnIntent = PendingIntent.getService(RFduinoService.this, 0, connIntent, 0); Intent stopIntent = new Intent(RFduinoService.this, RFduinoService.class); stopIntent.setAction("RFduinoService_Stop"); PendingIntent pStopIntent = PendingIntent.getService(RFduinoService.this, 0, stopIntent, 0); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(RFduinoService.this) .setContentTitle("Bluetooth Connection running").setTicker("BTLE Ticker") .setContentText("RFDuino connected").setSmallIcon(R.drawable.ic_launcher) // .setLargeIcon( // Bitmap.createScaledBitmap(icon, 128, 128, false)) .setContentIntent(pendingIntent).setOngoing(true) // maybe disable to allow closing with x-button? .addAction(android.R.drawable.ic_media_pause, "Disconnect", pDiscoIntent) .addAction(android.R.drawable.ic_media_play, "Connect", pConnIntent) .addAction(android.R.drawable.ic_delete, "Stop", pStopIntent); return mBuilder; }
From source file:br.com.bioscada.apps.biotracks.widgets.TrackWidgetProvider.java
/** * Updates the record button.//from ww w. j a va 2 s . co m * * @param context the context * @param remoteViews the remote views * @param isRecording true if recording * @param recordingTrackPaused true if recording track is paused */ private static void updateRecordButton(Context context, RemoteViews remoteViews, boolean isRecording, boolean recordingTrackPaused) { remoteViews.setImageViewResource(R.id.track_widget_record_button, isRecording && !recordingTrackPaused ? R.drawable.button_pause : R.drawable.button_record); int recordActionId; if (isRecording) { recordActionId = recordingTrackPaused ? R.string.track_action_resume : R.string.track_action_pause; } else { recordActionId = R.string.track_action_start; } Intent intent = new Intent(context, ControlRecordingService.class) .setAction(context.getString(recordActionId)); PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); remoteViews.setOnClickPendingIntent(R.id.track_widget_record_button, pendingIntent); }
From source file:com.jordanfitzgibbon.rfduinohrm.RFduinoService.java
private NotificationCompat.Builder buildServiceNotification() { Intent notificationIntent = new Intent(RFduinoService.this, com.jordanfitzgibbon.rfduinohrm.MainActivity.class); notificationIntent.setAction("RFduinoTest_CallToMain"); notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); PendingIntent pendingIntent = PendingIntent.getActivity(RFduinoService.this, 0, notificationIntent, 0); Intent discoIntent = new Intent(RFduinoService.this, RFduinoService.class); discoIntent.setAction("ACTION_DISCONNECT"); PendingIntent pDiscoIntent = PendingIntent.getService(RFduinoService.this, 0, discoIntent, 0); Intent connIntent = new Intent(RFduinoService.this, RFduinoService.class); connIntent.setAction("ACTION_CONNECT"); PendingIntent pConnIntent = PendingIntent.getService(RFduinoService.this, 0, connIntent, 0); Intent stopIntent = new Intent(RFduinoService.this, RFduinoService.class); stopIntent.setAction("RFduinoService_Stop"); PendingIntent pStopIntent = PendingIntent.getService(RFduinoService.this, 0, stopIntent, 0); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(RFduinoService.this) .setContentTitle("Bluetooth Connection running").setTicker("BTLE Ticker") .setContentText("RFDuino connected") //.setSmallIcon(R.drawable.ic_launcher) // .setLargeIcon( // Bitmap.createScaledBitmap(icon, 128, 128, false)) .setContentIntent(pendingIntent).setOngoing(true) // maybe disable to allow closing with x-button? .addAction(android.R.drawable.ic_media_pause, "Disconnect", pDiscoIntent) .addAction(android.R.drawable.ic_media_play, "Connect", pConnIntent) .addAction(android.R.drawable.ic_delete, "Stop", pStopIntent); return mBuilder; }
From source file:com.example.android.wearable.wear.wearnotifications.MainActivity.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();/*from www .ja v 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); // When creating your Intent, you need to take into account the back state, i.e., what // happens after your Activity launches and the user presses the back button. // There are two options: // 1. Regular activity - You're starting an Activity that's part of the application's // normal workflow. // 2. Special activity - The user only sees this Activity if it's started from a // notification. In a sense, the Activity extends the notification by providing // information that would be hard to display in the notification itself. // Even though this sample's MainActivity doesn't link to the Activity this Notification // launches directly, i.e., it isn't part of the normal workflow, a social app generally // always links to individual posts as part of the app flow, so we will follow option 1. // For an example of option 2, check out the BIG_TEXT_STYLE example. // For more information, check out our dev article: // https://developer.android.com/training/notify-user/navigation.html TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); // Adds the back stack stackBuilder.addParentStack(BigPictureSocialMainActivity.class); // Adds the Intent to the top of the stack stackBuilder.addNextIntent(mainIntent); // Gets a PendingIntent containing the entire back stack PendingIntent mainPendingIntent = PendingIntent.getActivity(this, 0, mainIntent, PendingIntent.FLAG_UPDATE_CURRENT); // 3. Set up RemoteInput, so users can input (keyboard and voice) from notification // Note: For API <24 (M and below) we need to use an Activity, so the lock-screen presents // the auth challenge. For API 24+ (N and above), we use a Service (could be a // BroadcastReceiver), so the user can input from Notification or lock-screen (they have // choice to allow) without leaving the notification. // 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(); // Pending intent = // API <24 (M and below): activity so the lock-screen presents the auth challenge // API 24+ (N and above): this should be a Service or BroadcastReceiver PendingIntent replyActionPendingIntent; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Intent intent = new Intent(this, BigPictureSocialIntentService.class); intent.setAction(BigPictureSocialIntentService.ACTION_COMMENT); replyActionPendingIntent = PendingIntent.getService(this, 0, intent, 0); } else { replyActionPendingIntent = mainPendingIntent; } NotificationCompat.Action replyAction = new NotificationCompat.Action.Builder( R.drawable.ic_reply_white_18dp, replyLabel, replyActionPendingIntent).addRemoteInput(remoteInput) .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); // 4. Build and issue the notification notificationCompatBuilder // BIG_PICTURE_STYLE sets title and content for API 16 (4.1 and after) .setStyle(bigPictureStyle) // Title for API <16 (4.0 and below) devices .setContentTitle(bigPictureStyleSocialAppData.getContentTitle()) // Content for API <24 (7.0 and below) devices .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)) // SIDE NOTE: Auto-bundling is enabled for 4 or more notifications on API 24+ (N+) // devices and all Android Wear devices. If you have more than one notification and // you prefer a different summary notification, set a group key and create a // summary notification via // .setGroupSummary(true) // .setGroup(GROUP_KEY_YOUR_NAME_HERE) .setSubText(Integer.toString(1)).addAction(replyAction).setCategory(Notification.CATEGORY_SOCIAL) .setPriority(Notification.PRIORITY_HIGH) // Hides content on the lock-screen .setVisibility(Notification.VISIBILITY_PRIVATE); // 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); }
From source file:com.brucegiese.perfectposture.OrientationService.java
/** * Send or cancel a notification, subject to user settings * * @param n The type of notification to send or cancel * @param send true if send, false if cancel *///w ww. java2 s . c o m private void sendNotification(NotificationType n, boolean send) { String title; String text; int id; int icon; if (mAlertNotification || !send) { // always attempt to cancel pending notifications switch (n) { // Right now, we're not sending any SERVICE_RUNNING notifications. // If we do, then we need two different icons for service running vs bad posture. case SERVICE_RUNNING: title = SERVICE_NOTIFICATION_TITLE; text = getResources().getString(R.string.service_notification_text); id = SERVICE_NOTIFICATION_ID; icon = R.drawable.ic_posture_notif; break; case BAD_POSTURE: title = POSTURE_NOTIFICATION_TITLE; text = getResources().getString(R.string.posture_notification_text); id = POSTURE_NOTIFICATION_ID; icon = R.drawable.ic_posture_notif; break; case CHIN_TUCK_REMINDER: title = CHIN_TUCK_NOTIFICATION_TITLE; text = getResources().getString(R.string.chin_tuck_notification_text); id = CHIN_TUCK_NOTIFICATION_ID; icon = R.drawable.ic_chin_tuck_notif; break; default: Log.e(TAG, "Unknown type given to sendNotification"); return; } if (send) { Intent resultIntent = new Intent(this, PerfectPostureActivity.class); PendingIntent pIntent = PendingIntent.getActivity(this, 0, resultIntent, 0); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setSmallIcon(icon) .setContentTitle(title).setContentText(text); // Add an action allowing the user to open the application mBuilder.addAction(R.drawable.ic_posture, getString(R.string.open_application), pIntent); // Add an action to turn off the service (needs to be a broadcast intent) Intent turnOffIntent = new Intent(this, OrientationService.class); turnOffIntent.setAction(TURN_OFF_SERVICE_ACTION); PendingIntent pendingIntentTurnOff = PendingIntent.getService(this, 0, turnOffIntent, 0); // ic_action_halt icon is from Opoloo, covered by Attribution-ShareAlike 4.0 license // http://creativecommons.org/licenses/by-sa/4.0/ // icons are at http://www.opoloo.com/ mBuilder.addAction(R.drawable.ic_action_halt, getString(R.string.turn_off_service), pendingIntentTurnOff); mNotificationManager.notify(id, mBuilder.build()); } else { // remove the notification mNotificationManager.cancel(id); } } }