我正在寻找一种能够从通知对象中检索ContentText的方法。如下所示:
NotificaionCompat.Builder builder;
Notification existing;
builder.setContentText(existing.ContentText);
我已经发现你可以找到并检索tickertext。以下代码已经执行了此操作,例如:
CharSquence tickertext;
tickertext = existing.tickerText;
请你帮我弄清楚如何解决我的问题?
谢谢,
艾萨克
答案 0 :(得分:1)
执行此操作的最佳方法是使用 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);