使用来自通知操作的PendingIntent OnFinished回调

时间:2015-11-28 17:12:27

标签: android notifications broadcastreceiver android-service android-pendingintent

Android通知中的操作需要PendingIntent才能运行。典型示例显示触发应用活动的操作。我尝试使用通知操作打开Android意图 - 在Play商店中为应用评分或发送电子邮件。

Intent intentRate = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + mThis.getPackageName()))
Intent intentEmail = new Intent(Intent.ACTION_SEND ...

我想使用OnFinished PendingIntent回调,但是那些是通过.send()方法调用的,并且在Actions中使用PendingIntents的语法不包括.send()

Notification.Builder myRatingNotification = new Notification.Builder(mThis)
                    .setContentTitle(title)
                    .setContentText(text)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .addAction(0, mThis.getString(R.string.Rate_Act_Now), PendingIntent.getActivity(mThis, 0, intentRate, PendingIntent.FLAG_UPDATE_CURRENT))
                    .addAction(0, mThis.getString(R.string.Rate_App_Email), PendingIntent.getActivity(mThis, 0, intentEmail, PendingIntent.FLAG_UPDATE_CURRENT));

            Notification notification = new Notification.BigTextStyle(myRatingNotification).bigText(text).build();
            ((NotificationManager) mThis.getSystemService(Context.NOTIFICATION_SERVICE)).notify(notificationId, notification);

顺便说一下,这都是在后台的BroadcastReceiver服务中运行的。除首次使用设置外,用户通常不会直接打开应用程序。所以这种互动只能通过通知进行。

如何在选择并完成操作后让我的应用程序运行一些代码?

1 个答案:

答案 0 :(得分:0)

使用Notification操作启动Service - 让我们调用它MyNewService - 它处理Intent的发送(intentRate和intentEmail)并实现{{ 1}}

对于PendingIntent.OnFinished,请使用两个NotificationBuilder s

Intent

添加两个Intent iRate = new Intent(this, MyNewService.class); iRate.setAction("rate"); Intent iMail = new Intent(this, MyNewService.class); iMail.setAction("mail"); 操作:

Notification

请注意,为PendingIntents提供不同的请求代码很重要,否则,尽管... .addAction(0, mThis.getString(R.string.Rate_Act_Now), PendingIntent.getService(mThis, 0, iRate, PendingIntent.FLAG_UPDATE_CURRENT)) .addAction(0, mThis.getString(R.string.Rate_App_Email), PendingIntent.getService(mThis, 1, iMail, PendingIntent.FLAG_UPDATE_CURRENT)); 操作不同,它们仍会被视为相同的PendingIntent。

这样,您就可以检查MyNewService的Intent方法中的Intent操作,以触发相应的操作过程。

onStartCommand()

最后,MyNewService必须在您的情况下适当地覆盖@Override public int onStartCommand(Intent intent, int flags, int startId) { if (intent.getAction().equals("rate")) { Intent intentRate = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" ...); PendingIntent pi = PendingIntent.getService(this, 11, intentRate, 0); try{ pi.send(12, this, null); } catch(Exception ex){ // ... } } else if (intent.getAction().equals("mail")) { Intent intentEmail = new Intent(Intent.ACTION_SEND ... PendingIntent pi = PendingIntent.getService(this, 21, intentEmail, 0); try{ pi.send(22, this, null); } catch(Exception ex){// ...} } }