我想创建一个外部通知LED。我能处理电话和微控制器之间的电子和无线通信。但是,我不知道如何检测是否有可用的通知。也许是NotificationListenerService?
发布于 2015-07-15 16:18:55
是的,最好的方法是使用NotificationListenerService.它是在Android4.3中引入的,在Android4.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
您必须从用户那里授权。可以在设置-> Security -> Notification 中找到它
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);
https://stackoverflow.com/questions/31433521
复制相似问题