即使应用程序关闭,whatsapp如何设法接收推送通知?
问题描述:
我目前正在研究一个应用程序,它在后台接收短信(短信)(即应用程序关闭时)。我不知道如何通过我注册的服务在状态栏上通知用户在后台接收短信。 NotificationCompat.Builder
类需要上下文作为我们无法在服务类中传递的参数。即使应用程序关闭,whatsapp如何设法接收推送通知?
Whatsapp messenger在新消息到达时如何在状态栏上通知?
我已经经历了很多类似的问题在stackoverflow,但没有人有我的问题的解决方案。请帮我解决这个问题。任何参考或小代码都会有所帮助。
答
NotificationCompat.Builder类需要上下文其paramater我们不能在服务类
Service
是一个Context
通过。 Service
inherits from Context
。因此,您使用Service
本身与NotificationCompat.Builder
。
答
您可以使用粘滞服务,这样做会让你的服务重新开始,如果您的应用程序就会被杀死:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("LocalService", "Received start id " + startId + ": " + intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
您可以检查这里的所有信息:
http://developer.android.com/reference/android/app/Service.html#START_STICKY
编辑:
以下是如何使用它的示例:
http://developer.android.com/reference/android/app/Service.html#LocalServiceSample
但谁说服务将保持活着? – TheRedFox 2014-11-05 13:43:48
@TheRedFox:提高'Notification'需要几微秒。一旦提出'Notification','Service'就不再需要了。 – CommonsWare 2014-11-05 13:44:21
是的,我知道,但我认为他的问题是如何检测消息(即保持服务活着),即使应用程序已被杀害。 – TheRedFox 2014-11-05 13:46:16