从我的应用程序中单击Google导航通知的“退出”按钮

时间:2019-01-06 12:17:30

标签: java android notifications

我想从我的Android应用程序代码中“点击”出现在Google导航通知中的“退出导航”按钮。

Google导航通知: enter image description here

我知道有一种方法可以执行,因为我可以使用Tasker任务来执行此操作,但是我不知道如何使用应用程序中的代码来执行此操作。

我有一个NotificationListenerService,当使用以下代码接收到onNotificationPosted时,我可以检索通知的文本:

@Override
public void onNotificationPosted(StatusBarNotification sbn) {
    Notification notification = sbn.getNotification();

    if (!pack.equals("com.google.android.apps.maps")) return;

    RemoteViews views = notification.bigContentView;
    if (views == null) views = notification.contentView;
    if (views == null) return null;

    int viewid=0;

    List<String> text = new ArrayList<String>();
    try
    {
        Field fieldActions = views.getClass().getDeclaredField("mActions");
        fieldActions.setAccessible(true);

        @SuppressWarnings("unchecked")
        ArrayList<Parcelable> actions = (ArrayList<Parcelable>) fieldActions.get(views);

        for (Parcelable p : actions)
        {
            Parcel parcel = Parcel.obtain();
            p.writeToParcel(parcel, 0);
            parcel.setDataPosition(0);

            int tag = parcel.readInt();

            if (tag != 2) continue;

            viewid=parcel.readInt();

            String methodName = parcel.readString();
            if (methodName == null) continue;
            else{
                if (methodName.equals("setText"))
                {
                    parcel.readInt();
                    String t = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(parcel).toString().trim();
                    text.add(t);
                    Log.w(TAG,"viewID: "+viewid+"setText: "+t);
                }
            }

            parcel.recycle();
        }
    } catch (Exception e)
    {
        Log.e(TAG, e.toString());
    }

    return text;
}

但是我没有找到一种方法来检索通知的操作(“按钮”)。

谢谢!

1 个答案:

答案 0 :(得分:0)

这很简单。只需从该通知中获取“操作按钮”即可。

Notification notification = sbn.getNotification();
Notification.Action[] actions = notification.actions;

由于该通知只有一个操作按钮,因此您只需执行以下操作:

actions[0].actionIntent.send();

在您检查这是Google地图通知之后。您是在这里做的:

if (!pack.equals("com.google.android.apps.maps")) return;



因此完整的代码应如下所示:

Notification notification = sbn.getNotification();
Notification.Action[] actions = notification.actions;    

if (!pack.equals("com.google.android.apps.maps")) return;    
actions[0].actionIntent.send();

应该工作。希望我能帮助您:)