【问题标题】:Android - use of pending intent with notificationAndroid - 使用带有通知的待处理意图
【发布时间】:2014-07-28 04:08:40
【问题描述】:

我正在阅读tutorial 的待定意图以及它如何与通知管理器一起使用。

在该页面中,提到了以下代码:

 Intent intent = new Intent(this, NotificationReceiverActivity.class);
 PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);

 Notification noti = new Notification.Builder(this)
    .setContentTitle("New mail from " + "test@gmail.com")
    .setContentText("Subject").setSmallIcon(R.drawable.icon)
    .setContentIntent(pIntent)
    .addAction(R.drawable.icon, "Call", pIntent)
    .addAction(R.drawable.icon, "More", pIntent)
    .addAction(R.drawable.icon, "And more", pIntent).build(); 


 NotificationManager notificationManager = 
     (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

 // hide the notification after its selected
 noti.flags |= Notification.FLAG_AUTO_CANCEL;

 notificationManager.notify(0, noti);

我想问一下为什么需要为通知管理器提供待处理的意图(为什么它需要我的应用程序的身份来发送意图)?

为什么不能只给出一个意图?

编辑:请不要回答待定意图的定义。我知道待定意图是什么。我感兴趣的是为什么通知不能只使用带有诸如 startActivity() 之类的 API 的正常意图。

【问题讨论】:

    标签: android android-intent android-pendingintent


    【解决方案1】:

    意图需要上下文。如果您的应用程序未运行,则没有上下文。使用 PendingIntent 允许系统使用您的应用程序的权限(上下文)调用意图。

    来自http://www.simplecodestuffs.com/what-is-pending-intent-in-android/

    需要它的原因是 因为必须从有效的上下文中创建和启动 Intent 您的应用程序,但在某些情况下不是 在您想要运行该操作时可用,因为您是 从技术上讲,在应用程序的上下文之外(两个常见的例子 正在从 Notification 或 BroadcastReceiver 启动 Activity。

    另见StackOverflow answer

    【讨论】:

    • 但是……为什么通知需要我的应用上下文?如果它只需要发送一个意图,它可以很容易地使用正常的意图并使用类似 startActivity ..
    • Intent 对象本身不依赖于上下文。那么你是说要使用像 startActivity 这样的 API,通知没有可用的上下文对象吗?
    • 发送“startActivity”意图,语法为context.startActivity(intent)。这需要上下文。如果系统在用户点击通知时(以及在您的应用程序关闭后)调用了该行,则上下文已经为空。在同一个链接中,“它是您给予外部应用程序的令牌,它允许外部应用程序使用您的应用程序的权限来执行预定义的一段代码。”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-04
    • 2020-03-30
    相关资源
    最近更新 更多