我正在寻找一种能够从Notification Object检索ContentText的方法。类似于以下内容:
NotificaionCompat.Builder builder;
Notification existing;
builder.setContentText(existing.ContentText);
我已经发现您可以找到并检索代码文本。例如,下面的代码已经做到了:
CharSquence tickertext;
tickertext = existing.tickerText;
请您能帮我弄清楚如何解决我的问题吗?
谢谢,
以撒
最佳答案
最好的方法是使用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>
第三步
您必须从用户授权。您可以在设置->安全->通知访问中找到它
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);
关于android - 如何从android.app.Notification对象检索ContentText?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31355927/