Android notification bar micro skills, adaptation of notification bar in 8.0 system

Please indicate the source for reprinting: https://blog.csdn.net/guolin_blog/article/details/79854070

Hello everyone, today we will continue to learn the adaptation of the Android 8.0 system.

As we have mentioned before, there are two main places where the Android 8.0 system needs to be adapted: the application icon and the notification bar. In the previous article, we learned about the adaptation of Android 8.0 system application icons. Friends who have not read this article can read the Android application icon micro-tips first, the adaptation of application icons in the 8.0 system .

So in this article, we will naturally focus on the notification bar and learn about the notification bar adaptation of the Android 8.0 system.

In fact, before the 8.0 system, there was another version with a relatively large change in the notification bar, which was the 5.0 system. Regarding the content that the 5.0 system needs to adapt to the notification bar, I have also compiled an article. Interested friends can read the Android notification bar micro-tips, those small details that you have not paid attention to .

So let's get to the point of this article.


Why do you need notification bar adaptation?

I have to say, the notification bar is really a love-hate thing.

The notification bar is an original feature of the Android system. Although Jobs always believed that the Android system was a product that completely copied iOS, the notification bar was indeed original to the Android system. On the contrary, Apple also added a similar notification bar function after iOS 5. .

The design of the notification bar is really ingenious. It does not take up any space by default. Only when the user needs to swipe down on the status bar, the content of the notification bar will be displayed. This is extremely early in the development of smartphones. Dadi solves the problem that the screen of the mobile phone is too small and the content display area is insufficient.

But as smartphones have matured, the notification bar has become less and less likable. Each app hopes to seize the space of the notification bar to promote and promote its products as much as possible. Now I often wake up in the morning and pick up my mobile phone to look at it, and the notification bar is full of pushes from various apps, which is very annoying.

Although I am an Android application developer, I am also an experienced user of Android phones. I've been using an Android phone for 8 years and currently I have zero tolerance for this kind of spam in the notification bar. Now whenever I install a new app, I will first go to the settings to find out if there is a push switch. If there is, I will turn it off as soon as possible. And if an app often pushes spam to me but cannot be closed, I will directly turn off its notification master switch. If it is not an important app, then I may directly uninstall it.

Why is a great notification bar feature now so annoying to users? A large part of the reason is because developers use it without restraint. It's like keeping the app alive. Even today, people keep asking me how to keep the app alive. Just imagine how everyone can keep their app alive. Who is the ultimate victim? Not yet a user of an Android phone. Everyone's mobile phones will only get more and more stuck, and finally they just want to throw away their phones and become iPhone users. It is also because of the uncontrolled use of developers that each version of Android will continue to shrink background permissions.

The same goes back to the notification bar. Every developer just wants to promote their app as much as possible. In the end, the user's mobile phone is like a chicken coop. But the notification bar is still useful. For example, when we receive messages such as WeChat and SMS, we really need the notification bar to remind us. Therefore, after analysis, the biggest problem of the notification bar is that it cannot allow users to distinguish between interesting and uninteresting messages. For example, I want Taobao to send me news about the seller's shipping and logistics, but I don't want to receive news about discounts or asking me to buy clothes. So for now, there is no way to distinguish these messages, I either agree to accept all messages or block all messages, which is the current pain point of the notification bar.

So in the Android 8.0 system, Google also started from this pain point.

8.0 system notification bar adaptation

Starting with the Android 8.0 system, Google introduced the concept of notification channels.

What is the notification channel? As the name implies, each notification must belong to a corresponding channel. Each app can freely create which notification channels the current app has, but the control of these notification channels is in the hands of the user. Users can freely choose the importance of these notification channels, whether to ring, whether to vibrate, or whether to turn off notifications for this channel.

With these controls, users no longer have to fear the interruption of those spam push messages, because users can choose which notifications they care about and which ones they don't care about. To give a specific example, I hope to receive payment information from Alipay immediately, because I don’t want to miss any income, but I don’t want to receive the food around me that Alipay recommends to me, because I have no money and can only afford the company canteen. In this case, Alipay can create two notification channels, one for income and expenditure, and one for recommendation. As a user, I am not interested in recommendation notifications, so I can directly close the recommendation notification channel, which will not affect my concerns. Notifications, and don't let those notifications that I don't care about bother me.

For each app, the division of notification channels needs to be carefully considered, because once a notification channel is created, it cannot be modified. Therefore, developers need to carefully analyze the types of notifications in their app before creating them. corresponding notification channels. Here we refer to Twitter's notification channel division:

It can be seen that Twitter divides the notification channels in great detail according to its own notification type, so that the user's self-selectivity is relatively high, which greatly reduces the harassment of the user's spam notification and uninstalls the app. probability.


Do I have to fit in?

This time, Google's attitude towards the promotion of the 8.0 system notification channel is still relatively tough.

First of all, if you upgrade the appcompat library, all places where the appcompat library is used to build notifications will be deprecated method hints, as follows:

The image above tells us that this method is deprecated and requires the use of a method with a notification channel.

Of course, Google has not completely done it. Even if the method is marked as abandoned, it can still be used normally. However, if you specify the targetSdkVersion in the project to 26 or higher, then the Android system will think that your app has been adapted to the 8.0 system, including the adaptation of the notification bar of course. If the notification channel is not used at this time, the notification of your app will not be able to pop up at all. So here's my advice to you, be sure to adapt.

Well, I have introduced so much background knowledge to you, so now we will officially enter the topic and learn how to adapt the notification bar in the 8.0 system.

Create a notification channel

First, we use Android Studio to create a new project, let's call it NotificationTest.

After creating the project, open the app/build.gradle file and check that the targetSdkVersion has been specified to 26 or higher, as shown below:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.example.notificationtest"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
}

As you can see, when I create a new project, the default targetSdkVersion is 26. If you are lower than 26, it means that your Android SDK is a bit old, and it is best to update it. Of course, it doesn't matter if you are too lazy to update, you can manually change it to 26.

Next, modify the code in MainActivity as follows:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String channelId = "chat";
            String channelName = "聊天消息";
            int importance = NotificationManager.IMPORTANCE_HIGH;
            createNotificationChannel(channelId, channelName, importance);

            channelId = "subscribe";
            channelName = "订阅消息";
            importance = NotificationManager.IMPORTANCE_DEFAULT;
            createNotificationChannel(channelId, channelName, importance);
        }
    }


    @TargetApi(Build.VERSION_CODES.O)
    private void createNotificationChannel(String channelId, String channelName, int importance) {
        NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
        NotificationManager notificationManager = (NotificationManager) getSystemService(
                NOTIFICATION_SERVICE);
        notificationManager.createNotificationChannel(channel);
    }
}

The code is not long, let me explain briefly. Here we have created two notification channels in MainActivity. The first thing to ensure is that the system version of the current mobile phone must be Android 8.0 or higher, because the lower version of the mobile phone system does not have the function of notification channels, so if you do not check the system version Will crash on lower version phones.

The way to create a notification channel is very simple. Here I encapsulate a createNotificationChannel() method. The logic inside is believed to be understood by everyone. It should be noted that creating a notification channel requires at least three parameters: channel ID, channel name, and importance level. The channel ID can be freely defined, as long as the global uniqueness is guaranteed. The channel name is for users to see, and it needs to be able to clearly express the purpose of the channel. The difference in the importance level will determine the different behaviors of the notification. Of course, this is only the importance level in the initial state. The user can manually change the importance level of a channel at any time, and the App cannot intervene.

The above code I simulated such a scenario. Imagine that we are developing an App similar to WeChat, in which App notifications can be mainly divided into two categories, one is the chat messages between me and others, these kinds of messages are very important, so I set the importance level to IMPORTANCE_HIGH. The other type is the subscription message of the official account. This kind of message is not so important, so I set the importance level to IMPORTANCE_DEFAULT. In addition, the importance level can also be set to IMPORTANCE_LOW and IMPORTANCE_MIN, which correspond to lower notification importance levels respectively.

Now you can run the code. After the operation is successful, we close the App, go to Settings -> Apps -> Notifications, and view the notification interface of the NotificationTest App, as shown in the following figure:

The two notification channels we just created are displayed here. It can be seen that due to the different importance levels of the two notification channels, the notification behaviors are also different. Chat messages can sound and pop up notifications on the screen, while subscription messages can only sound a sound.

Of course, the user can also click to make any modification to the notification channel, such as lowering the importance level of the chat message, or even completely closing the notification of the channel.

As for this part of the code for creating the notification channel, you can write it in MainActivity, or in the Application. In fact, you can write it anywhere in the program, as long as it is called before the notification pops up. And the code for creating a notification channel will only be created when it is executed for the first time. After each execution of the creation code, the system will detect that the notification channel already exists, so it will not be created repeatedly and will not affect any efficiency.


Make notifications show up

The code that triggers the notification is basically the same as the previous version, but when constructing the notification object, you need to pass in an additional notification channel ID to indicate which channel the notification belongs to.

Then let's make the notification show up.

First modify the code in activity_main.xml as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="发送聊天消息"
        android:onClick="sendChatMsg"
        />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="发送订阅消息"
        android:onClick="sendSubscribeMsg"
        />
</LinearLayout>

Here we have added two buttons to the layout file. Obviously, one is used to trigger the notification of the chat message channel, and the other is used to trigger the notification of the subscription message channel.

Next, modify the code in MainActivity as follows:

public class MainActivity extends AppCompatActivity {

    ...

    public void sendChatMsg(View view) {
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Notification notification = new NotificationCompat.Builder(this, "chat")
                .setContentTitle("收到一条聊天消息")
                .setContentText("今天中午吃什么?")
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.drawable.icon)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.icon))
                .setAutoCancel(true)
                .build();
        manager.notify(1, notification);
    }

    public void sendSubscribeMsg(View view) {
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Notification notification = new NotificationCompat.Builder(this, "subscribe")
                .setContentTitle("收到一条订阅消息")
                .setContentText("地铁沿线30万商铺抢购中!")
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.drawable.icon)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.icon))
                .setAutoCancel(true)
                .build();
        manager.notify(2, notification);
    }
}

Here we trigger two notifications in the sendChatMsg() and sendSubscribeMsg() methods respectively. The code for creating the notification will not be explained any more. A notification channel ID, then here we pass in the two just created channel IDs, chat and subscribe.

Now re-run the code and click the send chat message button, the effect is as shown below:

Since this is a high-level notification, this screen popup is used to notify the user that news is coming. Then we can pull down and expand the notification bar, where we can also view the details of the notification:

Users can dismiss this notification by swiping left or right quickly.

Next, click the Send Subscription Message button, and you will find that there will not be a notification reminder popping up on the screen now, only a small notification icon will be displayed on the status bar:

Because the severity level of the subscription message notification is the default level, this is how the default level notification is displayed. Of course, we can still pull down and expand the notification bar to view the details of the notification:

However, the above demonstrations are all traditional functions of the notification bar. Next, let's take a look at the unique functions of the notification bar in the Android 8.0 system.

As mentioned, a quick swipe left or right will dismiss a notification, but if you swipe left or right slowly, you'll see these two buttons:

Among them, the button of the clock icon on the left can delay the display of notifications. For example, this is a relatively important notification, but I don't have time to read it right now, and I don't want it to be constantly displayed in the status bar to bother me, so I can delay it for a while, so that I can temporarily focus on it first. Focus on things, wait until there will be time this notification will show up again, I will not miss any information. As follows:

The button with the setting icon on the right can be used to block and configure the notification channels. Users have absolute control over each notification channel of each App, and can configure and modify them according to their own preferences. As follows:

For example, I feel that it is too annoying that the subscribed message always recommends advertisements to me, so I can close the notification channel of the subscribed message. In this way, I will not receive any messages under this notification channel in the future, and the chat messages will not be affected. This is the biggest feature of the 8.0 system notification channel.

In addition, click on all categories in the above picture to enter the complete settings interface of the current application notification.


Manage notification channels

We have already learned in the previous content that once a notification channel is created, it cannot be modified through code. If it can't be modified, how can it be managed? To this end, Android gives developers the permission to read the notification channel configuration. If a certain function of ours can only be used by configuring the notification channel according to the specified requirements, then the user can be prompted to manually change the notification channel configuration.

It is not easy to understand only by talking about concepts. Let's learn it through specific examples. Thinking that we are developing an app similar to WeChat, chat messages are very important. If the user accidentally turns off the notification channel of chat messages, wouldn't all important information be lost? To this end, we must ensure that the user has opened the notification channel of the chat message.

Modify the code in MainActivity as follows:

public class MainActivity extends AppCompatActivity {

    ...

    public void sendChatMsg(View view) {
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = manager.getNotificationChannel("chat");
            if (channel.getImportance() == NotificationManager.IMPORTANCE_NONE) {
                Intent intent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS);
                intent.putExtra(Settings.EXTRA_APP_PACKAGE, getPackageName());
                intent.putExtra(Settings.EXTRA_CHANNEL_ID, channel.getId());
                startActivity(intent);
                Toast.makeText(this, "请手动将通知打开", Toast.LENGTH_SHORT).show();
            }
        }

        Notification notification = new NotificationCompat.Builder(this, "chat")
                ...
                .build();
        manager.notify(1, notification);
    }

    ...

}

Here we have modified the sendChatMsg() method, obtained the NotificationChannel object through the getNotificationChannel() method, and then can read all the configurations under the notification channel. Here we judge that if the importance of the notification channel is equal to IMPORTANCE_NONE, it means that the user has closed the notification of the channel, and then it will jump to the notification setting interface to remind the user to manually open it.

Now re-run the program, the effect is as shown below:

It can be seen that when we close the notification channel of the chat message, the next time we send the chat message again, it will directly jump to the notification setting interface, reminding the user to manually turn on the notification.

In addition to the above methods of managing notification channels, Android 8.0 also gives us the ability to delete notification channels, just use the following code to delete:

NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.deleteNotificationChannel(channelId);

But this feature is highly not recommended for everyone to use. Because Google will display the number of all deleted notification channels in the notification settings interface in order to prevent applications from randomly creating spam notification channels, as shown in the following figure:

This is very unsightly, so the best thing for developers to do is to carefully plan the notification channel, and not to use the delete function lightly.


Show unread banners

As we mentioned earlier, Apple only introduced the notification bar function from iOS 5, so before iOS 5, how did the iPhone perform message notifications? The unread corner mark function is used, and the effect is as follows:

In fact, the Android system has never provided this kind of corner label function similar to iOS before, but since many domestic mobile phone manufacturers like to follow the trend of iOS, various domestic mobile phone ROMs have launched their own corner label functions.

However, although domestic mobile phone manufacturers can customize ROMs, they do not have the ability to formulate APIs. Therefore, for a long time, there has not been a standard API to realize the corner mark function. Many mobile phone manufacturers have to send broadcasts to the system. The broadcast standards are inconsistent, often resulting in extremely mixed code.

The good news is that starting from the 8.0 system, Google has formulated the corner mark specification on the Android system and also provided a standard API. This problem that has long been a headache for developers can now finally be solved.

So let's learn how to achieve the effect of unread corners on the Android system.

Modify the code in MainActivity as follows:

public class MainActivity extends AppCompatActivity {

    ...

    @TargetApi(Build.VERSION_CODES.O)
    private void createNotificationChannel(String channelId, String channelName, int importance) {
        NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
        channel.setShowBadge(true);
        NotificationManager notificationManager = (NotificationManager) getSystemService(
                NOTIFICATION_SERVICE);
        notificationManager.createNotificationChannel(channel);
    }

    public void sendSubscribeMsg(View view) {
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Notification notification = new NotificationCompat.Builder(this, "subscribe")
                ...
                .setNumber(2)
                .build();
        manager.notify(2, notification);
    }
}

As you can see, we have mainly modified two places here. The first is when the notification channel is created, the setShowBadge(true) method of NotificationChannel is called, indicating that the notification under this channel is allowed to display the badge. The second is when the notification is created, the setNumber() method is called, and the number of unread messages is passed in.

Now re-run the program and click the send subscription message button, then find the NotificationTest application in the Launcher, as shown below:

It can be seen that there is a green corner mark in the upper right corner of the icon, indicating that the function of the corner mark we wrote has taken effect.

It should be noted that even if we don't call the setShowBadge(true) method, the Android system will display the corner label by default, but if you want to disable the corner label function, remember to call the setShowBadge(false) method.

But why isn't the unread count displayed? This function also requires us to long press the icon, the effect is as shown below:

This way you can see that the number of unread notifications is 2.

Maybe some friends are accustomed to the unread corner icon on iOS, and feel that the long-press method on Android is very troublesome. There is no way to do this, because after all, this is the native Android system, and Google has no way to imitate iOS as recklessly as domestic mobile phone manufacturers, or it may suffer a lawsuit. But I believe that domestic mobile phone manufacturers will definitely customize this part of the function, and the style should be similar to iOS. But this is not important. For our developers, the best news is to have a unified API standard. No matter how domestic mobile phone manufacturers customize ROM in the future, they will be customized according to this API standard. We only need to use this API to Just do programming.

Okay, the last two articles about the Android 8.0 system adaptation are over here, thank you for reading.

Click here to download the sample source code in the article .

Pay attention to my technical public account, and there are high-quality technical articles pushed every day. Pay attention to my entertainment public account, and relax when you are tired from work and study.

Scan the QR code below on WeChat to follow:

        

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324514178&siteId=291194637