如何创建Notification.Action并将其添加到自定义通知中

时间:2014-07-10 20:05:41

标签: android android-notifications android-support-library wear-os

我在此处遵循Google的说明https://developer.android.com/training/wearables/notifications/creating.html

然而,毫不奇怪,他们的代码不起作用。特别是我试图这样做:

// Build the notification and add the action via WearableExtender
        Notification notification =
                new Notification.Builder(context)
                        .setSmallIcon(R.drawable.buzz_icon)
                        .setContentTitle("Buzz")
                        .setContentText("OpenBuzz")
                        .extend(new Notification.WearableExtender().addAction(action))
                        .build();

我想要一个特定于Wearable的动作,所以我别无选择,只能使用Notification.WearableExtender()。但是它的addAction方法只接受一个动作作为它的参数。这是我创建动作的代码:

            Notification.Action action =
                Notification.Action.Builder(R.drawable.buzz_icon, actionIntent.toString(), pendingIntent);

哪个不起作用,因为Android Studio说"方法调用预期" 如何成功创建Notification.Action? 或者我如何在通知中添加可穿戴的特定操作?

2 个答案:

答案 0 :(得分:4)

你走在正确的轨道上。

您需要创建新的NotificationCompat.Action.Builder然后调用build()。像这样:

NotificationCompat.Action action = 
    new NotificationCompat.Action.Builder(android.R.drawable.ic_menu_call, "Only in wearable", pendingIntent)
        .build();    

另外,请确保操作定义为NotificationCompat.Action,而不是Notification.Action

答案 1 :(得分:0)

此示例说明了如何添加带有操作的通知(例如,打开主活动)。

 NotificationCompat.Builde mBuilder = new NotificationCompat.Builder(this, null);
 Intent myIntent = new Intent(this, MainActivity.class);
 PendingIntent myPendingIntent = PendingIntent.getActivity(this, 0, myIntent, 0);

 mBuilder.setContentTitle("Your_title")
                .setContentText("Some_text")
                .setSmallIcon(R.drawable.app_icon)
                .setVisibility(Notification.VISIBILITY_PUBLIC)
                .setOngoing(true)
                .addAction(R.drawable.open_icon, "Open", myPendingIntent)
                .setAutoCancel(false);

NotificationManager mNotifyManager = (NotificationManager) getApplicationContext().getSystemService(NOTIFICATION_SERVICE);
mNotifyManager.notify(1, mBuilder.build());