通过继承 NotificationListenerService实现, 它允许应用程序在创建或删除时接收有关通知的信息。
class MyNotificationListenerService : NotificationListenerService() {
private val pkgName = this.javaClass.name
/**
* 接收任何到通知
* @param sbn StatusBarNotification
*/
override fun onNotificationPosted(sbn: StatusBarNotification?) {
val extras = sbn?.notification?.extras
extras?.let {
val title = it.getString(NotificationCompat.EXTRA_TITLE, "")
val content = it.getString(NotificationCompat.EXTRA_TEXT, "")
Log.d(pkgName, "**********************")
Log.d(pkgName, "包名:${sbn.packageName}")
Log.d(pkgName, "标题:$title")
Log.d(pkgName, "内容:$content")
Log.d(pkgName, "**********************")
}
}
/**
* 首次连接
*/
override fun onListenerConnected() {
super.onListenerConnected()
}
}
在清单文件声明service,并声明权限和优先级
<service
android:name=".service.MyNotificationListenerService"
android:exported="true"
android:label="@string/app_name"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter android:priority="1000">
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>