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:de.dcja.prettygreatmusicplayer.MusicPlaybackService.java
private void updateNotification() { boolean audiobookMode = sharedPref.getBoolean("pref_audiobook_mode", false); // https://stackoverflow.com/questions/5528288/how-do-i-update-the-notification-text-for-a-foreground-service-in-android Intent resultIntent = new Intent(this, NowPlaying.class); // Use the FLAG_ACTIVITY_CLEAR_TOP to prevent launching a second // NowPlaying if one already exists. resultIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); resultIntent.putExtra("From_Notification", true); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT); Builder builder = new NotificationCompat.Builder(this.getApplicationContext()); int icon = R.drawable.ic_pgmp_launcher; String contentText = getResources().getString(R.string.ticker_text); if (songFile != null) { PlaybackInfoHolder pih = PlaybackInfoHolder.getInstance(); String artist;// w ww . j a v a 2 s .com String songName; synchronized (pih) { Playlist.Song song = pih.getActivePlaylist().getPlaying(); artist = song.getArtist(); songName = song.getSong(); } contentText = artist + ": " + songName; if (mp != null) { if (mp.isPlaying()) { icon = R.drawable.ic_pgmp_launcher; } } } Intent previousIntent = new Intent("Previous", null, this, MusicPlaybackService.class); previousIntent.putExtra("Message", MSG_PREVIOUS); PendingIntent previousPendingIntent = PendingIntent.getService(this, 0, previousIntent, PendingIntent.FLAG_UPDATE_CURRENT); Intent jumpBackIntent = new Intent("JumpBack", null, this, MusicPlaybackService.class); jumpBackIntent.putExtra("Message", MSG_JUMPBACK); PendingIntent jumpBackPendingIntent = PendingIntent.getService(this, 0, jumpBackIntent, PendingIntent.FLAG_UPDATE_CURRENT); Intent nextIntent = new Intent("Next", null, this, MusicPlaybackService.class); nextIntent.putExtra("Message", MSG_NEXT); PendingIntent nextPendingIntent = PendingIntent.getService(this, 0, nextIntent, PendingIntent.FLAG_UPDATE_CURRENT); PendingIntent playPausePendingIntent; Intent playPauseIntent = new Intent("PlayPause", null, this, MusicPlaybackService.class); playPauseIntent.putExtra("Message", MSG_PLAYPAUSE); playPausePendingIntent = PendingIntent.getService(this, 0, playPauseIntent, PendingIntent.FLAG_UPDATE_CURRENT); int playPauseIcon; if (mp != null && mp.isPlaying()) { playPauseIcon = R.drawable.ic_action_pause; } else { playPauseIcon = R.drawable.ic_action_play; } Notification notification; if (audiobookMode) { notification = builder.setContentText(contentText).setSmallIcon(icon) .setWhen(System.currentTimeMillis()).setContentIntent(pendingIntent) .setContentTitle(getResources().getString(R.string.notification_title)) .addAction(R.drawable.ic_action_rewind20, "", jumpBackPendingIntent) .addAction(playPauseIcon, "", playPausePendingIntent) .addAction(R.drawable.ic_action_next, "", nextPendingIntent).build(); } else { notification = builder.setContentText(contentText).setSmallIcon(icon) .setWhen(System.currentTimeMillis()).setContentIntent(pendingIntent) .setContentTitle(getResources().getString(R.string.notification_title)) .addAction(R.drawable.ic_action_previous, "", previousPendingIntent) .addAction(playPauseIcon, "", playPausePendingIntent) .addAction(R.drawable.ic_action_next, "", nextPendingIntent).build(); } NotificationManager mNotificationManager = (NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE); mNotificationManager.notify(uniqueid, notification); }
From source file:com.tct.mail.utils.NotificationActionUtils.java
public static Notification createUndoNotification(final Context context, final NotificationAction notificationAction, final int notificationId) { LogUtils.i(LOG_TAG, "createUndoNotification for %s", notificationAction.getNotificationActionType()); final NotificationCompat.Builder builder = new NotificationCompat.Builder(context); builder.setSmallIcon(R.drawable.ic_notification_mail_24dp); builder.setWhen(notificationAction.getWhen()); final RemoteViews undoView = new RemoteViews(context.getPackageName(), R.layout.undo_notification); undoView.setTextViewText(R.id.description_text, context.getString(notificationAction.getActionTextResId())); final String packageName = context.getPackageName(); final Intent clickIntent = new Intent(NotificationActionIntentService.ACTION_UNDO); clickIntent.setPackage(packageName); clickIntent.setData(notificationAction.mConversation.uri); putNotificationActionExtra(clickIntent, notificationAction); final PendingIntent clickPendingIntent = PendingIntent.getService(context, notificationId, clickIntent, PendingIntent.FLAG_CANCEL_CURRENT); undoView.setOnClickPendingIntent(R.id.status_bar_latest_event_content, clickPendingIntent); builder.setContent(undoView);/*from www . j a v a2 s. co m*/ // When the notification is cleared, we perform the destructive action final Intent deleteIntent = new Intent(NotificationActionIntentService.ACTION_DESTRUCT); deleteIntent.setPackage(packageName); deleteIntent.setData(notificationAction.mConversation.uri); putNotificationActionExtra(deleteIntent, notificationAction); final PendingIntent deletePendingIntent = PendingIntent.getService(context, notificationId, deleteIntent, PendingIntent.FLAG_CANCEL_CURRENT); builder.setDeleteIntent(deletePendingIntent); final Notification notification = builder.build(); return notification; }
From source file:com.android.deskclock.data.TimerModel.java
/** * Updates the notification controlling unexpired timers. This notification is only displayed * when the application is not open./*from www .ja va 2 s. c o m*/ */ void updateNotification() { // Notifications should be hidden if the app is open. if (mNotificationModel.isApplicationInForeground()) { mNotificationManager.cancel(mNotificationModel.getUnexpiredTimerNotificationId()); return; } // Filter the timers to just include unexpired ones. final List<Timer> unexpired = new ArrayList<>(); for (Timer timer : getMutableTimers()) { if (timer.isRunning() || timer.isPaused()) { unexpired.add(timer); } } // If no unexpired timers exist, cancel the notification. if (unexpired.isEmpty()) { mNotificationManager.cancel(mNotificationModel.getUnexpiredTimerNotificationId()); return; } // Sort the unexpired timers to locate the next one scheduled to expire. Collections.sort(unexpired, Timer.EXPIRY_COMPARATOR); final Timer timer = unexpired.get(0); final long remainingTime = timer.getRemainingTime(); // Generate some descriptive text, a title, and some actions based on timer states. final String contentText; final String contentTitle; @DrawableRes int firstActionIconId, secondActionIconId = 0; @StringRes int firstActionTitleId, secondActionTitleId = 0; Intent firstActionIntent, secondActionIntent = null; if (unexpired.size() == 1) { contentText = formatElapsedTimeUntilExpiry(remainingTime); if (timer.isRunning()) { // Single timer is running. if (TextUtils.isEmpty(timer.getLabel())) { contentTitle = mContext.getString(R.string.timer_notification_label); } else { contentTitle = timer.getLabel(); } firstActionIconId = R.drawable.ic_pause_24dp; firstActionTitleId = R.string.timer_pause; firstActionIntent = new Intent(mContext, TimerService.class) .setAction(HandleDeskClockApiCalls.ACTION_PAUSE_TIMER) .putExtra(HandleDeskClockApiCalls.EXTRA_TIMER_ID, timer.getId()); secondActionIconId = R.drawable.ic_add_24dp; secondActionTitleId = R.string.timer_plus_1_min; secondActionIntent = new Intent(mContext, TimerService.class) .setAction(HandleDeskClockApiCalls.ACTION_ADD_MINUTE_TIMER) .putExtra(HandleDeskClockApiCalls.EXTRA_TIMER_ID, timer.getId()); } else { // Single timer is paused. contentTitle = mContext.getString(R.string.timer_paused); firstActionIconId = R.drawable.ic_start_24dp; firstActionTitleId = R.string.sw_resume_button; firstActionIntent = new Intent(mContext, TimerService.class) .setAction(HandleDeskClockApiCalls.ACTION_START_TIMER) .putExtra(HandleDeskClockApiCalls.EXTRA_TIMER_ID, timer.getId()); secondActionIconId = R.drawable.ic_reset_24dp; secondActionTitleId = R.string.sw_reset_button; secondActionIntent = new Intent(mContext, TimerService.class) .setAction(HandleDeskClockApiCalls.ACTION_RESET_TIMER) .putExtra(HandleDeskClockApiCalls.EXTRA_TIMER_ID, timer.getId()); } } else { if (timer.isRunning()) { // At least one timer is running. final String timeRemaining = formatElapsedTimeUntilExpiry(remainingTime); contentText = mContext.getString(R.string.next_timer_notif, timeRemaining); contentTitle = mContext.getString(R.string.timers_in_use, unexpired.size()); } else { // All timers are paused. contentText = mContext.getString(R.string.all_timers_stopped_notif); contentTitle = mContext.getString(R.string.timers_stopped, unexpired.size()); } firstActionIconId = R.drawable.ic_reset_24dp; firstActionTitleId = R.string.timer_reset_all; firstActionIntent = TimerService.createResetUnexpiredTimersIntent(mContext); } // Intent to load the app and show the timer when the notification is tapped. final Intent showApp = new Intent(mContext, HandleDeskClockApiCalls.class) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).setAction(HandleDeskClockApiCalls.ACTION_SHOW_TIMERS) .putExtra(HandleDeskClockApiCalls.EXTRA_TIMER_ID, timer.getId()) .putExtra(HandleDeskClockApiCalls.EXTRA_EVENT_LABEL, R.string.label_notification); final PendingIntent pendingShowApp = PendingIntent.getActivity(mContext, 0, showApp, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT); final NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext).setOngoing(true) .setLocalOnly(true).setShowWhen(false).setAutoCancel(false).setContentText(contentText) .setContentTitle(contentTitle).setContentIntent(pendingShowApp) .setSmallIcon(R.drawable.stat_notify_timer).setPriority(NotificationCompat.PRIORITY_HIGH) .setCategory(NotificationCompat.CATEGORY_ALARM).setVisibility(NotificationCompat.VISIBILITY_PUBLIC); final PendingIntent firstAction = PendingIntent.getService(mContext, 0, firstActionIntent, PendingIntent.FLAG_UPDATE_CURRENT); final String firstActionTitle = mContext.getString(firstActionTitleId); builder.addAction(firstActionIconId, firstActionTitle, firstAction); if (secondActionIntent != null) { final PendingIntent secondAction = PendingIntent.getService(mContext, 0, secondActionIntent, PendingIntent.FLAG_UPDATE_CURRENT); final String secondActionTitle = mContext.getString(secondActionTitleId); builder.addAction(secondActionIconId, secondActionTitle, secondAction); } // Update the notification. final Notification notification = builder.build(); final int notificationId = mNotificationModel.getUnexpiredTimerNotificationId(); mNotificationManager.notify(notificationId, notification); final Intent updateNotification = TimerService.createUpdateNotificationIntent(mContext); if (timer.isRunning() && remainingTime > MINUTE_IN_MILLIS) { // Schedule a callback to update the time-sensitive information of the running timer. final PendingIntent pi = PendingIntent.getService(mContext, 0, updateNotification, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT); final long nextMinuteChange = remainingTime % MINUTE_IN_MILLIS; final long triggerTime = SystemClock.elapsedRealtime() + nextMinuteChange; schedulePendingIntent(triggerTime, pi); } else { // Cancel the update notification callback. final PendingIntent pi = PendingIntent.getService(mContext, 0, updateNotification, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_NO_CREATE); if (pi != null) { mAlarmManager.cancel(pi); pi.cancel(); } } }
From source file:de.tubs.ibr.dtn.service.DaemonService.java
@SuppressWarnings("deprecation") private Notification buildNotification(String stateText) { String content = Preferences.getEndpoint(DaemonService.this); NotificationCompat.Builder builder = new NotificationCompat.Builder(this); builder.setContentTitle(getResources().getString(R.string.service_name)); builder.setContentText(content);/*ww w . j a v a2 s . com*/ builder.setSmallIcon(R.drawable.ic_notification); builder.setOngoing(true); builder.setOnlyAlertOnce(true); builder.setWhen(0); if (stateText != null) builder.setTicker(stateText); List<Node> neighbors = mDaemonProcess.getNeighbors(); builder.setNumber(neighbors.size()); // create intent for the neighbor list Intent showNeighborsIntent = new Intent(this, NeighborActivity.class); showNeighborsIntent.setAction("android.intent.action.MAIN"); showNeighborsIntent.addCategory("android.intent.category.LAUNCHER"); if (mDiscoveryState) { // create intent to stop discovery Intent stopDiscoveryIntent = new Intent(this, DaemonService.class); stopDiscoveryIntent.setAction(de.tubs.ibr.dtn.service.DaemonService.ACTION_STOP_DISCOVERY); PendingIntent piDisco = PendingIntent.getService(this, 0, stopDiscoveryIntent, 0); builder.addAction(R.drawable.ic_action_discovery_stop, getString(R.string.stop_discovery), piDisco); } else { // create intent to start discovery Intent startDiscoveryIntent = new Intent(this, DaemonService.class); startDiscoveryIntent.setAction(de.tubs.ibr.dtn.service.DaemonService.ACTION_START_DISCOVERY); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); if ("smart".equals(prefs.getString(Preferences.KEY_DISCOVERY_MODE, "smart"))) { startDiscoveryIntent.putExtra(DaemonService.EXTRA_DISCOVERY_DURATION, 120L); } PendingIntent piDisco = PendingIntent.getService(this, 0, startDiscoveryIntent, 0); builder.addAction(R.drawable.ic_action_discovery, getString(R.string.start_discovery), piDisco); } TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); stackBuilder.addParentStack(NeighborActivity.class); stackBuilder.addNextIntent(showNeighborsIntent); PendingIntent contentIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); // PendingIntent.getActivity(this, 0, showNeighborsIntent, 0); builder.setContentIntent(contentIntent); return builder.getNotification(); }
From source file:com.irccloud.android.Notifications.java
@SuppressLint("NewApi") private android.app.Notification buildNotification(String ticker, int bid, long[] eids, String title, String text, Spanned big_text, int count, Intent replyIntent, Spanned wear_text, String network, String auto_messages[]) { SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext()); NotificationCompat.Builder builder = new NotificationCompat.Builder( IRCCloudApplication.getInstance().getApplicationContext()) .setContentTitle(title + ((network != null) ? (" (" + network + ")") : "")) .setContentText(Html.fromHtml(text)).setAutoCancel(true).setTicker(ticker) .setWhen(eids[0] / 1000).setSmallIcon(R.drawable.ic_stat_notify) .setColor(IRCCloudApplication.getInstance().getApplicationContext().getResources() .getColor(R.color.dark_blue)) .setVisibility(NotificationCompat.VISIBILITY_PRIVATE) .setCategory(NotificationCompat.CATEGORY_MESSAGE) .setPriority(NotificationCompat.PRIORITY_HIGH).setOnlyAlertOnce(false); if (ticker != null && (System.currentTimeMillis() - prefs.getLong("lastNotificationTime", 0)) > 10000) { if (prefs.getBoolean("notify_vibrate", true)) builder.setDefaults(android.app.Notification.DEFAULT_VIBRATE); String ringtone = prefs.getString("notify_ringtone", "content://settings/system/notification_sound"); if (ringtone != null && ringtone.length() > 0) builder.setSound(Uri.parse(ringtone)); }//from w ww. ja v a2 s . c o m int led_color = Integer.parseInt(prefs.getString("notify_led_color", "1")); if (led_color == 1) { if (prefs.getBoolean("notify_vibrate", true)) builder.setDefaults( android.app.Notification.DEFAULT_LIGHTS | android.app.Notification.DEFAULT_VIBRATE); else builder.setDefaults(android.app.Notification.DEFAULT_LIGHTS); } else if (led_color == 2) { builder.setLights(0xFF0000FF, 500, 500); } SharedPreferences.Editor editor = prefs.edit(); editor.putLong("lastNotificationTime", System.currentTimeMillis()); editor.commit(); Intent i = new Intent(); i.setComponent(new ComponentName(IRCCloudApplication.getInstance().getApplicationContext().getPackageName(), "com.irccloud.android.MainActivity")); i.putExtra("bid", bid); i.setData(Uri.parse("bid://" + bid)); Intent dismiss = new Intent(IRCCloudApplication.getInstance().getApplicationContext().getResources() .getString(R.string.DISMISS_NOTIFICATION)); dismiss.setData(Uri.parse("irccloud-dismiss://" + bid)); dismiss.putExtra("bid", bid); dismiss.putExtra("eids", eids); PendingIntent dismissPendingIntent = PendingIntent.getBroadcast( IRCCloudApplication.getInstance().getApplicationContext(), 0, dismiss, PendingIntent.FLAG_UPDATE_CURRENT); builder.setContentIntent( PendingIntent.getActivity(IRCCloudApplication.getInstance().getApplicationContext(), 0, i, PendingIntent.FLAG_UPDATE_CURRENT)); builder.setDeleteIntent(dismissPendingIntent); if (replyIntent != null) { WearableExtender extender = new WearableExtender(); PendingIntent replyPendingIntent = PendingIntent.getService( IRCCloudApplication.getInstance().getApplicationContext(), bid + 1, replyIntent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_CANCEL_CURRENT); extender.addAction( new NotificationCompat.Action.Builder(R.drawable.ic_reply, "Reply", replyPendingIntent) .addRemoteInput( new RemoteInput.Builder("extra_reply").setLabel("Reply to " + title).build()) .build()); if (count > 1 && wear_text != null) extender.addPage( new NotificationCompat.Builder(IRCCloudApplication.getInstance().getApplicationContext()) .setContentText(wear_text).extend(new WearableExtender().setStartScrollBottom(true)) .build()); NotificationCompat.CarExtender.UnreadConversation.Builder unreadConvBuilder = new NotificationCompat.CarExtender.UnreadConversation.Builder( title + ((network != null) ? (" (" + network + ")") : "")) .setReadPendingIntent(dismissPendingIntent).setReplyAction(replyPendingIntent, new RemoteInput.Builder("extra_reply").setLabel("Reply to " + title).build()); if (auto_messages != null) { for (String m : auto_messages) { if (m != null && m.length() > 0) { unreadConvBuilder.addMessage(m); } } } else { unreadConvBuilder.addMessage(text); } unreadConvBuilder.setLatestTimestamp(eids[count - 1] / 1000); builder.extend(extender) .extend(new NotificationCompat.CarExtender().setUnreadConversation(unreadConvBuilder.build())); } if (replyIntent != null && prefs.getBoolean("notify_quickreply", true)) { i = new Intent(IRCCloudApplication.getInstance().getApplicationContext(), QuickReplyActivity.class); i.setData(Uri.parse("irccloud-bid://" + bid)); i.putExtras(replyIntent); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent quickReplyIntent = PendingIntent.getActivity( IRCCloudApplication.getInstance().getApplicationContext(), 0, i, PendingIntent.FLAG_UPDATE_CURRENT); builder.addAction(R.drawable.ic_action_reply, "Quick Reply", quickReplyIntent); } android.app.Notification notification = builder.build(); RemoteViews contentView = new RemoteViews( IRCCloudApplication.getInstance().getApplicationContext().getPackageName(), R.layout.notification); contentView.setTextViewText(R.id.title, title + " (" + network + ")"); contentView.setTextViewText(R.id.text, (count == 1) ? Html.fromHtml(text) : (count + " unread highlights.")); contentView.setLong(R.id.time, "setTime", eids[0] / 1000); notification.contentView = contentView; if (Build.VERSION.SDK_INT >= 16 && big_text != null) { RemoteViews bigContentView = new RemoteViews( IRCCloudApplication.getInstance().getApplicationContext().getPackageName(), R.layout.notification_expanded); bigContentView.setTextViewText(R.id.title, title + (!title.equals(network) ? (" (" + network + ")") : "")); bigContentView.setTextViewText(R.id.text, big_text); bigContentView.setLong(R.id.time, "setTime", eids[0] / 1000); if (count > 3) { bigContentView.setViewVisibility(R.id.more, View.VISIBLE); bigContentView.setTextViewText(R.id.more, "+" + (count - 3) + " more"); } else { bigContentView.setViewVisibility(R.id.more, View.GONE); } if (replyIntent != null && prefs.getBoolean("notify_quickreply", true)) { bigContentView.setViewVisibility(R.id.actions, View.VISIBLE); bigContentView.setViewVisibility(R.id.action_divider, View.VISIBLE); i = new Intent(IRCCloudApplication.getInstance().getApplicationContext(), QuickReplyActivity.class); i.setData(Uri.parse("irccloud-bid://" + bid)); i.putExtras(replyIntent); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent quickReplyIntent = PendingIntent.getActivity( IRCCloudApplication.getInstance().getApplicationContext(), 0, i, PendingIntent.FLAG_UPDATE_CURRENT); bigContentView.setOnClickPendingIntent(R.id.action_reply, quickReplyIntent); } notification.bigContentView = bigContentView; } return notification; }
From source file:com.umaps.gpslogger.GpsLoggingService.java
private void SetAlarmForNextPoint() { Log.d(TAG, "Set alarm for " + AppSettings.getMinimumSeconds() + " seconds"); Intent i = new Intent(this, GpsLoggingService.class); i.putExtra(IntentConstants.GET_NEXT_POINT, true); PendingIntent pi = PendingIntent.getService(this, 0, i, 0); nextPointAlarmManager.cancel(pi);//from www . jav a 2 s. co m nextPointAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + AppSettings.getMinimumSeconds() * 1000, pi); }
From source file:com.google.android.apps.muzei.api.MuzeiArtSource.java
private PendingIntent getHandleNextCommandPendingIntent(Context context) { return PendingIntent.getService(context, 0, new Intent(ACTION_HANDLE_COMMAND) .setComponent(new ComponentName(context, getClass())) .setData(Uri.fromParts(URI_SCHEME_COMMAND, Integer.toString(BUILTIN_COMMAND_ID_NEXT_ARTWORK), null)) .putExtra(EXTRA_COMMAND_ID, BUILTIN_COMMAND_ID_NEXT_ARTWORK).putExtra(EXTRA_SCHEDULED, true), PendingIntent.FLAG_UPDATE_CURRENT); }
From source file:com.example.android.wearable.wear.wearnotifications.StandaloneMainActivity.java
private void generateMessagingStyleNotification() { Log.d(TAG, "generateMessagingStyleNotification()"); // Main steps for building a MESSAGING_STYLE notification: // 0. Get your data // 1. Build the MESSAGING_STYLE // 2. Add support for Wear 1.+ // 3. Set up main Intent for notification // 4. Set up RemoteInput (users can input directly from notification) // 5. Build and issue the notification // 0. Get your data (everything unique per Notification) MockDatabase.MessagingStyleCommsAppData messagingStyleCommsAppData = MockDatabase.getMessagingStyleData(); // 1. Build the Notification.Style (MESSAGING_STYLE) String contentTitle = messagingStyleCommsAppData.getContentTitle(); MessagingStyle messagingStyle = new NotificationCompat.MessagingStyle( messagingStyleCommsAppData.getReplayName()) // You could set a different title to appear when the messaging style // is supported on device (24+) if you wish. In our case, we use the same // title. .setConversationTitle(contentTitle); // Adds all Messages // Note: Messages include the text, timestamp, and sender for (MessagingStyle.Message message : messagingStyleCommsAppData.getMessages()) { messagingStyle.addMessage(message); }/* w ww . ja va2 s .co m*/ // 2. Add support for Wear 1.+ // Since Wear 1.0 doesn't support the MESSAGING_STYLE, we use the BIG_TEXT_STYLE, so all the // text is visible. // This is basically a toString() of all the Messages above. String fullMessageForWearVersion1 = messagingStyleCommsAppData.getFullConversation(); Notification chatHistoryForWearV1 = new NotificationCompat.Builder(getApplicationContext()) .setStyle(new BigTextStyle().bigText(fullMessageForWearVersion1)).setContentTitle(contentTitle) .setSmallIcon(R.drawable.ic_launcher).setContentText(fullMessageForWearVersion1).build(); // Adds page with all text to support Wear 1.+. NotificationCompat.WearableExtender wearableExtenderForWearVersion1 = new NotificationCompat.WearableExtender() .setHintContentIntentLaunchesActivity(true).addPage(chatHistoryForWearV1); // 3. Set up main Intent for notification Intent notifyIntent = new Intent(this, MessagingMainActivity.class); PendingIntent mainPendingIntent = PendingIntent.getActivity(this, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT); // 4. Set up a RemoteInput Action, so users can input (keyboard, drawing, voice) directly // from the notification without entering the app. // Create the RemoteInput specifying this key. String replyLabel = getString(R.string.reply_label); RemoteInput remoteInput = new RemoteInput.Builder(MessagingIntentService.EXTRA_REPLY).setLabel(replyLabel) .build(); // Create PendingIntent for service that handles input. Intent replyIntent = new Intent(this, MessagingIntentService.class); replyIntent.setAction(MessagingIntentService.ACTION_REPLY); 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) // Allows system to generate replies by context of conversation .setAllowGeneratedReplies(true) // Add WearableExtender to enable inline actions .extend(inlineActionForWear2).build(); // 5. Build and issue the notification // Because we want this to be a new notification (not updating current notification), we // create a new Builder. Later, we update this same notification, so we need to save this // Builder globally (as outlined earlier). NotificationCompat.Builder notificationCompatBuilder = new NotificationCompat.Builder( getApplicationContext()); GlobalNotificationBuilder.setNotificationCompatBuilderInstance(notificationCompatBuilder); // Builds and issues notification notificationCompatBuilder // MESSAGING_STYLE sets title and content for API 24+ (Wear 2.0) devices .setStyle(messagingStyle) // Title for API <24 (Wear 1.+) devices .setContentTitle(contentTitle) // Content for API <24 (Wear 1.+) devices .setContentText(messagingStyleCommsAppData.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)) // Number of new notifications for API <24 (Wear 1.+) devices .setSubText(Integer.toString(messagingStyleCommsAppData.getNumberOfNewMessages())) .addAction(replyAction).setCategory(Notification.CATEGORY_MESSAGE) .setPriority(Notification.PRIORITY_HIGH) // Hides content on the lock-screen .setVisibility(Notification.VISIBILITY_PRIVATE) // Adds multiple pages for easy consumption on a wear device. .extend(wearableExtenderForWearVersion1); // 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 : messagingStyleCommsAppData.getParticipants()) { notificationCompatBuilder.addPerson(name); } Notification notification = notificationCompatBuilder.build(); mNotificationManagerCompat.notify(NOTIFICATION_ID, notification); // Close app to demonstrate notification in steam. finish(); }