获取通知时获取

时间:2015-07-15 14:41:22

标签: android

我想创建一个外部通知LED。我可以轻松处理Phone和Micro控制器之间的电子和无线通信。但是,我不确定如何检测何时有可用的通知。也许是NotificationListenerService?

1 个答案:

答案 0 :(得分:3)

是的,最好的方法是使用 NotificationListenerService 。它是在Android 4.3中引入的,它在Android 4.4中有很多新功能得到了很大改进。你应该使用它。

我将尽力帮助您提供有关如何使用它的简短教程。

如何使用

第1步

首先需要扩展NotificationListenerService类并实现其方法。

public class SimpleKitkatNotificationListener extends NotificationListenerService {

        @Override
        public void onNotificationPosted(StatusBarNotification sbn) {
              //..............
        }

        @Override
        public void onNotificationRemoved(StatusBarNotification sbn) {
              //.............. 
        }
}

第2步

然后,您必须使用BIND_NOTIFICATION_LISTENER_SERVICE权限在清单文件中声明服务,并包含一个带有SERVICE_INTERFACE操作的意图过滤器。

<service
      android:name="it.gmariotti.android.examples.
            notificationlistener.SimpleKitkatNotificationListener"
      android:label="@string/service_name"
      android:debuggable="true"
      android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE" >
      <intent-filter>
           <action android:name="android.service.
                 notification.NotificationListenerService" ></action>
      </intent-filter>

 </service>

第3步

您必须向用户授权。您可以在设置 - &gt;中找到它。安全 - &gt;通知访问

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

第4步

使用extras字段获取您想要的任何信息,

Notification mNotification=sbn.getNotification();
   Bundle extras = mNotification.extras;

你可以从这个课程中获得很多信息,

/**
     * {@link #extras} key: this is the title of the notification,
     * as supplied to {@link Builder#setContentTitle(CharSequence)}.
     */
    public static final String EXTRA_TITLE = "android.title";

    /**
     * {@link #extras} key: this is the main text payload, as supplied to
     * {@link Builder#setContentText(CharSequence)}.
     */
    public static final String EXTRA_TEXT = "android.text";

    /**
     * {@link #extras} key: this is a third line of text, as supplied to
     * {@link Builder#setSubText(CharSequence)}.
     */
    public static final String EXTRA_SUB_TEXT = "android.subText";

    /**
     * {@link #extras} key: this is a bitmap to be used instead of the small icon when showing the
     * notification payload, as
     * supplied to {@link Builder#setLargeIcon(android.graphics.Bitmap)}.
     */
    public static final String EXTRA_LARGE_ICON = "android.largeIcon";

第5步

您可以轻松获取此类数据,

String notificationTitle = extras.getString(Notification.EXTRA_TITLE);
     int notificationIcon = extras.getInt(Notification.EXTRA_SMALL_ICON);
     Bitmap notificationLargeIcon = 
                  ((Bitmap) extras.getParcelable(Notification.EXTRA_LARGE_ICON));
     CharSequence notificationText = extras.getCharSequence(Notification.EXTRA_TEXT);
     CharSequence notificationSubText = extras.getCharSequence(Notification.EXTRA_SUB_TEXT);