Android通知,点击按钮后如何调用自定义功能?

时间:2014-09-07 19:51:33

标签: android android-notifications android-pendingintent

我有一个简单的通知,有三个按钮。按钮点击后如何调用自定义功能。我是红色的,这里应该使用待定意图,但我没有找到任何有用的例子。

这是我的代码:

PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent, 0);
// I WOULD LIKE TO CALL THIS INTENT OR CUSTOM FUNCTION 
Intent phoneCallIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + "123456789"));

        // build notification
        // the addAction re-use the same intent to keep the example short
        Notification n  = new Notification.Builder(context)
                .setContentTitle("New mail from " + "test@gmail.com")
                .setContentText("Subject")
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentIntent(pIntent)
                .setAutoCancel(true)
                .addAction(R.drawable.ic_launcher, "Call", phoneCallIntent) //CUSTOM INTENT OR FUNCTION CALLING
                .addAction(R.drawable.ic_launcher, "More", pIntent)
                .addAction(R.drawable.ic_launcher, "And more", pIntent)
                .build();


        NotificationManager notificationManager =
                (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0, n);

我该怎么办?

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

您必须使用PendingIntent。以下是如何从Intent创建一个:

PendingIntent pendingPhoneCallIntent = PendingIntent.getActivity(context, REQUEST_CODE, phoneCallIntent, 0);

然后在pendingPhoneCallIntent中使用phoneCallIntent代替addAction()

答案 1 :(得分:0)

来自Notification.Builder setContentIntent(PendingIntent intent)

的文档
  

public Notification.Builder setContentIntent(PendingIntent intent)提供单击通知时要发送的PendingIntent。

所以在构建Notification之前,你需要像这样PendingIntent

PendingIntent pIntent = PendingIntent.getActivity(context, requestCode,phoneCallIntent,PendingIntent.FLAG_UPDATE_CURRENT);
//requestCode is Private request code for the sender like 0,1,2 etc

然后

Notification n  = new Notification.Builder(context)
            .setContentTitle("New mail from " + "test@gmail.com")
            .setContentText("Subject")
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentIntent(pIntent)
            .setAutoCancel(true)
            .build();

现在,当您点击通知时,我们会发送pIntent PendingIntent,以便phoneCallIntent Intent执行。