Android:使用 Context.startService 与 PendingIntent.getService 启动服务

标签 android android-intent android-context android-pendingintent

Context.startService

Intent intent = new Intent(context, MyService.class);
context.startService(intent);

PendingIntent.getService

Intent intent = new Intent(context, MyService.class);
PendingIntent pi = PendingIntent.getService(context, 0, intent, 0);
pi.send();


问题

  1. 您何时会使用 Context.startService 与 PendingIntent 启动服务?
  2. 你为什么要用一个而不是另一个?

最佳答案

真的没有区别。

特别是 Context 方法用于直接启动它,因为 PendingIntent 通常与通知一起使用以在点击时触发此 Intent ,这会延迟到用户点击它(通常)。然而;您通常不会直接发送 PendingIntent,因为这不是它的用途。

PendingIntent 是待定、未决的 Intent,这意味着它NOT应该现在发生,但会在不久的将来发生。而对于 Intent,它会立即发送。

如果一个 PendingIntent 在使用时不是挂起的,那么它就不再是一个 PendingIntent,它实际上是一个 Intent。 完全违背目的

关于Android:使用 Context.startService 与 PendingIntent.getService 启动服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9152924/

相关文章:

android - 如何在完整的 TextView 中制作一个单词可点击的android(不是url链接)

java - Xamarin android 图像 URI 到字节数组

android - MediaPlayer.start() 不能在构造函数中调用?

class - 安卓状态机

android - 检测拨出电话是否已接听

c# - Xamarin Android图像url数组到gridview中

android - 如何显式地在另一个模块中启动一个 Activity

android - getApplicationContext() 在服务中返回 null

android - 在 Thread 捕获 UncaughtException 之前上下文会发生什么

android - 从 getContext() 或从构造函数获取上下文作为字段