我在这里遵循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();
我想要特定于可穿戴设备的操作,因此我别无选择,只能使用Notification.WearableExtender()
。但是它的addAction方法仅接受一个动作作为其参数。这是我创建动作的代码:
Notification.Action action =
Notification.Action.Builder(R.drawable.buzz_icon, actionIntent.toString(), pendingIntent);
这不起作用,因为Android Studio提示“预期方法调用”如何成功创建Notification.Action
?还是我该如何在通知中添加可穿戴设备特定的操作?
您在正确的轨道上。
您需要创建一个新的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
。
此示例说明了如何添加带有操作的通知(例如,打开主活动)。
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());