在实时android中读取传入的通知

时间:2017-07-31 15:31:32

标签: android notifications broadcastreceiver broadcast android-broadcast

我试图在文本视图中阅读所有传入通知...

我希望看起来像这样

我找到了一些代码,但所有代码都混淆了并且不起作用,任何帮助都将非常感激。

enter image description here

1 个答案:

答案 0 :(得分:2)

它适用于:Android 4.3(JELLY_BEAN_MR2)。

  1. 添加到您的清单新权限android.permission.BIND_NOTIFICATION_LISTENER_SERVICE

  2. 创建NotificationListenerService类并添加到清单中 来自Google Developer:

  3.   

    NotificationListenerService必须要求,以确保这一点   只有系统可以绑定它。

    的AndroidManifest.xml:

    <service android:name=".NotificationListener"
             android:label="@string/service_name"
          android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
        <intent-filter>
            <action android:name="android.service.notification.NotificationListenerService" />
        </intent-filter>
    </service>
    
    1. 覆盖onNotificationPosted()
    2. NotificationListenerService类:

      @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
      public class NotificationListenerService extends NotificationListenerService {
      
      @Override
      public void onNotificationPosted(final StatusBarNotification sbn) {
          if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
      // Here you need to play with the sbn object and get the data that you want from it.
      
              //sbn.getPackageName()
              Notification notification = sbn.getNotification();
              Bundle extras = null;
              if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                  extras = notification.extras;
              }
      
              if (extras != null) {
                  extras.get("android.title");
              }
          }
      }
      
          @Override
          public void onNotificationRemoved(StatusBarNotification sbn) {
          }
      
          @Override
          @TargetApi(Build.VERSION_CODES.N)
          public void onListenerDisconnected() {
              if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                  // Notification listener disconnected - requesting rebind
                  requestRebind(new ComponentName(this, NotificationListenerService2.class));
              }
          }
      }
      

      开发人员参考:https://developer.android.com/reference/android/service/notification/NotificationListenerService.html

      实施的简单示例应用程序:https://github.com/kpbird/NotificationListenerService-Example/