Search in sources :

Example 1 with RemoteInput

use of androidx.core.app.RemoteInput in project Tusky by Vavassor.

the class NotificationHelper method make.

/**
 * Takes a given Mastodon notification and either creates a new Android notification or updates
 * the state of the existing notification to reflect the new interaction.
 *
 * @param context to access application preferences and services
 * @param body    a new Mastodon notification
 * @param account the account for which the notification should be shown
 */
public static void make(final Context context, Notification body, AccountEntity account, boolean isFirstOfBatch) {
    body = body.rewriteToStatusTypeIfNeeded(account.getAccountId());
    if (!filterNotification(account, body, context)) {
        return;
    }
    String rawCurrentNotifications = account.getActiveNotifications();
    JSONArray currentNotifications;
    try {
        currentNotifications = new JSONArray(rawCurrentNotifications);
    } catch (JSONException e) {
        currentNotifications = new JSONArray();
    }
    for (int i = 0; i < currentNotifications.length(); i++) {
        try {
            if (currentNotifications.getString(i).equals(body.getAccount().getName())) {
                currentNotifications.remove(i);
                break;
            }
        } catch (JSONException e) {
            Log.d(TAG, Log.getStackTraceString(e));
        }
    }
    currentNotifications.put(body.getAccount().getName());
    account.setActiveNotifications(currentNotifications.toString());
    // Notification group member
    // =========================
    final NotificationCompat.Builder builder = newNotification(context, body, account, false);
    notificationId++;
    builder.setContentTitle(titleForType(context, body, account)).setContentText(bodyForType(body, context));
    if (body.getType() == Notification.Type.MENTION || body.getType() == Notification.Type.POLL) {
        builder.setStyle(new NotificationCompat.BigTextStyle().bigText(bodyForType(body, context)));
    }
    // load the avatar synchronously
    Bitmap accountAvatar;
    try {
        FutureTarget<Bitmap> target = Glide.with(context).asBitmap().load(body.getAccount().getAvatar()).transform(new RoundedCorners(20)).submit();
        accountAvatar = target.get();
    } catch (ExecutionException | InterruptedException e) {
        Log.d(TAG, "error loading account avatar", e);
        accountAvatar = BitmapFactory.decodeResource(context.getResources(), R.drawable.avatar_default);
    }
    builder.setLargeIcon(accountAvatar);
    // Reply to mention action; RemoteInput is available from KitKat Watch, but buttons are available from Nougat
    if (body.getType() == Notification.Type.MENTION && android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        RemoteInput replyRemoteInput = new RemoteInput.Builder(KEY_REPLY).setLabel(context.getString(R.string.label_quick_reply)).build();
        PendingIntent quickReplyPendingIntent = getStatusReplyIntent(REPLY_ACTION, context, body, account);
        NotificationCompat.Action quickReplyAction = new NotificationCompat.Action.Builder(R.drawable.ic_reply_24dp, context.getString(R.string.action_quick_reply), quickReplyPendingIntent).addRemoteInput(replyRemoteInput).build();
        builder.addAction(quickReplyAction);
        PendingIntent composePendingIntent = getStatusReplyIntent(COMPOSE_ACTION, context, body, account);
        NotificationCompat.Action composeAction = new NotificationCompat.Action.Builder(R.drawable.ic_reply_24dp, context.getString(R.string.action_compose_shortcut), composePendingIntent).build();
        builder.addAction(composeAction);
    }
    builder.setSubText(account.getFullName());
    builder.setVisibility(NotificationCompat.VISIBILITY_PRIVATE);
    builder.setCategory(NotificationCompat.CATEGORY_SOCIAL);
    builder.setOnlyAlertOnce(true);
    // only alert for the first notification of a batch to avoid multiple alerts at once
    if (!isFirstOfBatch) {
        builder.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_SUMMARY);
    }
    // Summary
    // =======
    final NotificationCompat.Builder summaryBuilder = newNotification(context, body, account, true);
    if (currentNotifications.length() != 1) {
        try {
            String title = context.getResources().getQuantityString(R.plurals.notification_title_summary, currentNotifications.length(), currentNotifications.length());
            String text = joinNames(context, currentNotifications);
            summaryBuilder.setContentTitle(title).setContentText(text);
        } catch (JSONException e) {
            Log.d(TAG, Log.getStackTraceString(e));
        }
    }
    summaryBuilder.setSubText(account.getFullName());
    summaryBuilder.setVisibility(NotificationCompat.VISIBILITY_PRIVATE);
    summaryBuilder.setCategory(NotificationCompat.CATEGORY_SOCIAL);
    summaryBuilder.setOnlyAlertOnce(true);
    summaryBuilder.setGroupSummary(true);
    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
    notificationManager.notify(notificationId, builder.build());
    if (currentNotifications.length() == 1) {
        notificationManager.notify((int) account.getId(), builder.setGroupSummary(true).build());
    } else {
        notificationManager.notify((int) account.getId(), summaryBuilder.build());
    }
}
Also used : RemoteInput(androidx.core.app.RemoteInput) TaskStackBuilder(androidx.core.app.TaskStackBuilder) JSONArray(org.json.JSONArray) NotificationManagerCompat(androidx.core.app.NotificationManagerCompat) JSONException(org.json.JSONException) RoundedCorners(com.bumptech.glide.load.resource.bitmap.RoundedCorners) Bitmap(android.graphics.Bitmap) NotificationCompat(androidx.core.app.NotificationCompat) PendingIntent(android.app.PendingIntent) ExecutionException(java.util.concurrent.ExecutionException)

Example 2 with RemoteInput

use of androidx.core.app.RemoteInput in project Conversations by siacs.

the class NotificationService method buildSingleConversations.

private Builder buildSingleConversations(final ArrayList<Message> messages, final boolean notify, final boolean quietHours) {
    final Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService, quietHours ? "quiet_hours" : (notify ? "messages" : "silent_messages"));
    if (messages.size() >= 1) {
        final Conversation conversation = (Conversation) messages.get(0).getConversation();
        mBuilder.setLargeIcon(mXmppConnectionService.getAvatarService().get(conversation, AvatarService.getSystemUiAvatarSize(mXmppConnectionService)));
        mBuilder.setContentTitle(conversation.getName());
        if (Config.HIDE_MESSAGE_TEXT_IN_NOTIFICATION) {
            int count = messages.size();
            mBuilder.setContentText(mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages, count, count));
        } else {
            Message message;
            // TODO starting with Android 9 we might want to put images in MessageStyle
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P && (message = getImage(messages)) != null) {
                modifyForImage(mBuilder, message, messages);
            } else {
                modifyForTextOnly(mBuilder, messages);
            }
            RemoteInput remoteInput = new RemoteInput.Builder("text_reply").setLabel(UIHelper.getMessageHint(mXmppConnectionService, conversation)).build();
            PendingIntent markAsReadPendingIntent = createReadPendingIntent(conversation);
            NotificationCompat.Action markReadAction = new NotificationCompat.Action.Builder(R.drawable.ic_drafts_white_24dp, mXmppConnectionService.getString(R.string.mark_as_read), markAsReadPendingIntent).setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_MARK_AS_READ).setShowsUserInterface(false).build();
            final String replyLabel = mXmppConnectionService.getString(R.string.reply);
            final String lastMessageUuid = Iterables.getLast(messages).getUuid();
            final NotificationCompat.Action replyAction = new NotificationCompat.Action.Builder(R.drawable.ic_send_text_offline, replyLabel, createReplyIntent(conversation, lastMessageUuid, false)).setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_REPLY).setShowsUserInterface(false).addRemoteInput(remoteInput).build();
            final NotificationCompat.Action wearReplyAction = new NotificationCompat.Action.Builder(R.drawable.ic_wear_reply, replyLabel, createReplyIntent(conversation, lastMessageUuid, true)).addRemoteInput(remoteInput).build();
            mBuilder.extend(new NotificationCompat.WearableExtender().addAction(wearReplyAction));
            int addedActionsCount = 1;
            mBuilder.addAction(markReadAction);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                mBuilder.addAction(replyAction);
                ++addedActionsCount;
            }
            if (displaySnoozeAction(messages)) {
                String label = mXmppConnectionService.getString(R.string.snooze);
                PendingIntent pendingSnoozeIntent = createSnoozeIntent(conversation);
                NotificationCompat.Action snoozeAction = new NotificationCompat.Action.Builder(R.drawable.ic_notifications_paused_white_24dp, label, pendingSnoozeIntent).build();
                mBuilder.addAction(snoozeAction);
                ++addedActionsCount;
            }
            if (addedActionsCount < 3) {
                final Message firstLocationMessage = getFirstLocationMessage(messages);
                if (firstLocationMessage != null) {
                    final PendingIntent pendingShowLocationIntent = createShowLocationIntent(firstLocationMessage);
                    if (pendingShowLocationIntent != null) {
                        final String label = mXmppConnectionService.getResources().getString(R.string.show_location);
                        NotificationCompat.Action locationAction = new NotificationCompat.Action.Builder(R.drawable.ic_room_white_24dp, label, pendingShowLocationIntent).build();
                        mBuilder.addAction(locationAction);
                        ++addedActionsCount;
                    }
                }
            }
            if (addedActionsCount < 3) {
                Message firstDownloadableMessage = getFirstDownloadableMessage(messages);
                if (firstDownloadableMessage != null) {
                    String label = mXmppConnectionService.getResources().getString(R.string.download_x_file, UIHelper.getFileDescriptionString(mXmppConnectionService, firstDownloadableMessage));
                    PendingIntent pendingDownloadIntent = createDownloadIntent(firstDownloadableMessage);
                    NotificationCompat.Action downloadAction = new NotificationCompat.Action.Builder(R.drawable.ic_file_download_white_24dp, label, pendingDownloadIntent).build();
                    mBuilder.addAction(downloadAction);
                    ++addedActionsCount;
                }
            }
        }
        if (conversation.getMode() == Conversation.MODE_SINGLE) {
            Contact contact = conversation.getContact();
            Uri systemAccount = contact.getSystemAccount();
            if (systemAccount != null) {
                mBuilder.addPerson(systemAccount.toString());
            }
        }
        mBuilder.setWhen(conversation.getLatestMessage().getTimeSent());
        mBuilder.setSmallIcon(R.drawable.ic_notification);
        mBuilder.setDeleteIntent(createDeleteIntent(conversation));
        mBuilder.setContentIntent(createContentIntent(conversation));
    }
    return mBuilder;
}
Also used : RemoteInput(androidx.core.app.RemoteInput) Message(eu.siacs.conversations.entities.Message) Builder(androidx.core.app.NotificationCompat.Builder) Conversation(eu.siacs.conversations.entities.Conversation) SpannableString(android.text.SpannableString) Uri(android.net.Uri) Contact(eu.siacs.conversations.entities.Contact) NotificationCompat(androidx.core.app.NotificationCompat) PendingIntent(android.app.PendingIntent)

Example 3 with RemoteInput

use of androidx.core.app.RemoteInput in project Gadgetbridge by Freeyourgadget.

the class DebugActivity method testNotification.

private void testNotification() {
    Intent notificationIntent = new Intent(getApplicationContext(), DebugActivity.class);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);
    RemoteInput remoteInput = new RemoteInput.Builder(EXTRA_REPLY).build();
    Intent replyIntent = new Intent(ACTION_REPLY);
    PendingIntent replyPendingIntent = PendingIntent.getBroadcast(this, 0, replyIntent, 0);
    NotificationCompat.Action action = new NotificationCompat.Action.Builder(android.R.drawable.ic_input_add, "Reply", replyPendingIntent).addRemoteInput(remoteInput).build();
    NotificationCompat.WearableExtender wearableExtender = new NotificationCompat.WearableExtender().addAction(action);
    NotificationCompat.Builder ncomp = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID).setContentTitle(getString(R.string.test_notification)).setContentText(getString(R.string.this_is_a_test_notification_from_gadgetbridge)).setTicker(getString(R.string.this_is_a_test_notification_from_gadgetbridge)).setSmallIcon(R.drawable.ic_notification).setAutoCancel(true).setContentIntent(pendingIntent).extend(wearableExtender);
    GB.notify((int) System.currentTimeMillis(), ncomp.build(), this);
}
Also used : RemoteInput(androidx.core.app.RemoteInput) NotificationCompat(androidx.core.app.NotificationCompat) PendingIntent(android.app.PendingIntent) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent)

Example 4 with RemoteInput

use of androidx.core.app.RemoteInput in project orgzly-android by orgzly.

the class Notifications method createNewNoteNotification.

public static void createNewNoteNotification(Context context) {
    if (BuildConfig.LOG_DEBUG)
        LogUtils.d(TAG, context);
    PendingIntent resultPendingIntent = ShareActivity.createNewNoteIntent(context, null);
    /* Build notification */
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context, NotificationChannels.ONGOING).setOngoing(true).setSmallIcon(R.drawable.ic_logo_for_notification).setContentTitle(context.getString(R.string.new_note)).setContentText(context.getString(R.string.tap_to_create_new_note)).setColor(ContextCompat.getColor(context, R.color.notification)).setContentIntent(resultPendingIntent);
    builder.setPriority(getNotificationPriority(AppPreferences.ongoingNotificationPriority(context)));
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        PendingIntent newNotePendingIntent = PendingIntent.getBroadcast(context, 0, new Intent(context, NewNoteBroadcastReceiver.class), 0);
        RemoteInput remoteInput = new RemoteInput.Builder(NOTE_TITLE).setLabel(context.getString(R.string.quick_note)).build();
        /* Add new note action */
        NotificationCompat.Action action = new NotificationCompat.Action.Builder(R.drawable.ic_add_white_24dp, context.getString(R.string.quick_note), newNotePendingIntent).addRemoteInput(remoteInput).build();
        builder.addAction(action);
    }
    /* Add open action */
    PendingIntent openAppPendingIntent = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
    builder.addAction(R.drawable.ic_open_in_new_white_24dp, context.getString(R.string.open), openAppPendingIntent);
    /* Add sync action */
    Intent syncIntent = new Intent(context, SyncService.class);
    syncIntent.setAction(AppIntent.ACTION_SYNC_START);
    PendingIntent syncPendingIntent = PendingIntent.getService(context, 0, syncIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.addAction(R.drawable.ic_sync_white_24dp, context.getString(R.string.sync), syncPendingIntent);
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(ONGOING_NEW_NOTE_ID, builder.build());
}
Also used : RemoteInput(androidx.core.app.RemoteInput) NewNoteBroadcastReceiver(com.orgzly.android.NewNoteBroadcastReceiver) NotificationManager(android.app.NotificationManager) NotificationCompat(androidx.core.app.NotificationCompat) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) AppIntent(com.orgzly.android.AppIntent) PendingIntent(android.app.PendingIntent) MainActivity(com.orgzly.android.ui.main.MainActivity)

Example 5 with RemoteInput

use of androidx.core.app.RemoteInput in project react-native-push-notification by zo0r.

the class RNPushNotificationHelper method sendToNotificationCentreWithPicture.

public void sendToNotificationCentreWithPicture(Bundle bundle, Bitmap largeIconBitmap, Bitmap bigPictureBitmap, Bitmap bigLargeIconBitmap) {
    try {
        Class intentClass = getMainActivityClass();
        if (intentClass == null) {
            Log.e(LOG_TAG, "No activity class found for the notification");
            return;
        }
        if (bundle.getString("message") == null) {
            // this happens when a 'data' notification is received - we do not synthesize a local notification in this case
            Log.d(LOG_TAG, "Ignore this message if you sent data-only notification. Cannot send to notification centre because there is no 'message' field in: " + bundle);
            return;
        }
        String notificationIdString = bundle.getString("id");
        if (notificationIdString == null) {
            Log.e(LOG_TAG, "No notification ID specified for the notification");
            return;
        }
        Resources res = context.getResources();
        String packageName = context.getPackageName();
        String title = bundle.getString("title");
        if (title == null) {
            ApplicationInfo appInfo = context.getApplicationInfo();
            title = context.getPackageManager().getApplicationLabel(appInfo).toString();
        }
        int priority = NotificationCompat.PRIORITY_HIGH;
        final String priorityString = bundle.getString("priority");
        if (priorityString != null) {
            switch(priorityString.toLowerCase()) {
                case "max":
                    priority = NotificationCompat.PRIORITY_MAX;
                    break;
                case "high":
                    priority = NotificationCompat.PRIORITY_HIGH;
                    break;
                case "low":
                    priority = NotificationCompat.PRIORITY_LOW;
                    break;
                case "min":
                    priority = NotificationCompat.PRIORITY_MIN;
                    break;
                case "default":
                    priority = NotificationCompat.PRIORITY_DEFAULT;
                    break;
                default:
                    priority = NotificationCompat.PRIORITY_HIGH;
            }
        }
        int visibility = NotificationCompat.VISIBILITY_PRIVATE;
        final String visibilityString = bundle.getString("visibility");
        if (visibilityString != null) {
            switch(visibilityString.toLowerCase()) {
                case "private":
                    visibility = NotificationCompat.VISIBILITY_PRIVATE;
                    break;
                case "public":
                    visibility = NotificationCompat.VISIBILITY_PUBLIC;
                    break;
                case "secret":
                    visibility = NotificationCompat.VISIBILITY_SECRET;
                    break;
                default:
                    visibility = NotificationCompat.VISIBILITY_PRIVATE;
            }
        }
        String channel_id = bundle.getString("channelId");
        if (channel_id == null) {
            channel_id = this.config.getNotificationDefaultChannelId();
        }
        NotificationCompat.Builder notification = new NotificationCompat.Builder(context, channel_id).setContentTitle(title).setTicker(bundle.getString("ticker")).setVisibility(visibility).setPriority(priority).setAutoCancel(bundle.getBoolean("autoCancel", true)).setOnlyAlertOnce(bundle.getBoolean("onlyAlertOnce", false));
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            // API 24 and higher
            // Restore showing timestamp on Android 7+
            // Source: https://developer.android.com/reference/android/app/Notification.Builder.html#setShowWhen(boolean)
            boolean showWhen = bundle.getBoolean("showWhen", true);
            notification.setShowWhen(showWhen);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // API 26 and higher
            // Changing Default mode of notification
            notification.setDefaults(Notification.DEFAULT_LIGHTS);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
            // API 20 and higher
            String group = bundle.getString("group");
            if (group != null) {
                notification.setGroup(group);
            }
            if (bundle.containsKey("groupSummary") || bundle.getBoolean("groupSummary")) {
                notification.setGroupSummary(bundle.getBoolean("groupSummary"));
            }
        }
        String numberString = bundle.getString("number");
        if (numberString != null) {
            notification.setNumber(Integer.parseInt(numberString));
        }
        // Small icon
        int smallIconResId = 0;
        String smallIcon = bundle.getString("smallIcon");
        if (smallIcon != null && !smallIcon.isEmpty()) {
            smallIconResId = res.getIdentifier(smallIcon, "drawable", packageName);
            if (smallIconResId == 0) {
                smallIconResId = res.getIdentifier(smallIcon, "mipmap", packageName);
            }
        } else if (smallIcon == null) {
            smallIconResId = res.getIdentifier("ic_notification", "mipmap", packageName);
        }
        if (smallIconResId == 0) {
            smallIconResId = res.getIdentifier("ic_launcher", "mipmap", packageName);
            if (smallIconResId == 0) {
                smallIconResId = android.R.drawable.ic_dialog_info;
            }
        }
        notification.setSmallIcon(smallIconResId);
        // Large icon
        if (largeIconBitmap == null) {
            int largeIconResId = 0;
            String largeIcon = bundle.getString("largeIcon");
            if (largeIcon != null && !largeIcon.isEmpty()) {
                largeIconResId = res.getIdentifier(largeIcon, "drawable", packageName);
                if (largeIconResId == 0) {
                    largeIconResId = res.getIdentifier(largeIcon, "mipmap", packageName);
                }
            } else if (largeIcon == null) {
                largeIconResId = res.getIdentifier("ic_launcher", "mipmap", packageName);
            }
            // Before Lolipop there was no large icon for notifications.
            if (largeIconResId != 0 && (largeIcon != null || Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)) {
                largeIconBitmap = BitmapFactory.decodeResource(res, largeIconResId);
            }
        }
        if (largeIconBitmap != null) {
            notification.setLargeIcon(largeIconBitmap);
        }
        String message = bundle.getString("message");
        notification.setContentText(message);
        String subText = bundle.getString("subText");
        if (subText != null) {
            notification.setSubText(subText);
        }
        NotificationCompat.Style style;
        if (bigPictureBitmap != null) {
            // Big large icon
            if (bigLargeIconBitmap == null) {
                int bigLargeIconResId = 0;
                String bigLargeIcon = bundle.getString("bigLargeIcon");
                if (bigLargeIcon != null && !bigLargeIcon.isEmpty()) {
                    bigLargeIconResId = res.getIdentifier(bigLargeIcon, "mipmap", packageName);
                    if (bigLargeIconResId != 0) {
                        bigLargeIconBitmap = BitmapFactory.decodeResource(res, bigLargeIconResId);
                    }
                }
            }
            style = new NotificationCompat.BigPictureStyle().bigPicture(bigPictureBitmap).setBigContentTitle(title).setSummaryText(message).bigLargeIcon(bigLargeIconBitmap);
        } else {
            String bigText = bundle.getString("bigText");
            if (bigText == null) {
                style = new NotificationCompat.BigTextStyle().bigText(message);
            } else {
                Spanned styledText = HtmlCompat.fromHtml(bigText, HtmlCompat.FROM_HTML_MODE_LEGACY);
                style = new NotificationCompat.BigTextStyle().bigText(styledText);
            }
        }
        notification.setStyle(style);
        Intent intent = new Intent(context, intentClass);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        bundle.putBoolean("foreground", this.isApplicationInForeground());
        bundle.putBoolean("userInteraction", true);
        intent.putExtra("notification", bundle);
        // Add message_id to intent so react-native-firebase/messaging can identify it
        String messageId = bundle.getString("messageId");
        if (messageId != null) {
            intent.putExtra("message_id", messageId);
        }
        Uri soundUri = null;
        if (!bundle.containsKey("playSound") || bundle.getBoolean("playSound")) {
            String soundName = bundle.getString("soundName");
            soundUri = getSoundUri(soundName);
            notification.setSound(soundUri);
        }
        if (soundUri == null || Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            notification.setSound(null);
        }
        if (bundle.containsKey("ongoing") || bundle.getBoolean("ongoing")) {
            notification.setOngoing(bundle.getBoolean("ongoing"));
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            notification.setCategory(NotificationCompat.CATEGORY_CALL);
            String color = bundle.getString("color");
            int defaultColor = this.config.getNotificationColor();
            if (color != null) {
                notification.setColor(Color.parseColor(color));
            } else if (defaultColor != -1) {
                notification.setColor(defaultColor);
            }
        }
        int notificationID = Integer.parseInt(notificationIdString);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, notificationID, intent, Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ? PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE : PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationManager notificationManager = notificationManager();
        long[] vibratePattern = new long[] { 0 };
        if (!bundle.containsKey("vibrate") || bundle.getBoolean("vibrate")) {
            long vibration = bundle.containsKey("vibration") ? (long) bundle.getDouble("vibration") : DEFAULT_VIBRATION;
            if (vibration == 0)
                vibration = DEFAULT_VIBRATION;
            vibratePattern = new long[] { 0, vibration };
            notification.setVibrate(vibratePattern);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // Define the shortcutId
            String shortcutId = bundle.getString("shortcutId");
            if (shortcutId != null) {
                notification.setShortcutId(shortcutId);
            }
            Long timeoutAfter = (long) bundle.getDouble("timeoutAfter");
            if (timeoutAfter != null && timeoutAfter >= 0) {
                notification.setTimeoutAfter(timeoutAfter);
            }
        }
        Long when = (long) bundle.getDouble("when");
        if (when != null && when >= 0) {
            notification.setWhen(when);
        }
        notification.setUsesChronometer(bundle.getBoolean("usesChronometer", false));
        notification.setChannelId(channel_id);
        notification.setContentIntent(pendingIntent);
        JSONArray actionsArray = null;
        try {
            actionsArray = bundle.getString("actions") != null ? new JSONArray(bundle.getString("actions")) : null;
        } catch (JSONException e) {
            Log.e(LOG_TAG, "Exception while converting actions to JSON object.", e);
        }
        if (actionsArray != null) {
            // No icon for now. The icon value of 0 shows no icon.
            int icon = 0;
            // Add button for each actions.
            for (int i = 0; i < actionsArray.length(); i++) {
                String action;
                try {
                    action = actionsArray.getString(i);
                } catch (JSONException e) {
                    Log.e(LOG_TAG, "Exception while getting action from actionsArray.", e);
                    continue;
                }
                Intent actionIntent = new Intent(context, RNPushNotificationActions.class);
                actionIntent.setAction(packageName + ".ACTION_" + i);
                actionIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                // Add "action" for later identifying which button gets pressed.
                bundle.putString("action", action);
                actionIntent.putExtra("notification", bundle);
                actionIntent.setPackage(packageName);
                if (messageId != null) {
                    intent.putExtra("message_id", messageId);
                }
                int flags = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ? PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE : PendingIntent.FLAG_UPDATE_CURRENT;
                PendingIntent pendingActionIntent = PendingIntent.getBroadcast(context, notificationID, actionIntent, flags);
                if (action.equals("ReplyInput")) {
                    // Action with inline reply
                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT_WATCH) {
                        RemoteInput remoteInput = new RemoteInput.Builder(KEY_TEXT_REPLY).setLabel(bundle.getString("reply_placeholder_text")).build();
                        NotificationCompat.Action replyAction = new NotificationCompat.Action.Builder(icon, bundle.getString("reply_button_text"), pendingActionIntent).addRemoteInput(remoteInput).setAllowGeneratedReplies(true).build();
                        notification.addAction(replyAction);
                    } else {
                        // The notification will not have action
                        break;
                    }
                } else {
                    // Add "action" for later identifying which button gets pressed
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        notification.addAction(new NotificationCompat.Action.Builder(icon, action, pendingActionIntent).build());
                    } else {
                        notification.addAction(icon, action, pendingActionIntent);
                    }
                }
            }
        }
        // it will be scheduled again.
        if (scheduledNotificationsPersistence.getString(notificationIdString, null) != null) {
            SharedPreferences.Editor editor = scheduledNotificationsPersistence.edit();
            editor.remove(notificationIdString);
            editor.apply();
        }
        if (!(this.isApplicationInForeground() && bundle.getBoolean("ignoreInForeground"))) {
            Notification info = notification.build();
            info.defaults |= Notification.DEFAULT_LIGHTS;
            if (bundle.containsKey("tag")) {
                String tag = bundle.getString("tag");
                notificationManager.notify(tag, notificationID, info);
            } else {
                notificationManager.notify(notificationID, info);
            }
        }
        // Can't use setRepeating for recurring notifications because setRepeating
        // is inexact by default starting API 19 and the notifications are not fired
        // at the exact time. During testing, it was found that notifications could
        // late by many minutes.
        this.scheduleNextNotificationIfRepeating(bundle);
    } catch (Exception e) {
        Log.e(LOG_TAG, "failed to send push notification", e);
    }
}
Also used : ApplicationInfo(android.content.pm.ApplicationInfo) Uri(android.net.Uri) Notification(android.app.Notification) StatusBarNotification(android.service.notification.StatusBarNotification) NotificationCompat(androidx.core.app.NotificationCompat) RemoteInput(androidx.core.app.RemoteInput) NotificationManager(android.app.NotificationManager) SharedPreferences(android.content.SharedPreferences) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) Spanned(android.text.Spanned) JSONException(org.json.JSONException) Resources(android.content.res.Resources) PendingIntent(android.app.PendingIntent)

Aggregations

PendingIntent (android.app.PendingIntent)5 NotificationCompat (androidx.core.app.NotificationCompat)5 RemoteInput (androidx.core.app.RemoteInput)5 Intent (android.content.Intent)3 NotificationManager (android.app.NotificationManager)2 Uri (android.net.Uri)2 JSONArray (org.json.JSONArray)2 JSONException (org.json.JSONException)2 Notification (android.app.Notification)1 SharedPreferences (android.content.SharedPreferences)1 ApplicationInfo (android.content.pm.ApplicationInfo)1 Resources (android.content.res.Resources)1 Bitmap (android.graphics.Bitmap)1 StatusBarNotification (android.service.notification.StatusBarNotification)1 SpannableString (android.text.SpannableString)1 Spanned (android.text.Spanned)1 Builder (androidx.core.app.NotificationCompat.Builder)1 NotificationManagerCompat (androidx.core.app.NotificationManagerCompat)1 TaskStackBuilder (androidx.core.app.TaskStackBuilder)1 RoundedCorners (com.bumptech.glide.load.resource.bitmap.RoundedCorners)1