我在Android应用中实现了Firebase的推送通知功能。我实现了两个服务,用于注册令牌和在检测到令牌时创建通知。当我的应用程序启动时,它可以工作,但是当我的应用程序关闭时,它不能工作。
public class FirebaseinstanceIdService extends FirebaseInstanceIdService {
@Override
public void onTokenRefresh() {
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.e("Firebase", refreshedToken);
MainActivity.setFirebaseToken(refreshedToken);
}
}
public class MyFirebaseMessageService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
//Displaying data in log
//It is optional
Log.e(TAG, "From: " + remoteMessage.getFrom());
Log.e(TAG, "Notification Message Body: " + remoteMessage.getData().get("title"));
//Calling method to generate notification
sendNotification(remoteMessage.getData());
}
//This method is only generating push notification
//It is same as we did in earlier posts
private void sendNotification(Map<String, String> notification) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(notification.get("title"))
.setContentText(notification.get("body"))
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
}
而我的清单:
<service
android:name=".FirebaseinstanceIdService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
<service
android:name=".MyFirebaseMessageService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
和我的要求:
{
"to": "ex1CtVz5bbE:APA91bHiM_BCun62A9iCobF1yV26Dwn-hYCDhkYPoWEG5ZdqH0P28UsE5q1v7QibwAX7AJ290-9en9L6f548_2b7WEbJ8RPEWlIotLczjjCP7xEOWqeJk6Iz44vilWYvdu4chPwfsvXD",
"data": {
"title": "Notification",
"body": "Message",
}
}
我已经在StackOverflow中找到了一些解决方案,但是在我的情况下它不起作用。我有一个API Rest,可以调用API Request Post:https : //fcm.googleapis.com/fcm/send
因此,我有一个问题:当应用关闭时,Firebase是否会处理推送通知,以及如何处理?
谢谢您的回答
当应用关闭时,FCM确实支持通知。您的代码似乎还可以,因此我认为电池省电器(或节电器)可以杀死您的通知。我的华硕Zenfone遇到了此类问题,在使用华为和小米的情况下也有报告。只需禁用它们或将您的应用添加到例外列表(如果有)。在最新版本的Android中,还有一种新的省电模式,也请尝试将其禁用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句