通过监听通知栏的消息,获取其他应用的一些消息
1.创建继承NotificationListenerService的类
class NotificationListener : NotificationListenerService() {
private lateinit var mListener: messageListener
companion object {
private const val TAG = "NotificationListener"
private const val LISTEN_CALL = "com.android.incallui"
private const val LISTEN_TIM = "com.tencent.tim"
}
override fun onNotificationPosted(sbn: StatusBarNotification?) {
super.onNotificationPosted(sbn)
when (sbn?.packageName) {
LISTEN_CALL -> Log.d(TAG, "收到电话消息")
LISTEN_TIM -> Log.d(TAG, "收到TIM消息")
else -> Log.d(TAG, "收到未知类型消息")
}
}
override fun onNotificationRemoved(sbn: StatusBarNotification?) {
super.onNotificationRemoved(sbn)
when (sbn?.packageName) {
LISTEN_CALL -> Log.d(TAG, "移除电话消息")
LISTEN_TIM -> Log.d(TAG, "移除TIM消息")
else -> Log.d(TAG, "移除未知类型消息")
}
}
override fun onListenerConnected() {
super.onListenerConnected()
Log.d(TAG, "建立监听连接")
}
override fun onListenerDisconnected() {
super.onListenerDisconnected()
Log.d(TAG, "监听连接断开")
}
}
AndroidManifest.xml:
<service
android:name=".NotificationListener"
android:enabled="true"
android:exported="true"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
2.启用NotificationService
try {
val intent = Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS")
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
} catch (e: Exception) {
e.printStackTrace()
}
3.获取标准文本信息
if (sbn.getNotification().tickerText != null) {
Log.d(TAG, sbn.getNotification().tickerText.toString())//标题和内容一起程序,eg:小明:今天去打球吗?
}
//或
val extras = sbn.notification.extras
if (extras != null) {
// 获取通知标题
val title = extras.getString(Notification.EXTRA_TITLE, "")//eg:小明
Log.d(TAG, title)
// 获取通知内容
val content = extras.getString(Notification.EXTRA_TEXT, "")//eg:今天去打球吗?
Log.d(TAG,content)
}