【问题标题】:Android notification, how to call custom function after click on button?Android通知,点击按钮后如何调用自定义函数?
【发布时间】:2014-09-08 04:32:57
【问题描述】:

我有一个带有三个按钮的简单通知。单击按钮后如何调用自定义函数。我红了,说这里应该用pending intent,但是没找到有用的例子。

这是我的代码:

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

请问我该怎么做?

感谢您的帮助。

【问题讨论】:

    标签: android android-notifications android-pendingintent


    【解决方案1】:

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

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

    然后在addAction() 中使用pendingPhoneCallIntent 而不是phoneCallIntent

    【讨论】:

      【解决方案2】:

      来自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 将执行。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-12-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多