1. 服务代码
@SuppressLint("NewApi")
public class NotificationMonitorService extends NotificationListenerService {
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
Bundle extras = sbn.getNotification().extras;
String notificationPkg = sbn.getPackageName();
String notificationTitle = extras.getString(Notification.EXTRA_TITLE);
String notificationText = extras.getString(Notification.EXTRA_TEXT);
if (notificationPkg.equals("com.faxuan.zjb")) {
Log.i("XSL_Test", "Notification posted 我是站特们加勒比杰斯们");
}
Log.i("XSL_Test", "Notification posted " + notificationTitle + " & " + notificationText+"_"+notificationPkg);
}
@Override
public void onNotificationRemoved(StatusBarNotification sbn) {
Bundle extras = sbn.getNotification().extras;
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);
}
}
2. 使用方式
public class NotificationUtil {
private static NotificationUtil intance;
private Context context;
private NotificationUtil(Context context) {
this.context = context.getApplicationContext();
}
public static NotificationUtil getIntance(Context context) {
if (intance == null) {
synchronized (NotificationUtil.class) {
intance = new NotificationUtil(context);
}
}
return intance;
}
public boolean isEnabled() {
String pkgName = context.getPackageName();
final String flat = Settings.Secure.getString(context.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;
}
}
3.调用
// //1, // if (!NotificationUtil.getIntance(this).isEnabled()) { // startActivity(new Intent(“android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS”)); // } // //2. // <service android:name=“com.faxuan.zjb.api.NotificationMonitorService” // android:label=“NotificationMonitor” // android:permission=“android.permission.BIND_NOTIFICATION_LISTENER_SERVICE”> // // // //
|