android捆绑demo_Android捆绑通知

android捆绑demo

In this tutorial, we’ll be implementing Bundled Notifications in our Android Application. We’ve seen and implemented Direct Reply for Android Nougat. If you aren’t aware about Notifications and Pending Intents do go through the tutorial before proceeding.

在本教程中,我们将在Android应用程序中实现捆绑通知。 我们已经看到并实现了针对Android Nougat的直接回复 。 如果您不了解通知和待处理的意图 ,请先阅读本教程,然后再继续。

Android捆绑通知 (Android Bundled Notifications)

Android Bundled Notifications are handy when you have too many notifications stacked vertically. Bundled Notifications collapse them all into a single notification with a group summary set on the group notification. This saves us from scrolling through all the notifications. Also, if you receive many single notifications at once, instead of getting multiple noisy notification sounds, bundled notifications would give a single notification sound.

当垂直堆积过多的通知时,Android捆绑通知非常方便。 捆绑的通知将它们全部折叠到一个通知中,并在组通知上设置了组摘要。 这使我们免于滚动浏览所有通知。 另外,如果您一次收到许多单个通知,则捆绑的通知不会发出多个嘈杂的通知声音,而是会发出单个通知声音。

A Bundle Notification is of the format:

捆绑通知的格式为:

  • 1 Summary Notification

    1摘要通知
  • N enclosed Single Notifications

    N个随附的单一通知

We can set a separate tone for every single notification. Every notification of a bundle would have the same group key.

我们可以为每个通知设置单独的音调。 每个捆绑通知都将具有相同的组密钥。

When a new notification is added, it gets merged in the bundle with the matching group key.

添加新通知后,它将与匹配的组密钥合并到捆绑包中。

We can add a separate action on each notification click as well as a separate action on bundle notification click.
The Bundle Notification can exist without any enclosed notifications.

我们可以为每个通知单击添加单独的操作,也可以为捆绑通知单击添加单独的操作。
捆绑通知可以不带任何附带的通知而存在。

创建捆绑通知 (Creating a Bundle Notification)

A Bundle Notification is defined in the following way.

捆绑通知是通过以下方式定义的。

NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                    NotificationChannel groupChannel = new NotificationChannel("bundle_channel_id", "bundle_channel_name", NotificationManager.IMPORTANCE_LOW);
                    notificationManager.createNotificationChannel(groupChannel);
                }


NotificationCompat.Builder summaryNotificationBuilder = new NotificationCompat.Builder(this, "bundle_channel_id")
                        .setGroup(bundle_notification_id)
                        .setGroupSummary(true)
                        .setContentTitle("Bundled Notification. " + bundleNotificationId)
                        .setContentText("Content Text for bundle notification")
                        .setSmallIcon(R.mipmap.ic_launcher);

                notificationManager.notify(bundleNotificationId, summaryNotificationBuilder.build());

A Bundle Notification must have the setGroupSummary() set to true.

捆绑通知必须将setGroupSummary()设置为true。

The group key set in the setGroup() method must be set in all the notifications that are to be enclosed in the bundle.

必须在捆绑包中包含的所有通知中设置setGroup()方法中设置的组密钥。

Note: A bundle_channel_id needs to defined since Android Oreo. We’ve discussed Notification Channels at length in a separate tutorial.

注意 :从Android Oreo开始,需要定义bundle_channel_id。 我们已经在单独的教程中详细讨论了通知通道。

We’ve set the importance of the bundle notification channel to LOW to avoid simultaneous sounds from the Bundle and single notifications. We’ll create a separate channel for single notifications.

我们已将捆绑包通知通道的重要性设置为“ LOW以避免捆绑包和单个通知同时发出声音。 我们将为单个通知创建一个单独的渠道。

In the sample application, we’ll be implementing the Bundle Notifications feature. We’ll be using a Button to create a new Bundle and another button to add new Single Notifications in the current Bundle.

在示例应用程序中,我们将实现捆绑通知功能。 我们将使用一个Button创建一个新的Bundle,使用另一个Button在当前Bundle中添加新的Single Notifications。

On a notification click, we’ll cancel the notification and display it’s ID in a Toast.

点击通知后,我们将取消该通知并将其ID显示在Toast中

We’ll not be focusing on push notifications from the backend in this tutorial. Our goal is to understand the Bundle Notifications feature only.

在本教程中,我们将不再关注后端的推送通知。 我们的目标是仅了解捆绑包通知功能。

Android捆绑通知项目结构 (Android Bundled Notifications Project Structure)

A Single Activity application.

单一活动应用程序。

Android捆绑通知代码 (Android Bundled Notifications Code)

The code for the activity_main.xml layout class is given below.

下面给出了activity_main.xml布局类的代码。

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.journaldev.bundlednotificationsexample.MainActivity">

    <Button
        android:id="@+id/btnBundleNotification"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Bundle Notification"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btnSingleNotification"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Add Notification to Bundle"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btnBundleNotification" />

</android.support.constraint.ConstraintLayout>

The code for the MainActivity.java class is given below.

下面给出MainActivity.java类的代码。

package com.journaldev.bundlednotificationsexample;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    Button btnBundleNotification, btnSingleNotification;
    NotificationManager notificationManager;
    int bundleNotificationId = 100;
    int singleNotificationId = 100;
    NotificationCompat.Builder summaryNotificationBuilder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        btnBundleNotification = findViewById(R.id.btnBundleNotification);
        btnSingleNotification = findViewById(R.id.btnSingleNotification);
        btnBundleNotification.setOnClickListener(this);
        btnSingleNotification.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnBundleNotification:


                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                    NotificationChannel groupChannel = new NotificationChannel("bundle_channel_id", "bundle_channel_name", NotificationManager.IMPORTANCE_LOW);
                    notificationManager.createNotificationChannel(groupChannel);
                }
                bundleNotificationId += 100;
                singleNotificationId = bundleNotificationId;
                String bundle_notification_id = "bundle_notification_" + bundleNotificationId;
                Intent resultIntent = new Intent(this, MainActivity.class);
                resultIntent.putExtra("notification", "Summary Notification Clicked");
                resultIntent.putExtra("notification_id", bundleNotificationId);
                resultIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);


                summaryNotificationBuilder = new NotificationCompat.Builder(this, "bundle_channel_id")
                        .setGroup(bundle_notification_id)
                        .setGroupSummary(true)
                        .setContentTitle("Bundled Notification. " + bundleNotificationId)
                        .setContentText("Content Text for bundle notification")
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setContentIntent(resultPendingIntent);

                notificationManager.notify(bundleNotificationId, summaryNotificationBuilder.build());

                break;

            case R.id.btnSingleNotification:


                bundle_notification_id = "bundle_notification_" + bundleNotificationId;

                resultIntent = new Intent(this, MainActivity.class);
                resultIntent.putExtra("notification", "Summary Notification Clicked");
                resultIntent.putExtra("notification_id", bundleNotificationId);
                resultIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);

                //We need to update the bundle notification every time a new notification comes up.
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                    if (notificationManager.getNotificationChannels().size() < 2) {
                        NotificationChannel groupChannel = new NotificationChannel("bundle_channel_id", "bundle_channel_name", NotificationManager.IMPORTANCE_LOW);
                        notificationManager.createNotificationChannel(groupChannel);
                        NotificationChannel channel = new NotificationChannel("channel_id", "channel_name", NotificationManager.IMPORTANCE_DEFAULT);
                        notificationManager.createNotificationChannel(channel);
                    }
                }
                summaryNotificationBuilder = new NotificationCompat.Builder(this, "bundle_channel_id")
                        .setGroup(bundle_notification_id)
                        .setGroupSummary(true)
                        .setContentTitle("Bundled Notification " + bundleNotificationId)
                        .setContentText("Content Text for group summary")
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setContentIntent(resultPendingIntent);


                if (singleNotificationId == bundleNotificationId)
                    singleNotificationId = bundleNotificationId + 1;
                else
                    singleNotificationId++;

                resultIntent = new Intent(this, MainActivity.class);
                resultIntent.putExtra("notification", "Single notification clicked");
                resultIntent.putExtra("notification_id", singleNotificationId);
                resultIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);


                NotificationCompat.Builder notification = new NotificationCompat.Builder(this, "channel_id")
                        .setGroup(bundle_notification_id)
                        .setContentTitle("New Notification " + singleNotificationId)
                        .setContentText("Content for the notification")
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setGroupSummary(false)
                        .setContentIntent(resultPendingIntent);

                notificationManager.notify(singleNotificationId, notification.build());
                notificationManager.notify(bundleNotificationId, summaryNotificationBuilder.build());
                break;

        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        Bundle extras = intent.getExtras();
        if (extras != null) {
            int notification_id = extras.getInt("notification_id");
            Toast.makeText(getApplicationContext(), "Notification with ID " + notification_id + " is cancelled", Toast.LENGTH_LONG).show();
            notificationManager.cancel(notification_id);
        }
    }
}
  1. btnSingleNotification adds a Single Notification in the current bundle notification. If the current bundle notification doesn’t exist it creates one first.

    btnSingleNotification在当前的捆绑软件通知中添加单个通知。 如果当前的捆绑包通知不存在,它将首先创建一个。
  2. btnBundleNotification creates a new Bundle Notification and updates the group key by incrementing the id.

    btnBundleNotification创建一个新的捆绑通知,并通过增加ID来更新组密钥。
  3. We set a bundleNotificationId equal to the singleNotificationId initially.

    我们设置了bundleNotificationId等于singleNotificationId开始。
  4. Every time a new bundle notification is created, we increment the bundleNotificationId by 100.

    每次创建新的包通知时,我们都会将bundleNotificationId增加100。
  5. Every time a single notification is created inside the bundle notification, we increment the singleNotificationId by 1 on the current bundleNotificationId.

    每一个通知捆绑通知内创造了时间,我们增加singleNotificationId对当前bundleNotificationId 1。
  6. We’ve created separate channels for Bundle and Single Notifications.

    我们为捆绑通知和单一通知创建了单独的渠道。
  7. onNewIntent is triggered on Notification click. It gets the notification id from the intent data and cancels the respective notification.

    在通知单击时触发onNewIntent 。 它从意图数据中获取通知ID,并取消相应的通知。

Android捆绑通知应用程序输出 (Android Bundled Notifications App Output)

Let’s see the output from the above code.

android bundled notifications app output

让我们看看上面代码的输出。

Do note that in the above output, clicking any notification cancels only the last notification added.

请注意,在上面的输出中,单击任何通知只会取消最后添加的通知。

Why?

为什么?

Because PendingIntent updates the data to the latest and we’re using request code as 0 for each of the PendingIntents. So it returns the latest data only.

由于PendingIntent将数据更新为最新数据,因此我们将每个PendingIntent的请求代码都设为0。 因此,它仅返回最新数据。

We need to set a different request code for each notification.

我们需要为每个通知设置不同的请求代码。

Let’s set the request code as bundleNotificationId for bundle notifications and singleNotificationId for the single ones.

让我们将请求代码设置为bundleNotificationId和单个消息的singleNotificationId

@Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnBundleNotification:


                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                    NotificationChannel groupChannel = new NotificationChannel("bundle_channel_id", "bundle_channel_name", NotificationManager.IMPORTANCE_LOW);
                    notificationManager.createNotificationChannel(groupChannel);
                }
                bundleNotificationId += 100;
                singleNotificationId = bundleNotificationId;
                String bundle_notification_id = "bundle_notification_" + bundleNotificationId;
                Intent resultIntent = new Intent(this, MainActivity.class);
                resultIntent.putExtra("notification", "Summary Notification Clicked");
                resultIntent.putExtra("notification_id", bundleNotificationId);
                resultIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                PendingIntent resultPendingIntent = PendingIntent.getActivity(this, bundleNotificationId, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);


                summaryNotificationBuilder = new NotificationCompat.Builder(this, "bundle_channel_id")
                        .setGroup(bundle_notification_id)
                        .setGroupSummary(true)
                        .setContentTitle("Bundled Notification. " + bundleNotificationId)
                        .setContentText("Content Text for bundle notification")
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setContentIntent(resultPendingIntent);

                notificationManager.notify(bundleNotificationId, summaryNotificationBuilder.build());

                break;

            case R.id.btnSingleNotification:


                bundle_notification_id = "bundle_notification_" + bundleNotificationId;

                resultIntent = new Intent(this, MainActivity.class);
                resultIntent.putExtra("notification", "Summary Notification Clicked");
                resultIntent.putExtra("notification_id", bundleNotificationId);
                resultIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                resultPendingIntent = PendingIntent.getActivity(this, bundleNotificationId, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);

                //We need to update the bundle notification every time a new notification comes up.
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                    if (notificationManager.getNotificationChannels().size() < 2) {
                        NotificationChannel groupChannel = new NotificationChannel("bundle_channel_id", "bundle_channel_name", NotificationManager.IMPORTANCE_LOW);
                        notificationManager.createNotificationChannel(groupChannel);
                        NotificationChannel channel = new NotificationChannel("channel_id", "channel_name", NotificationManager.IMPORTANCE_DEFAULT);
                        notificationManager.createNotificationChannel(channel);
                    }
                }
                summaryNotificationBuilder = new NotificationCompat.Builder(this, "bundle_channel_id")
                        .setGroup(bundle_notification_id)
                        .setGroupSummary(true)
                        .setContentTitle("Bundled Notification " + bundleNotificationId)
                        .setContentText("Content Text for group summary")
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setContentIntent(resultPendingIntent);


                if (singleNotificationId == bundleNotificationId)
                    singleNotificationId = bundleNotificationId + 1;
                else
                    singleNotificationId++;

                resultIntent = new Intent(this, MainActivity.class);
                resultIntent.putExtra("notification", "Single notification clicked");
                resultIntent.putExtra("notification_id", singleNotificationId);
                resultIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                resultPendingIntent = PendingIntent.getActivity(this, singleNotificationId, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT); //singleNotificationId is set as the request code.


                NotificationCompat.Builder notification = new NotificationCompat.Builder(this, "channel_id")
                        .setGroup(bundle_notification_id)
                        .setContentTitle("New Notification " + singleNotificationId)
                        .setContentText("Content for the notification")
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setGroupSummary(false)
                        .setContentIntent(resultPendingIntent);

                notificationManager.notify(singleNotificationId, notification.build());
                notificationManager.notify(bundleNotificationId, summaryNotificationBuilder.build());
                break;

        }
    }

Let’s see the output now.

android bundled notifications example

现在来看输出。

Works!. This brings an end to android bundled notifications tutorial. You can download the Android BundledNotificationsExample Project from the link below.

作品!。 这结束了android捆绑通知教程。 您可以从下面的链接下载Android BundledNotificationsExample项目。

翻译自: https://www.journaldev.com/19382/android-bundled-notifications

android捆绑demo

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值