androidx.core.app.Person Java Examples

The following examples show how to use androidx.core.app.Person. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SingleRecipientNotificationBuilder.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
private void applyMessageStyle() {
  NotificationCompat.MessagingStyle messagingStyle = new NotificationCompat.MessagingStyle(
      new Person.Builder()
                .setBot(false)
                .setName(Recipient.self().getDisplayName(context))
                .setKey(Recipient.self().getId().serialize())
                .setIcon(AvatarUtil.getIconForNotification(context, Recipient.self()))
                .build());

  if (threadRecipient.isGroup()) {
    if (privacy.isDisplayContact()) {
      messagingStyle.setConversationTitle(threadRecipient.getDisplayName(context));
    } else {
      messagingStyle.setConversationTitle(context.getString(R.string.SingleRecipientNotificationBuilder_signal));
    }

    messagingStyle.setGroupConversation(true);
  }

  Stream.of(messages).forEach(messagingStyle::addMessage);
  setStyle(messagingStyle);
}
 
Example #2
Source File: NotificationService.java    From Pix-Art-Messenger with GNU General Public License v3.0 6 votes vote down vote up
private Person getPerson(Message message) {
    final Contact contact = message.getContact();
    final Person.Builder builder = new Person.Builder();
    if (contact != null) {
        builder.setName(contact.getDisplayName());
        final Uri uri = contact.getSystemAccount();
        if (uri != null) {
            builder.setUri(uri.toString());
        }
    } else {
        builder.setName(UIHelper.getColoredUsername(mXmppConnectionService, message));
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
        builder.setIcon(IconCompat.createWithBitmap(mXmppConnectionService.getAvatarService().get(message, AvatarService.getSystemUiAvatarSize(mXmppConnectionService), false)));
    }
    return builder.build();
}
 
Example #3
Source File: SingleRecipientNotificationBuilder.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public void addMessageBody(@NonNull Recipient threadRecipient,
                           @NonNull Recipient individualRecipient,
                           @Nullable CharSequence messageBody,
                           long timestamp)
{
  SpannableStringBuilder stringBuilder = new SpannableStringBuilder();
  Person.Builder personBuilder = new Person.Builder()
                                           .setKey(individualRecipient.getId().serialize())
                                           .setBot(false);

  this.threadRecipient = threadRecipient;

  if (privacy.isDisplayContact()) {
    personBuilder.setName(individualRecipient.getDisplayName(context));

    Bitmap bitmap = getLargeBitmap(getContactDrawable(individualRecipient));
    if (bitmap != null) {
      personBuilder.setIcon(IconCompat.createWithBitmap(bitmap));
    }
  } else {
    personBuilder.setName("");
  }

  final CharSequence text;
  if (privacy.isDisplayMessage()) {
    text = messageBody == null ? "" : messageBody;
  } else {
    text = stringBuilder.append(context.getString(R.string.SingleRecipientNotificationBuilder_new_message));
  }

  messages.add(new NotificationCompat.MessagingStyle.Message(text, timestamp, personBuilder.build()));
}
 
Example #4
Source File: MainActivity.java    From journaldev with MIT License 5 votes vote down vote up
private void notificationWithIcon() {
    Person anupam = new Person.Builder()
            .setName("Anupam")
            .setIcon(IconCompat.createWithResource(this, R.drawable.sample_photo))
            .setImportant(true)
            .build();

    new NotificationCompat.MessagingStyle(anupam)
            .addMessage("Check out my latest article!", new Date().getTime(), anupam)
            .setBuilder(builder);


    notificationManager.notify(2, builder.build());
}
 
Example #5
Source File: MainActivity.java    From journaldev with MIT License 5 votes vote down vote up
private void simpleNotification() {
    Person jd = new Person.Builder()
            .setName("JournalDev")
            .setImportant(true)
            .build();

    new NotificationCompat.MessagingStyle(jd)
            .addMessage("Check me out", new Date().getTime(), jd)
            .setBuilder(builder);


    notificationManager.notify(1, builder.build());
}
 
Example #6
Source File: SharingShortcutsManager.java    From android-SharingShortcuts with Apache License 2.0 5 votes vote down vote up
/**
 * Publish the list of dynamics shortcuts that will be used in Direct Share.
 * <p>
 * For each shortcut, we specify the categories that it will be associated to,
 * the intent that will trigger when opened as a static launcher shortcut,
 * and the Shortcut ID between other things.
 * <p>
 * The Shortcut ID that we specify in the {@link ShortcutInfoCompat.Builder} constructor will
 * be received in the intent as {@link Intent#EXTRA_SHORTCUT_ID}.
 * <p>
 * In this code sample, this method is completely static. We are always setting the same sharing
 * shortcuts. In a real-world example, we would replace existing shortcuts depending on
 * how the user interacts with the app as often as we want to.
 */
public void pushDirectShareTargets(@NonNull Context context) {
    ArrayList<ShortcutInfoCompat> shortcuts = new ArrayList<>();

    // Category that our sharing shortcuts will be assigned to
    Set<String> contactCategories = new HashSet<>();
    contactCategories.add(CATEGORY_TEXT_SHARE_TARGET);

    // Adding maximum number of shortcuts to the list
    for (int id = 0; id < MAX_SHORTCUTS; ++id) {
        Contact contact = Contact.byId(id);

        // Item that will be sent if the shortcut is opened as a static launcher shortcut
        Intent staticLauncherShortcutIntent = new Intent(Intent.ACTION_DEFAULT);

        // Creates a new Sharing Shortcut and adds it to the list
        // The id passed in the constructor will become EXTRA_SHORTCUT_ID in the received Intent
        shortcuts.add(new ShortcutInfoCompat.Builder(context, Integer.toString(id))
                .setShortLabel(contact.getName())
                // Icon that will be displayed in the share target
                .setIcon(IconCompat.createWithResource(context, contact.getIcon()))
                .setIntent(staticLauncherShortcutIntent)
                // Make this sharing shortcut cached by the system
                // Even if it is unpublished, it can still appear on the sharesheet
                .setLongLived()
                .setCategories(contactCategories)
                // Person objects are used to give better suggestions
                .setPerson(new Person.Builder()
                        .setName(contact.getName())
                        .build())
                .build());
    }

    ShortcutManagerCompat.addDynamicShortcuts(context, shortcuts);
}
 
Example #7
Source File: SharingShortcutsManager.java    From storage-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Publish the list of dynamics shortcuts that will be used in Direct Share.
 * <p>
 * For each shortcut, we specify the categories that it will be associated to,
 * the intent that will trigger when opened as a static launcher shortcut,
 * and the Shortcut ID between other things.
 * <p>
 * The Shortcut ID that we specify in the {@link ShortcutInfoCompat.Builder} constructor will
 * be received in the intent as {@link Intent#EXTRA_SHORTCUT_ID}.
 * <p>
 * In this code sample, this method is completely static. We are always setting the same sharing
 * shortcuts. In a real-world example, we would replace existing shortcuts depending on
 * how the user interacts with the app as often as we want to.
 */
public void pushDirectShareTargets(@NonNull Context context) {
    ArrayList<ShortcutInfoCompat> shortcuts = new ArrayList<>();

    // Category that our sharing shortcuts will be assigned to
    Set<String> contactCategories = new HashSet<>();
    contactCategories.add(CATEGORY_TEXT_SHARE_TARGET);

    // Adding maximum number of shortcuts to the list
    for (int id = 0; id < MAX_SHORTCUTS; ++id) {
        Contact contact = Contact.byId(id);

        // Item that will be sent if the shortcut is opened as a static launcher shortcut
        Intent staticLauncherShortcutIntent = new Intent(Intent.ACTION_DEFAULT);

        // Creates a new Sharing Shortcut and adds it to the list
        // The id passed in the constructor will become EXTRA_SHORTCUT_ID in the received Intent
        shortcuts.add(new ShortcutInfoCompat.Builder(context, Integer.toString(id))
                .setShortLabel(contact.getName())
                // Icon that will be displayed in the share target
                .setIcon(IconCompat.createWithResource(context, contact.getIcon()))
                .setIntent(staticLauncherShortcutIntent)
                // Make this sharing shortcut cached by the system
                // Even if it is unpublished, it can still appear on the sharesheet
                .setLongLived()
                .setCategories(contactCategories)
                // Person objects are used to give better suggestions
                .setPerson(new Person.Builder()
                        .setName(contact.getName())
                        .build())
                .build());
    }

    ShortcutManagerCompat.addDynamicShortcuts(context, shortcuts);
}
 
Example #8
Source File: NotificationBuilderImplP.java    From FCM-for-Mojo with GNU General Public License v3.0 5 votes vote down vote up
@Override
public NotificationCompat.Style createStyle(Context context, Chat chat) {
    MessagingStyle style = new MessagingStyle(new Person.Builder()
            .setName(context.getString(R.string.you))
            .setIcon(IconCompat.createWithBitmap(UserIcon.requestIcon(context, User.getSelf().getUid(), Chat.ChatType.FRIEND)))
            .build());
    style.setConversationTitle(chat.getName());
    style.setGroupConversation(chat.isGroup());

    for (int i = chat.getMessages().size() - NOTIFICATION_MAX_MESSAGES, count = 0; i < chat.getMessages().size() && count <= 8; i++, count++) {
        if (i < 0) {
            continue;
        }

        Message message = chat.getMessages().get(i);
        User sender = message.getSenderUser();

        IconCompat icon = null;
        Bitmap bitmap = UserIcon.getIcon(context, sender.getUid(), Chat.ChatType.FRIEND);
        if (bitmap != null) {
            icon = IconCompat.createWithBitmap(bitmap);
        }

        Person person = null;
        if (message.getSenderUser() != User.getSelf()) {
            person = new Person.Builder()
                    .setKey(sender.getName())
                    .setName(sender.getName())
                    .setIcon(icon)
                    .build();
        }

        style.addMessage(message.getContent(context), message.getTimestamp(), person);
    }

    style.setSummaryText(context.getString(R.string.notification_messages, chat.getMessages().getSize()));

    return style;
}
 
Example #9
Source File: MockDatabase.java    From wear-os-samples with Apache License 2.0 4 votes vote down vote up
private MessagingStyleCommsAppData(Context context) {
    // Standard notification values:
    // Content for API <24 (M and below) devices.
    // Note: I am actually hardcoding these Strings based on info below. You would be
    // pulling these values from the same source in your database. I leave this up here, so
    // you can see the standard parts of a Notification first.
    mContentTitle = "3 Messages w/ Famous, Wendy";
    mContentText = "HEY, I see my house! :)";
    mPriority = NotificationCompat.PRIORITY_HIGH;

    // Create the users for the conversation.
    // Name preferred when replying to chat.
    mMe =
            new Person.Builder()
                    .setName("Me MacDonald")
                    .setKey("1234567890")
                    .setUri("tel:1234567890")
                    .setIcon(
                            IconCompat.createWithResource(context, R.drawable.me_macdonald))
                    .build();

    Person participant1 =
            new Person.Builder()
                    .setName("Famous Fryer")
                    .setKey("9876543210")
                    .setUri("tel:9876543210")
                    .setIcon(
                            IconCompat.createWithResource(context, R.drawable.famous_fryer))
                    .build();

    Person participant2 =
            new Person.Builder()
                    .setName("Wendy Wonda")
                    .setKey("2233221122")
                    .setUri("tel:2233221122")
                    .setIcon(IconCompat.createWithResource(context, R.drawable.wendy_wonda))
                    .build();

    // If the phone is in "Do not disturb mode, the user will still be notified if
    // the user(s) is starred as a favorite.
    // Note: You don't need to add yourself, aka 'me', as a participant.
    mParticipants = new ArrayList<>();
    mParticipants.add(participant1);
    mParticipants.add(participant2);

    mMessages = new ArrayList<>();

    // For each message, you need the timestamp. In this case, we are using arbitrary longs
    // representing time in milliseconds.
    mMessages.add(
            // When you are setting an image for a message, text does not display.
            new MessagingStyle.Message("", 1528490641998L, participant1)
                    .setData(
                            "image/png", resourceToUri(context, R.drawable.earth)));

    mMessages.add(
            new MessagingStyle.Message(
                    "Visiting the moon again? :P", 1528490643998L, mMe));

    mMessages.add(
            new MessagingStyle.Message(
                    "HEY, I see my house!", 1528490645998L, participant2));

    // String version of the mMessages above.
    mFullConversation =
            "Famous: [Picture of Moon]\n\n"
                    + "Me: Visiting the moon again? :P\n\n"
                    + "Wendy: HEY, I see my house! :)\n\n";

    // Responses based on the last messages of the conversation. You would use
    // Machine Learning to get these (https://developers.google.com/ml-kit/).
    mReplyChoicesBasedOnLastMessages =
            new CharSequence[] {"Me too!", "How's the weather?", "You have good eyesight."};

    // Notification channel values (for devices targeting 26 and above):
    mChannelId = "channel_messaging_1";
    // The user-visible name of the channel.
    mChannelName = "Sample Messaging";
    // The user-visible description of the channel.
    mChannelDescription = "Sample Messaging Notifications";
    mChannelImportance = NotificationManager.IMPORTANCE_MAX;
    mChannelEnableVibrate = true;
    mChannelLockscreenVisibility = NotificationCompat.VISIBILITY_PRIVATE;
}
 
Example #10
Source File: MessagingIntentService.java    From android-Notifications with Apache License 2.0 4 votes vote down vote up
/** Handles action for replying to messages from the notification. */
private void handleActionReply(CharSequence replyCharSequence) {
    Log.d(TAG, "handleActionReply(): " + replyCharSequence);

    if (replyCharSequence != null) {

        // TODO: Asynchronously save your message to Database and servers.

        /*
         * You have two options for updating your notification (this class uses approach #2):
         *
         *  1. Use a new NotificationCompatBuilder to create the Notification. This approach
         *  requires you to get *ALL* the information that existed in the previous
         *  Notification (and updates) and pass it to the builder. This is the approach used in
         *  the MainActivity.
         *
         *  2. Use the original NotificationCompatBuilder to create the Notification. This
         *  approach requires you to store a reference to the original builder. The benefit is
         *  you only need the new/updated information. In our case, the reply from the user
         *  which we already have here.
         *
         *  IMPORTANT NOTE: You shouldn't save/modify the resulting Notification object using
         *  its member variables and/or legacy APIs. If you want to retain anything from update
         *  to update, retain the Builder as option 2 outlines.
         */

        // Retrieves NotificationCompat.Builder used to create initial Notification
        NotificationCompat.Builder notificationCompatBuilder =
                GlobalNotificationBuilder.getNotificationCompatBuilderInstance();

        // Recreate builder from persistent state if app process is killed
        if (notificationCompatBuilder == null) {
            // Note: New builder set globally in the method
            notificationCompatBuilder = recreateBuilderWithMessagingStyle();
        }

        // Since we are adding to the MessagingStyle, we need to first retrieve the
        // current MessagingStyle from the Notification itself.
        Notification notification = notificationCompatBuilder.build();
        MessagingStyle messagingStyle =
                NotificationCompat.MessagingStyle.extractMessagingStyleFromNotification(
                        notification);

        // Add new message to the MessagingStyle. Set last parameter to null for responses
        // from user.
        messagingStyle.addMessage(replyCharSequence, System.currentTimeMillis(), (Person) null);

        // Updates the Notification
        notification = notificationCompatBuilder.setStyle(messagingStyle).build();

        // Pushes out the updated Notification
        NotificationManagerCompat notificationManagerCompat =
                NotificationManagerCompat.from(getApplicationContext());
        notificationManagerCompat.notify(MainActivity.NOTIFICATION_ID, notification);
    }
}
 
Example #11
Source File: MessagingIntentService.java    From android-Notifications with Apache License 2.0 4 votes vote down vote up
/** Handles action for replying to messages from the notification. */
private void handleActionReply(CharSequence replyCharSequence) {
    Log.d(TAG, "handleActionReply(): " + replyCharSequence);

    if (replyCharSequence != null) {

        // TODO: Asynchronously save your message to Database and servers.

        /*
         * You have two options for updating your notification (this class uses approach #2):
         *
         *  1. Use a new NotificationCompatBuilder to create the Notification. This approach
         *  requires you to get *ALL* the information that existed in the previous
         *  Notification (and updates) and pass it to the builder. This is the approach used in
         *  the MainActivity.
         *
         *  2. Use the original NotificationCompatBuilder to create the Notification. This
         *  approach requires you to store a reference to the original builder. The benefit is
         *  you only need the new/updated information. In our case, the reply from the user
         *  which we already have here.
         *
         *  IMPORTANT NOTE: You shouldn't save/modify the resulting Notification object using
         *  its member variables and/or legacy APIs. If you want to retain anything from update
         *  to update, retain the Builder as option 2 outlines.
         */

        // Retrieves NotificationCompat.Builder used to create initial Notification
        NotificationCompat.Builder notificationCompatBuilder =
                GlobalNotificationBuilder.getNotificationCompatBuilderInstance();

        // Recreate builder from persistent state if app process is killed
        if (notificationCompatBuilder == null) {
            // Note: New builder set globally in the method
            notificationCompatBuilder = recreateBuilderWithMessagingStyle();
        }

        // Since we are adding to the MessagingStyle, we need to first retrieve the
        // current MessagingStyle from the Notification itself.
        Notification notification = notificationCompatBuilder.build();
        MessagingStyle messagingStyle =
                NotificationCompat.MessagingStyle.extractMessagingStyleFromNotification(
                        notification);

        // Add new message to the MessagingStyle. Set last parameter to null for responses
        // from user.
        messagingStyle.addMessage(replyCharSequence, System.currentTimeMillis(), (Person) null);

        // Updates the Notification
        notification = notificationCompatBuilder.setStyle(messagingStyle).build();

        // Pushes out the updated Notification
        NotificationManagerCompat notificationManagerCompat =
                NotificationManagerCompat.from(getApplicationContext());
        notificationManagerCompat.notify(StandaloneMainActivity.NOTIFICATION_ID, notification);
    }
}
 
Example #12
Source File: MockDatabase.java    From android-Notifications with Apache License 2.0 4 votes vote down vote up
public ArrayList<Person> getParticipants() {
    return mParticipants;
}
 
Example #13
Source File: MockDatabase.java    From android-Notifications with Apache License 2.0 4 votes vote down vote up
public Person getMe() {
    return mMe;
}
 
Example #14
Source File: MockDatabase.java    From android-Notifications with Apache License 2.0 4 votes vote down vote up
private MessagingStyleCommsAppData(Context context) {
    // Standard notification values:
    // Content for API <24 (M and below) devices.
    // Note: I am actually hardcoding these Strings based on info below. You would be
    // pulling these values from the same source in your database. I leave this up here, so
    // you can see the standard parts of a Notification first.
    mContentTitle = "3 Messages w/ Famous, Wendy";
    mContentText = "HEY, I see my house! :)";
    mPriority = NotificationCompat.PRIORITY_HIGH;

    // Create the users for the conversation.
    // Name preferred when replying to chat.
    mMe =
            new Person.Builder()
                    .setName("Me MacDonald")
                    .setKey("1234567890")
                    .setUri("tel:1234567890")
                    .setIcon(
                            IconCompat.createWithResource(context, R.drawable.me_macdonald))
                    .build();

    Person participant1 =
            new Person.Builder()
                    .setName("Famous Fryer")
                    .setKey("9876543210")
                    .setUri("tel:9876543210")
                    .setIcon(
                            IconCompat.createWithResource(context, R.drawable.famous_fryer))
                    .build();

    Person participant2 =
            new Person.Builder()
                    .setName("Wendy Wonda")
                    .setKey("2233221122")
                    .setUri("tel:2233221122")
                    .setIcon(IconCompat.createWithResource(context, R.drawable.wendy_wonda))
                    .build();

    // If the phone is in "Do not disturb mode, the user will still be notified if
    // the user(s) is starred as a favorite.
    // Note: You don't need to add yourself, aka 'me', as a participant.
    mParticipants = new ArrayList<>();
    mParticipants.add(participant1);
    mParticipants.add(participant2);

    mMessages = new ArrayList<>();

    // For each message, you need the timestamp. In this case, we are using arbitrary longs
    // representing time in milliseconds.
    mMessages.add(
            // When you are setting an image for a message, text does not display.
            new MessagingStyle.Message("", 1528490641998l, participant1)
                    .setData("image/png", resourceToUri(context, R.drawable.earth)));

    mMessages.add(
            new MessagingStyle.Message(
                    "Visiting the moon again? :P", 1528490643998l, mMe));

    mMessages.add(
            new MessagingStyle.Message("HEY, I see my house!", 1528490645998l, participant2));

    // String version of the mMessages above.
    mFullConversation =
            "Famous: [Picture of Moon]\n\n"
                    + "Me: Visiting the moon again? :P\n\n"
                    + "Wendy: HEY, I see my house! :)\n\n";

    // Responses based on the last messages of the conversation. You would use
    // Machine Learning to get these (https://developers.google.com/ml-kit/).
    mReplyChoicesBasedOnLastMessages =
            new CharSequence[] {"Me too!", "How's the weather?", "You have good eyesight."};

    // Notification channel values (for devices targeting 26 and above):
    mChannelId = "channel_messaging_1";
    // The user-visible name of the channel.
    mChannelName = "Sample Messaging";
    // The user-visible description of the channel.
    mChannelDescription = "Sample Messaging Notifications";
    mChannelImportance = NotificationManager.IMPORTANCE_MAX;
    mChannelEnableVibrate = true;
    mChannelLockscreenVisibility = NotificationCompat.VISIBILITY_PRIVATE;
}
 
Example #15
Source File: MessagingStyle.java    From FCM-for-Mojo with GNU General Public License v3.0 4 votes vote down vote up
public MessagingStyle(@NonNull Person user) {
    super(user);
}
 
Example #16
Source File: Shortcuts.java    From FairEmail with GNU General Public License v3.0 4 votes vote down vote up
@NotNull
private static ShortcutInfoCompat.Builder getShortcut(Context context, String email, String name, Uri avatar) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    boolean identicons = prefs.getBoolean("identicons", false);
    boolean circular = prefs.getBoolean("circular", true);

    Intent intent = new Intent(context, ActivityMain.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    intent.setAction(Intent.ACTION_SEND);
    intent.addCategory(Intent.CATEGORY_DEFAULT);
    intent.setData(Uri.parse("mailto:" + email));

    Bitmap bitmap = null;
    if (avatar != null &&
            Helper.hasPermission(context, Manifest.permission.READ_CONTACTS)) {
        // Create icon from bitmap because launcher might not have contacts permission
        InputStream is = ContactsContract.Contacts.openContactPhotoInputStream(
                context.getContentResolver(), avatar);
        bitmap = BitmapFactory.decodeStream(is);
    }

    boolean identicon = false;
    if (bitmap == null) {
        int dp = Helper.dp2pixels(context, 96);
        if (identicons) {
            identicon = true;
            bitmap = ImageHelper.generateIdenticon(email, dp, 5, context);
        } else
            bitmap = ImageHelper.generateLetterIcon(email, name, dp, context);
    }

    bitmap = ImageHelper.makeCircular(bitmap,
            circular && !identicon ? null : Helper.dp2pixels(context, 3));

    IconCompat icon = IconCompat.createWithBitmap(bitmap);
    String id = (name == null ? email : "\"" + name + "\" <" + email + ">");
    Set<String> categories = new HashSet<>(Arrays.asList("eu.faircode.email.TEXT_SHARE_TARGET"));
    ShortcutInfoCompat.Builder builder = new ShortcutInfoCompat.Builder(context, id)
            .setIcon(icon)
            .setShortLabel(name == null ? email : name)
            .setLongLabel(name == null ? email : name)
            .setCategories(categories)
            .setIntent(intent);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        Person.Builder person = new Person.Builder()
                .setIcon(icon)
                .setName(name == null ? email : name)
                .setImportant(true);
        if (avatar != null)
            person.setUri(avatar.toString());
        builder.setPerson(person.build());
    }

    return builder;
}
 
Example #17
Source File: MessagingIntentService.java    From user-interface-samples with Apache License 2.0 4 votes vote down vote up
/** Handles action for replying to messages from the notification. */
private void handleActionReply(CharSequence replyCharSequence) {
    Log.d(TAG, "handleActionReply(): " + replyCharSequence);

    if (replyCharSequence != null) {

        // TODO: Asynchronously save your message to Database and servers.

        /*
         * You have two options for updating your notification (this class uses approach #2):
         *
         *  1. Use a new NotificationCompatBuilder to create the Notification. This approach
         *  requires you to get *ALL* the information that existed in the previous
         *  Notification (and updates) and pass it to the builder. This is the approach used in
         *  the MainActivity.
         *
         *  2. Use the original NotificationCompatBuilder to create the Notification. This
         *  approach requires you to store a reference to the original builder. The benefit is
         *  you only need the new/updated information. In our case, the reply from the user
         *  which we already have here.
         *
         *  IMPORTANT NOTE: You shouldn't save/modify the resulting Notification object using
         *  its member variables and/or legacy APIs. If you want to retain anything from update
         *  to update, retain the Builder as option 2 outlines.
         */

        // Retrieves NotificationCompat.Builder used to create initial Notification
        NotificationCompat.Builder notificationCompatBuilder =
                GlobalNotificationBuilder.getNotificationCompatBuilderInstance();

        // Recreate builder from persistent state if app process is killed
        if (notificationCompatBuilder == null) {
            // Note: New builder set globally in the method
            notificationCompatBuilder = recreateBuilderWithMessagingStyle();
        }

        // Since we are adding to the MessagingStyle, we need to first retrieve the
        // current MessagingStyle from the Notification itself.
        Notification notification = notificationCompatBuilder.build();
        MessagingStyle messagingStyle =
                NotificationCompat.MessagingStyle.extractMessagingStyleFromNotification(
                        notification);

        // Add new message to the MessagingStyle. Set last parameter to null for responses
        // from user.
        messagingStyle.addMessage(replyCharSequence, System.currentTimeMillis(), (Person) null);

        // Updates the Notification
        notification = notificationCompatBuilder.setStyle(messagingStyle).build();

        // Pushes out the updated Notification
        NotificationManagerCompat notificationManagerCompat =
                NotificationManagerCompat.from(getApplicationContext());
        notificationManagerCompat.notify(MainActivity.NOTIFICATION_ID, notification);
    }
}
 
Example #18
Source File: MessagingIntentService.java    From user-interface-samples with Apache License 2.0 4 votes vote down vote up
/** Handles action for replying to messages from the notification. */
private void handleActionReply(CharSequence replyCharSequence) {
    Log.d(TAG, "handleActionReply(): " + replyCharSequence);

    if (replyCharSequence != null) {

        // TODO: Asynchronously save your message to Database and servers.

        /*
         * You have two options for updating your notification (this class uses approach #2):
         *
         *  1. Use a new NotificationCompatBuilder to create the Notification. This approach
         *  requires you to get *ALL* the information that existed in the previous
         *  Notification (and updates) and pass it to the builder. This is the approach used in
         *  the MainActivity.
         *
         *  2. Use the original NotificationCompatBuilder to create the Notification. This
         *  approach requires you to store a reference to the original builder. The benefit is
         *  you only need the new/updated information. In our case, the reply from the user
         *  which we already have here.
         *
         *  IMPORTANT NOTE: You shouldn't save/modify the resulting Notification object using
         *  its member variables and/or legacy APIs. If you want to retain anything from update
         *  to update, retain the Builder as option 2 outlines.
         */

        // Retrieves NotificationCompat.Builder used to create initial Notification
        NotificationCompat.Builder notificationCompatBuilder =
                GlobalNotificationBuilder.getNotificationCompatBuilderInstance();

        // Recreate builder from persistent state if app process is killed
        if (notificationCompatBuilder == null) {
            // Note: New builder set globally in the method
            notificationCompatBuilder = recreateBuilderWithMessagingStyle();
        }

        // Since we are adding to the MessagingStyle, we need to first retrieve the
        // current MessagingStyle from the Notification itself.
        Notification notification = notificationCompatBuilder.build();
        MessagingStyle messagingStyle =
                NotificationCompat.MessagingStyle.extractMessagingStyleFromNotification(
                        notification);

        // Add new message to the MessagingStyle. Set last parameter to null for responses
        // from user.
        messagingStyle.addMessage(replyCharSequence, System.currentTimeMillis(), (Person) null);

        // Updates the Notification
        notification = notificationCompatBuilder.setStyle(messagingStyle).build();

        // Pushes out the updated Notification
        NotificationManagerCompat notificationManagerCompat =
                NotificationManagerCompat.from(getApplicationContext());
        notificationManagerCompat.notify(StandaloneMainActivity.NOTIFICATION_ID, notification);
    }
}
 
Example #19
Source File: MockDatabase.java    From user-interface-samples with Apache License 2.0 4 votes vote down vote up
public ArrayList<Person> getParticipants() {
    return mParticipants;
}
 
Example #20
Source File: MockDatabase.java    From user-interface-samples with Apache License 2.0 4 votes vote down vote up
public Person getMe() {
    return mMe;
}
 
Example #21
Source File: MockDatabase.java    From user-interface-samples with Apache License 2.0 4 votes vote down vote up
private MessagingStyleCommsAppData(Context context) {
    // Standard notification values:
    // Content for API <24 (M and below) devices.
    // Note: I am actually hardcoding these Strings based on info below. You would be
    // pulling these values from the same source in your database. I leave this up here, so
    // you can see the standard parts of a Notification first.
    mContentTitle = "3 Messages w/ Famous, Wendy";
    mContentText = "HEY, I see my house! :)";
    mPriority = NotificationCompat.PRIORITY_HIGH;

    // Create the users for the conversation.
    // Name preferred when replying to chat.
    mMe =
            new Person.Builder()
                    .setName("Me MacDonald")
                    .setKey("1234567890")
                    .setUri("tel:1234567890")
                    .setIcon(
                            IconCompat.createWithResource(context, R.drawable.me_macdonald))
                    .build();

    Person participant1 =
            new Person.Builder()
                    .setName("Famous Frank")
                    .setKey("9876543210")
                    .setUri("tel:9876543210")
                    .setIcon(
                            IconCompat.createWithResource(context, R.drawable.famous_fryer))
                    .build();

    Person participant2 =
            new Person.Builder()
                    .setName("Wendy Weather")
                    .setKey("2233221122")
                    .setUri("tel:2233221122")
                    .setIcon(IconCompat.createWithResource(context, R.drawable.wendy_wonda))
                    .build();

    // If the phone is in "Do not disturb mode, the user will still be notified if
    // the user(s) is starred as a favorite.
    // Note: You don't need to add yourself, aka 'me', as a participant.
    mParticipants = new ArrayList<>();
    mParticipants.add(participant1);
    mParticipants.add(participant2);

    mMessages = new ArrayList<>();

    // For each message, you need the timestamp. In this case, we are using arbitrary longs
    // representing time in milliseconds.
    mMessages.add(
            // When you are setting an image for a message, text does not display.
            new MessagingStyle.Message("", 1528490641998l, participant1)
                    .setData("image/png", resourceToUri(context, R.drawable.earth)));

    mMessages.add(
            new MessagingStyle.Message(
                    "Visiting the moon again? :P", 1528490643998l, mMe));

    mMessages.add(
            new MessagingStyle.Message("HEY, I see my house!", 1528490645998l, participant2));

    // String version of the mMessages above.
    mFullConversation =
            "Famous: [Picture of Moon]\n\n"
                    + "Me: Visiting the moon again? :P\n\n"
                    + "Wendy: HEY, I see my house! :)\n\n";

    // Responses based on the last messages of the conversation. You would use
    // Machine Learning to get these (https://developers.google.com/ml-kit/).
    mReplyChoicesBasedOnLastMessages =
            new CharSequence[] {"Me too!", "How's the weather?", "You have good eyesight."};

    // Notification channel values (for devices targeting 26 and above):
    mChannelId = "channel_messaging_1";
    // The user-visible name of the channel.
    mChannelName = "Sample Messaging";
    // The user-visible description of the channel.
    mChannelDescription = "Sample Messaging Notifications";
    mChannelImportance = NotificationManager.IMPORTANCE_MAX;
    mChannelEnableVibrate = true;
    mChannelLockscreenVisibility = NotificationCompat.VISIBILITY_PRIVATE;
}
 
Example #22
Source File: MockDatabase.java    From wear-os-samples with Apache License 2.0 4 votes vote down vote up
public ArrayList<Person> getParticipants() {
    return mParticipants;
}
 
Example #23
Source File: MockDatabase.java    From wear-os-samples with Apache License 2.0 4 votes vote down vote up
public Person getMe() {
    return mMe;
}
 
Example #24
Source File: MessagingIntentService.java    From wear-os-samples with Apache License 2.0 4 votes vote down vote up
/** Handles action for replying to messages from the notification. */
private void handleActionReply(CharSequence replyCharSequence) {
    Log.d(TAG, "handleActionReply(): " + replyCharSequence);

    if (replyCharSequence != null) {

        // TODO: Asynchronously save your message to Database and servers.

        /*
         * You have two options for updating your notification (this class uses approach #2):
         *
         *  1. Use a new NotificationCompatBuilder to create the Notification. This approach
         *  requires you to get *ALL* the information that existed in the previous
         *  Notification (and updates) and pass it to the builder. This is the approach used in
         *  the MainActivity.
         *
         *  2. Use the original NotificationCompatBuilder to create the Notification. This
         *  approach requires you to store a reference to the original builder. The benefit is
         *  you only need the new/updated information. In our case, the reply from the user
         *  which we already have here.
         *
         *  IMPORTANT NOTE: You shouldn't save/modify the resulting Notification object using
         *  its member variables and/or legacy APIs. If you want to retain anything from update
         *  to update, retain the Builder as option 2 outlines.
         */

        // Retrieves NotificationCompat.Builder used to create initial Notification
        NotificationCompat.Builder notificationCompatBuilder =
                GlobalNotificationBuilder.getNotificationCompatBuilderInstance();

        // Recreate builder from persistent state if app process is killed
        if (notificationCompatBuilder == null) {
            // Note: New builder set globally in the method
            notificationCompatBuilder = recreateBuilderWithMessagingStyle();
        }

        // Since we are adding to the MessagingStyle, we need to first retrieve the
        // current MessagingStyle from the Notification itself.
        Notification notification = notificationCompatBuilder.build();
        MessagingStyle messagingStyle =
                NotificationCompat.MessagingStyle.extractMessagingStyleFromNotification(
                        notification);

        // Add new message to the MessagingStyle. Set last parameter to null for responses
        // from user.
        messagingStyle.addMessage(replyCharSequence, System.currentTimeMillis(), (Person) null);

        // Updates the Notification
        notification = notificationCompatBuilder.setStyle(messagingStyle).build();

        // Pushes out the updated Notification
        NotificationManagerCompat notificationManagerCompat =
                NotificationManagerCompat.from(getApplicationContext());
        notificationManagerCompat.notify(NotificationsActivity.NOTIFICATION_ID, notification);
    }
}
 
Example #25
Source File: MainActivity.java    From journaldev with MIT License 3 votes vote down vote up
private void notificationWithImage() {
    Person bot = new Person.Builder()
            .setName("Bot")
            .setImportant(true)
            .setBot(true)
            .build();


    Uri uri = Uri.parse("android.resource://com.journaldev.androidpnotifications/drawable/"+R.drawable.sample_bg);

    NotificationCompat.MessagingStyle.Message message = new NotificationCompat.MessagingStyle.Message("Check out my latest article!", new Date().getTime(), bot);
    message.setData("image/*",uri);


    new NotificationCompat.MessagingStyle(bot)
            .addMessage(message)
            .setGroupConversation(true)
            .setBuilder(builder);


    notificationManager.notify(3, builder.build());
}
 
Example #26
Source File: MessagingStyle.java    From FCM-for-Mojo with GNU General Public License v3.0 2 votes vote down vote up
/**
 * @param userDisplayName the name to be displayed for any replies sent by the user before the
 *                        posting app reposts the notification with those messages after they've been actually
 *                        sent and in previous messages sent by the user added in
 *                        {@link #addMessage(Message)}
 */
public MessagingStyle(CharSequence userDisplayName) {
    super(new Person.Builder().setName(userDisplayName).build());
}
 
Example #27
Source File: MainActivity.java    From journaldev with MIT License 2 votes vote down vote up
private void notificationWithGroupConvo()
{

    Person jd = new Person.Builder()
            .setName("JournalDev")
            .build();

    Person anupam = new Person.Builder()
            .setName("Anupam")
            .setIcon(IconCompat.createWithResource(this, R.drawable.sample_photo))
            .setImportant(true)
            .build();


    Person bot = new Person.Builder()
            .setName("Bot")
            .setBot(true)
            .build();


    Uri uri = Uri.parse("android.resource://com.journaldev.androidpnotifications/drawable/"+R.drawable.sample_bg);

    NotificationCompat.MessagingStyle.Message message = new NotificationCompat.MessagingStyle.Message("", new Date().getTime(), bot);
    message.setData("image/*",uri);





    new NotificationCompat.MessagingStyle(bot)
            .addMessage("Hi. How are you?", new Date().getTime(), anupam)
            .addMessage(message)
            .addMessage("Does this image look good?", new Date().getTime(), bot)
            .addMessage("Looks good!", new Date().getTime(), jd)
            .setGroupConversation(true)
            .setConversationTitle("Sample Conversation")
            .setBuilder(builder);


    notificationManager.notify(4, builder.build());

}
 
Example #28
Source File: MainActivity.java    From journaldev with MIT License 2 votes vote down vote up
private void notificationSemantic()
{

    Person jd = new Person.Builder()
            .setName("JournalDev")
            .build();

    Person anupam = new Person.Builder()
            .setName("Anupam")
            .setIcon(IconCompat.createWithResource(this, R.drawable.sample_photo))
            .setImportant(true)
            .build();


    Person bot = new Person.Builder()
            .setName("Bot")
            .setBot(true)
            .build();


    Uri uri = Uri.parse("android.resource://com.journaldev.androidpnotifications/drawable/"+R.drawable.sample_bg);

    Intent intent = new Intent(this, MainActivity.class);
    intent.putExtra("hi","Notifications were read");
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);



    NotificationCompat.MessagingStyle.Message message = new NotificationCompat.MessagingStyle.Message("", new Date().getTime(), bot);
    message.setData("image/*",uri);

    NotificationCompat.Action replyAction =
            new NotificationCompat.Action.Builder(
                    R.drawable.sample_bg,
                    "MARK READ",
                    pendingIntent)
                    .setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_MARK_AS_READ)
                    .build();




    NotificationCompat.Builder separateBuilder = builder;
    separateBuilder.addAction(replyAction);

    new NotificationCompat.MessagingStyle(bot)
            .addMessage("Hi. How are you?", new Date().getTime(), anupam)
            .addMessage(message)
            .addMessage("Does this image look good?", new Date().getTime(), bot)
            .addMessage("Looks good!", new Date().getTime(), jd)
            .setGroupConversation(true)
            .setConversationTitle("Sample Conversation")
            .setBuilder(separateBuilder);


    notificationManager.notify(5, separateBuilder.build());

}
 
Example #29
Source File: MyFirebaseMessagingService.java    From NaviBee with GNU General Public License v3.0 votes vote down vote up
void callback(Person person);