簡體   English   中英

在Android上未閱讀消息時出現錯誤通知

[英]Wrong notification when messages are unread on Android

我正在為我的Android應用程序通知使用Firebase cloudmessaging,所以我的問題是,如果用戶取消了該通知,則發送通知時,我單擊后發送的下一個通知將打開第一個已被取消的通知,即使我發送第三個通知,並且用戶同時關閉了第一個和第二個通知,如果單擊第三個通知,它將打開第一個通知。 我正在將Firebase雲消息傳遞與數據一起使用,並發送(標題,摘錄,圖像,鏈接)。 在通知欄中,所有內容都很酷而且正確,但是當單擊鏈接時,鏈接更改了,並且Webview將打開第一個通知。

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMsgService";

    // [START receive_message]
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        Log.d(TAG, "From: " + remoteMessage.getFrom());

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
            sendNotification(remoteMessage.getData().get("title"), remoteMessage.getData().get("body"),
                    Integer.parseInt(remoteMessage.getData().get("topic")), remoteMessage.getData().get("link"), remoteMessage.getData().get("imageUrl"), Integer.parseInt(remoteMessage.getData().get("id")));

            if (/* Check if data needs to be processed by long running job */ true) {
                // For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.
                scheduleJob();
            } else {
                // Handle message within 10 seconds
                handleNow();
            }

        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
            sendNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody(),
                    0, " ", " ", 0);
        }
    }
    // [END receive_message]

    /**
     * Schedule a job using FirebaseJobDispatcher.
     */
    private void scheduleJob() {
        // [START dispatch_job]
        FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));
        Job myJob = dispatcher.newJobBuilder()
                .setService(MyJobService.class)
                .setTag("my-job-tag")
                .build();
        dispatcher.schedule(myJob);
        // [END dispatch_job]
    }

    /**
     * Handle time allotted to BroadcastReceivers.
     */
    private void handleNow() {
        Log.d(TAG, "Short lived task is done.");
    }

    /**
     * Create and show a simple notification containing the received FCM message.
     *
     * @param messageBody FCM message body received.
     */
    @TargetApi(Build.VERSION_CODES.O)
    private void sendNotification(String messageTitle, String messageBody, int topic, String link, String imageUrl, int id) {

        PendingIntent pendingIntent;
        if (topic == 1){
            Intent intent = new Intent(this, WebActivity.class);
            // Create the TaskStackBuilder and add the intent, which inflates the back stack
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
            stackBuilder.addNextIntentWithParentStack(intent);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra("link", link);
            intent.putExtra("title", messageTitle);
            // Get the PendingIntent containing the entire back stack
            pendingIntent =
                    stackBuilder.getPendingIntent(0, PendingIntent.FLAG_ONE_SHOT);
        }else{
            Intent intent = new Intent(this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra("link", link);
            intent.putExtra("topic", topic);
            pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                    PendingIntent.FLAG_ONE_SHOT);
        }

        String channelId = getString(R.string.default_notification_channel_id);

        InputStream in;
        Bitmap myBitmap = null;
        try {
            URL url = new URL(imageUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            in = connection.getInputStream();
            myBitmap = BitmapFactory.decodeStream(in);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, channelId)
                        .setPriority(NotificationManager.IMPORTANCE_DEFAULT)
                        .setChannelId(channelId)
                        .setSmallIcon(R.drawable.ic_stat_name)
                        .setLargeIcon(myBitmap)
                        .setContentTitle(messageTitle)
                        .setContentText(messageBody)
                        .setColor(ContextCompat.getColor(getApplicationContext(), R.color.colorAccent))
                        .setAutoCancel(true)
                        .setStyle(new NotificationCompat.BigTextStyle().bigText(messageTitle))
                        .setStyle(new NotificationCompat.BigPictureStyle().bigPicture(myBitmap))
                        .setGroupSummary(true)
                        .setGroup(String.valueOf(topic))
                        .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        // Since android Oreo notification channel is needed.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = getString(R.string.channel_name);
            String description = "The Channel";
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel(channelId, name, importance);
            channel.setDescription(description);
            channel.setShowBadge(true);
            // Register the channel with the system; you can't change the importance
            // or other notification behaviors after this
            notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
            notificationManager.createNotificationChannelGroup(new NotificationChannelGroup(String.valueOf(topic), "Articles"));
        }

        notificationManager.notify(id /* ID of notification */, notificationBuilder.build());
    }
}

預期的結果是,如果用戶關閉了第一個通知,則單擊該按鈕,Webview將打開從該通知發送的第二個信息。

因此,經過大量研究,我發現我必須使用PendingIntent.FLAG_UPDATE_CURRENT更新我的意圖,並在每次創建新意圖時更改該意圖的request code ,這就是將來任何出現此問題的人的新代碼:

PendingIntent pendingIntent;
        if (topic == 1){
            Intent intent = new Intent(this, WebActivity.class);
            // Create the TaskStackBuilder and add the intent, which inflates the back stack
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
            stackBuilder.addNextIntentWithParentStack(intent);
            intent.putExtra("link", link);
            intent.putExtra("title", messageTitle);
            intent.setAction("actionstring" + System.currentTimeMillis());
            // Get the PendingIntent containing the entire back stack
            pendingIntent =
                    stackBuilder.getPendingIntent(id, PendingIntent.FLAG_UPDATE_CURRENT);
        }else{
            Intent intent = new Intent(this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra("link", link);
            intent.putExtra("topic", topic);
            pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                    PendingIntent.FLAG_ONE_SHOT);
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM