我阅读了Android文档,但我仍然需要更多的说明。PendingIntent到底是什么?


当前回答

出租车的类比

意图

intent通常用于启动Services。例如:

Intent intent = new Intent(CurrentClass.this, ServiceClass.class);
startService(intent);

这就像你叫出租车的时候:

Myself = CurrentClass
Taxi Driver = ServiceClass

悬而未决的意图

你需要使用像这样的东西:

Intent intent = new Intent(CurrentClass.this, ServiceClass.class);
PendingIntent pi = PendingIntent.getService(parameter, parameter, intent, parameter);
getDataFromThirdParty(parameter, parameter, pi, parameter);

现在这个第三方将代表您启动服务。 现实生活中的一个类比是Uber或Lyft,它们都是出租车公司。

你向优步/来福车发出打车请求。然后他们会代表你打电话给他们的司机。

因此:

Uber/Lyft ------ ThirdParty which receives PendingIntent
Myself --------- Class calling PendingIntent
Taxi Driver ---- ServiceClass

其他回答

在我的例子中,上述答案和谷歌的官方文档都没有帮助我抓住PendingIntent类的概念。

然后我发现了这个视频,谷歌I/O 2013, Beyond Blue Dot会议。在这个视频中,前谷歌员工Jaikumar Ganesh解释了PendingIntent是什么,这让我对它有了一个大的了解。

以下是上述视频的转录(从15:24)。

待定意图是什么? 它是你的应用进程会给定位进程的一个令牌,定位进程会在感兴趣的事件发生时用它来唤醒你的应用。这基本上意味着你的应用在后台不需要一直在运行。当有趣的事情发生时,我们会叫醒你。这样可以节省很多电池。

通过下面的代码片段(包含在会话的幻灯片中),这种解释变得更加清晰。

PendingIntent mIntent = PendingIntent.getService(...);

mLocationClient.requestLocationUpdates(locationRequest, mIntent);

public void onHandleIntent(Intent intent) {   
    String action = intent.getAction();   
    if (ACTION_LOCATION.equals(action)) {       
        Location location = intent.getParcelableExtra(...)   
    }
}

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

如果你给了外部应用一个Intent,它会用自己的权限执行你的Intent。但是如果你给了外部应用一个PendingIntent,该应用将使用你的应用权限执行你的Intent。

一个PendingIntent用一个令牌包装了一般的Intent,你给外部应用程序执行你的许可。 如:

你的音乐应用程序的通知不能播放/暂停音乐如果你 没有给PendingIntent发送广播,因为你的音乐应用 哪个通知应用程序具有READ_EXTERNAL_STORAGE权限 不喜欢。通知是一个系统服务(所以它是一个外部应用程序)。

顾名思义…PendingIntent

你可以过一段时间再做。这是另一个意图。它是一种将你的任务交给其他应用程序来执行的方式。

简单来说

悬而未决的意图基本上是一种意图,你可以传递给其他应用程序或服务,如通知管理器,警报管理器等,让他们处理何时是正确的时间/行为执行。