安卓:启动服务与Context.startService VS PendingIntent.getServicestartService、Context、VS、getService

2023-09-05 00:34:30 作者:╰悲微oO生活

Context.startService

 意向意图=新的意图(背景下,MyService.class);
context.startService(意向);
 

PendingIntent.getService

 意向意图=新的意图(背景下,MyService.class);
PendingIntent圆周率= PendingIntent.getService(上下文,0,意图,0);
pi.send();
 

问题

当你启动VS一个PendingIntent与Context.startService服务? 为什么要使用一个比其他? 解决方案

真的是没有什么区别。

具体语境方法用于直接启动它在那里作为PendingIntent通常用一个通知触发此意图时,它被窃听,它被延迟,直到它的用户水龙头(通常)。然而;你通常不会直接发送PendingIntent因为这不是它是什么。

Android Studio使用onCreate ,onStartCommand 和stopService 方法来启动和停止服务

一个PendingIntent是待定,待定,这意味着一个意向,其不会现在应该发生,但在不久的将来。而与意图,它在非常时刻被发送。

如果当它用于一个PendingIntent不是未决的,则它不再是PendingIntent并且它是逸岸一个Intent。 击败的目的完全

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();

Questions

When would you start a service with Context.startService vs a PendingIntent? Why would you use one over the other?

解决方案

There really is no difference.

Specifically the Context method is used to directly start it where as a PendingIntent is typically used with a notification to fire this intent when it is tapped, which is delayed until the user taps it (typically). However; you wouldn't typically send the PendingIntent directly because that is not what it is for.

A PendingIntent is an Intent that is pending, pending, meaning that its NOT supposed to happen now, but in the near future. Whereas with an Intent, it is sent at the very moment.

If a PendingIntent is not pending when it is used, then it is no longer a PendingIntent and it is infact an Intent. Defeating the purpose entirely.

 
精彩推荐
图片推荐