logo头像
Snippet 博客主题

android 监听通知消息

android 监听通知消息

1
2
3
4
监听通知消息 系统权限 
开启权限 跳转系统设置

startActivity(new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"));

NotificationListenerService 监听

创建 NotificationListenerService的监听

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class NotificationMonitorService extends NotificationListenerService {

// 在收到消息时触发
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
// TODO Auto-generated method stub
Bundle extras = sbn.getNotification().extras;
// 获取接收消息APP的包名
String notificationPkg = sbn.getPackageName();
// 获取接收消息的抬头
String notificationTitle = extras.getString(Notification.EXTRA_TITLE);
// 获取接收消息的内容
String notificationText = extras.getString(Notification.EXTRA_TEXT);
Log.i("XSL_Test", "Notification posted " + notificationTitle + " & " + notificationText);
}

// 在删除消息时触发
@Override
public void onNotificationRemoved(StatusBarNotification sbn) {
// TODO Auto-generated method stub
Bundle extras = sbn.getNotification().extras;
// 获取接收消息APP的包名
String notificationPkg = sbn.getPackageName();
// 获取接收消息的抬头
String notificationTitle = extras.getString(Notification.EXTRA_TITLE);
// 获取接收消息的内容
String notificationText = extras.getString(Notification.EXTRA_TEXT);
Log.i("XSL_Test", "Notification removed " + notificationTitle + " & " + notificationText);
}
}

AndroidManifest.xml 中添加配置

1
2
3
4
5
6
7
 <service android:name=".NotificationMonitorService" 
android:label="NotificationMonitor"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>

开启权限 监听

1
2
3
4
5
6
7

if (!isEnabled()) {
startActivity(new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"));
} else {
Toast toast = Toast.makeText(getApplicationContext(), "监控器开关已打开", Toast.LENGTH_SHORT);
toast.show();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

// 判断是否打开了通知监听权限
private boolean isEnabled() {
String pkgName = getPackageName();
final String flat = Settings.Secure.getString(getContentResolver(), "enabled_notification_listeners");
if (!TextUtils.isEmpty(flat)) {
final String[] names = flat.split(":");
for (int i = 0; i < names.length; i++) {
final ComponentName cn = ComponentName.unflattenFromString(names[i]);
if (cn != null) {
if (TextUtils.equals(pkgName, cn.getPackageName())) {
return true;
}
}
}
}
return false;
}
支付宝打赏 微信打赏

打赏