我阅读了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

其他回答

未决意图是指向其他应用程序提供执行特定工作的所有许可的意图。当主活动被销毁时,Android操作系统会收回主活动的权限。

在我的例子中,上述答案和谷歌的官方文档都没有帮助我抓住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或 为什么我们不能使用一个简单的意图达到同样的目的。

例如:Intent bluetoothIntent= new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

如果我将bluetoothIntent发送到另一个没有android。permission权限的应用程序。接收应用程序不能通过startActivity(bluetoothIntent)启用蓝牙。

使用PendingIntent可以克服这个限制。对于PendingIntent,接收应用程序不需要android.permission。BLUETOOTH_ADMIN用于开启蓝牙。源。

一个PendingIntent是一个令牌,你给另一个应用程序(例如通知管理器,警报管理器或其他第三方应用程序),它允许这个其他应用程序使用你的应用程序的权限来执行预定义的代码段。 要通过挂起意图执行广播,请通过PendingIntent. getbroadcast()获取一个PendingIntent。要通过挂起intent来执行一个activity,你需要通过PendingIntent.getActivity()来接收这个activity。