Intent和PendingIntent之间的差异

use*_*316 92 android android-service

我读了一些文章,似乎都做了同样的事情,我想知道启动服务之间的区别是什么:

Intent intent = new Intent(this, HelloService.class);
startService(intent);
Run Code Online (Sandbox Code Playgroud)

或者像那样:

Calendar cal = Calendar.getInstance();
Intent intent = new Intent(this, MyService.class);
PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 30*1000, pintent); 
Run Code Online (Sandbox Code Playgroud)

当我读完时,这两个做同样的事情,如果在服务中你返回一个参数START_STICKY;

Sid*_*yas 142

意图

Android Intent是一个携带意图的对象,即从应用程序内部或外部的一个组件到另一个组件的消息.Intent可以在应用程序的三个核心组件中的任何一个之间传递消息 - Activities,Services和BroadcastReceivers.

意图本身是一个Intent对象,是一种被动数据结构.它包含要执行的操作的抽象描述.

例如:假设您有一个需要启动电子邮件客户端并发送电子邮件的活动.为此,您的Activity会将操作的Intent ACTION_SEND以及相应的选择器发送到Android Intent Resolver:

Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:")); // only email apps should handle this
Run Code Online (Sandbox Code Playgroud)

指定的选择器为用户提供了适当的界面,以便选择如何发送电子邮件数据.

显性意图

// Explicit Intent by specifying its class name
   Intent i = new Intent(this, TargetActivity.class);
   i.putExtra("Key1", "ABC");
   i.putExtra("Key2", "123");

// Starts TargetActivity
   startActivity(i);
Run Code Online (Sandbox Code Playgroud)

隐含意图

// Implicit Intent by specifying a URI
   Intent i = new Intent(Intent.ACTION_VIEW, 
   Uri.parse("http://www.example.com"));

// Starts Implicit Activity
   startActivity(i); 
Run Code Online (Sandbox Code Playgroud)

待定意图

PendingIntent是您为外部应用程序(例如NotificationManager,AlarmManager,Home Screen AppWidgetManager或其他第三方应用程序)提供的令牌,它允许外部应用程序使用您的应用程序的权限来执行预定义的代码段.

通过向另一个应用程序提供PendingIntent,您授予它执行您指定的操作的权利,就好像另一个应用程序是您自己(具有相同的权限和标识).因此,您应该注意如何构建PendingIntent:几乎总是,例如,您提供的基本Intent应该将组件名称显式设置为您自己的组件之一,以确保它最终发送到那里,而不是其他任何地方.

待定意图的示例:http://android-pending-intent.blogspot.in/

资料来源:Android IntentsAndroid Pending Intents

希望这可以帮助.


Hun*_*NM2 24

PendingIntent是一个包装Intent.收到的外国应用程序,PendingIntent不知道其内容Intent被包装PendingIntent.外国应用程序的任务是在满足某些条件时将意图发送给所有者(例如:带有计划的警报或带有点击的通知......).所有者给出条件,但由外国应用程序处理(例如:警报,通知).

如果外国应用程序向您的应用程序发送意图,则表示外国应用程序了解意图的内容.和外国应用程序决定发送意图,然后您的应用程序必须处理意图,以满足某些条件=>您的应用程序获得系统的性能资源.


Zum*_*med 8

另一个简单的区别:

  • 正常意图会在应用程序被杀死后立即消失。

  • 挂起的意图永远不会消亡。只要警报服务、定位服务或任何其他服务需要它们,它们就会一直存在。


Val*_*kov 6

Intent和之间还有另一个主要区别,PendingIntent最好注意一下,否则您的应用程序的设计可能会变得脆弱Android Nesting Intents文章很好地描述了这个问题。

请注意,该PendingIntent.send()方法不接受Context实例,而是使用意图创建期间提供的上下文。它允许第三方组件在意图创建者的上下文中执行与待处理意图关联的操作。

让我们想象一个第三方服务,它执行一些工作,然后启动由您的应用程序指定为意图的活动。如果回调活动作为 basic 提供Intent,则服务只能使用自己的上下文来启动它,这样的设计有两个缺点:

  • 它强制定义回调exported活动,以便可以使用第三方上下文启动它。因此,该活动不仅可以由其预期的服务启动,还可以由设备上安装的任何其他应用程序启动。
  • 第三方服务应用程序定义的任何活动都可以用作回调活动,即使是未导出的活动,因为它是使用第三方上下文开始的。

通过指定回调活动可以轻松解决这两个问题PendingIntent