可靠地检索状态栏通知的详细信息(标题,通知文本)的方法

14

我希望能够从 StatusBarNotification 对象中获取尽可能多的信息。目前,唯一可访问的“可靠”信息是 tickerText 属性。我使用以下代码通过 RemoteViews 获取通知的标题和文本,但很多时候,标题和/或文本将会简单地为 null :-(:

    //Get the title and text
    String mTitle = "";
    String mText = "";
    try {
        RemoteViews remoteView = sbn.getNotification().contentView;
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        ViewGroup localView = (ViewGroup) inflater.inflate(remoteView.getLayoutId(), null);
        remoteView.reapply(getApplicationContext(), localView);
        TextView tvTitle = (TextView) localView.findViewById(android.R.id.title);
        TextView tvText = (TextView) localView.findViewById(16908358);
        mTitle = (String)tvTitle.getText();
        mText = (String)tvText.getText();
    } catch (Exception e){
        Log.e(TAG, "Error getting notification title/text: " + e);
    }

有没有其他(更可靠的)方法?我可以手动编码“流行”的通知(如Gmail、短信等)的资源ID,但这可能会在这些应用程序更新时随时中断。谢谢!

2个回答

4

3

检查资源ID实际上是Android屏幕阅读器TalkBack解析通知类型的方式。它尝试直接从各种包中加载ID。

查看Google代码上的示例。以下是一小段:

private static int ICON_GMAIL;

private static boolean sHasLoadedIcons = false;

private static void loadIcons(Context context) {
    ...

    ICON_GMAIL = loadIcon(context, "com.google.android.gm",
        "com.google.android.gm.R$drawable", "stat_notify_email");

    sHasLoadedIcons = true;
}

public static NotificationType getNotificationTypeFromIcon(Context context, int icon) {
    if (!sHasLoadedIcons) {
        loadIcons(context);
    }

    ...

    if (icon == ICON_GMAIL) {
        return NotificationType.EMAIL;
    }
}

谢谢,alanv,这真的很有趣!我没想到这会是一种“可接受”的方法,因为其他包中资源的名称(和int-ID)可能随时更改。那我就试着手动挖掘最流行的应用程序标题/摘要通知文本字段的资源ID吧。 - Nick
@Nick 你有什么想法吗?另外,当尝试填充布局资源ID时,很多时候会抛出异常。 - nhaarman
2
@Niek,一旦我完成了解决方案,我会在这里分享。我也遇到了布局膨胀异常的问题 :-/。我看到另一个解决方案是他们迭代布局TextView ID(而不是预先膨胀实际布局)。我会看看能否再次找到它。 - Nick
还没有,抱歉,Niek。我还没来得及实现这个功能。 - Nick

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接