简体   繁体   中英

How can I create a Notification.Action and add it to a custom notification

I'm following Google's instructions here https://developer.android.com/training/wearables/notifications/creating.html

However, unsurprisingly, their code doesn't work. Specifically I'm trying to do this:

// 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();

I want an action specific to the Wearable, so I have no choice but to use Notification.WearableExtender() . But it's addAction method only accepts an action as it's parameter. Here is my code for creating an action:

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

Which doesn't work, as Android Studio says "Method call expected" How can I successfully create a Notification.Action ? Or how else might I add a Wearable specific action to my notification?

You're on the right track.

You need to create a new NotificationCompat.Action.Builder and then call build() on it. Like this:

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

Also, make sure that the action is defined as NotificationCompat.Action , not Notification.Action .

This example illustrates how to add a notification with an action (eg open the main activity).

 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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM