Use of NotificationListenerService for Android notification monitoring service

foreword

In this article, we will introduce how to use NotificationListenerService to implement functions such as smart watch notification synchronization and WeChat automatic red envelope grabbing. The principle of realizing these functions is actually to monitor the notification service of the system. Next, let's see how to realize it.

Use of NotificationListenerService

Create NotificationListenerService

In Android, if we want to monitor system notifications, we need to implement a service that inherits from NotificationListenerService and create a new NotificationMonitorService class. The code is as follows.

class NotificationMonitorService : NotificationListenerService() {
    //收到通知时的回调
    override fun onNotificationPosted(sbn: StatusBarNotification) {
        super.onNotificationPosted(sbn)
    }

    //通知移除时的回调
    override fun onNotificationRemoved(sbn: StatusBarNotification?) {
        super.onNotificationRemoved(sbn)
    }
}

Here we rewrite the onNotificationPosted method and the onNotificationRemoved method, which will be called when the notification is received and when the notification is removed, respectively. Here we focus on the onNotificationPosted method.

There is a StatusBarNotification instance in the onNotificationPosted method, through which we can obtain the package name, content, etc. of the notification message. The code is shown below.

class NotificationMonitorService : NotificationListenerService() {
    override fun onNotificationPosted(sbn: StatusBarNotification) {
        super.onNotificationPosted(sbn)
        val extras = sbn.notification.extras
        // 获取接收消息APP的包名
        val notificationPkg = sbn.packageName
        // 获取接收消息的抬头
        val notificationTitle = extras.getString(Notification.EXTRA_TITLE)
        // 获取接收消息的内容
        val notificationText = extras.getString(Notification.EXTRA_TEXT)
        Log.d("收到的消息内容包名:", notificationPkg)
        Log.d("收到的消息内容", "Notification posted $notificationTitle & $notificationText")
    }
}

Then remember to add the declaration of this Service in the configuration file, the code is as follows.

<service android:name="com.example.myapplication.NotificationMonitorService"
    android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE"
    android:exported="true">
    <intent-filter>
        <action android:name="android.service.notification.NotificationListenerService" />
    </intent-filter>
</service>

After creating the NotificationMonitorService, we can start the service next.

start service

Now start the service directly, there is definitely no way to monitor the system notification. Before starting the service, we should grant the app the permission to monitor the system notification.

Add permission in AndroidManifest.xml, the code is as follows.

 <uses-permission android:name="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE"/>

Before starting the service, determine whether the permission to monitor notifications is enabled. If not, jump to the settings page to enable it. The code is as follows.

if (NotificationManagerCompat.getEnabledListenerPackages(this).contains(packageName)){
    val intent = Intent(this,NotificationMonitorService::class.java)
    startService(intent)
 }else{
    startActivity(Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"))
 }

If it is not enabled, the jump to the setting page is as follows.

Enable the monitoring notification permission, run the program, and print the log as shown below.

 The corresponding print log is that I received a group chat message from WeChat and sent a "strong".

When a message such as a text message or an incoming call is received, the system will also send a notification, and we can handle different businesses according to the received notification. Interested readers here can try it themselves. Next, let's simulate the function of automatically grabbing red envelopes.

Realize the function of automatically grabbing red envelopes

For testing purposes, my wife sent me a 0.01 red envelope after going through all kinds of hardships. The content we listened to was "[WeChat red envelope] Gong Xi Fa Cai, good luck". As shown below.

 Therefore, when we receive a message, we can judge whether we have received a WeChat red packet by monitoring the WeChat package name and the content of the message to handle specific operations. (Do not deal with it, others deliberately send the same text).

if (notificationPkg.equals("com.tencent.mm")){
   if (notificationText.equals("[微信红包]恭喜发财,大吉大利")){
      //收到微信红包了
   }
}

In this way, we only need to handle the next operation at the code. In fact, our operation is also very simple. We only need to open the corresponding WeChat page when there is a red envelope detected. The code is as follows.

class NotificationMonitorService : NotificationListenerService() {
    override fun onNotificationPosted(sbn: StatusBarNotification) {
        super.onNotificationPosted(sbn)
        val extras = sbn.notification.extras
        // 获取接收消息APP的包名
        val notificationPkg = sbn.packageName
        // 获取接收消息的内容
        val notificationText = extras.getString(Notification.EXTRA_TEXT)
        if (notificationPkg.equals("com.tencent.mm")){
            if (notificationText.equals("[微信红包]恭喜发财,大吉大利")){
                //收到微信红包了
                val intent = sbn.notification.contentIntent
                intent.send()
            }
        }
    }
}

Here we get the intent of notification directly through sbn, just perform the intent.send operation, run the program, and after receiving the red envelope, the page will automatically jump to the WeChat red envelope page, and the result is shown in the figure below.

write at the end

Using the function of notification monitoring service, we can realize many functions such as message synchronization of smart watches, grabbing red envelopes on WeChat, etc. If you need it, you can also let your girlfriend's message pop up immediately, so that you no longer have to kneel on the washboard la~

In the next article, we will focus on digging into the principle of the monitoring notification service, see you in the next article~

Guess you like

Origin blog.csdn.net/huangliniqng/article/details/127649466