首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >应用被杀时Firebase未收到消息- Android Oreo

应用被杀时Firebase未收到消息- Android Oreo
EN

Stack Overflow用户
提问于 2018-06-16 04:22:30
回答 2查看 1.3K关注 0票数 0

我知道它有很多关于这个主题的问题,但是没有人在我的项目中工作,我也不知道为什么。

我正在使用Firebase,如果我的应用程序是打开的或在后台,他会收到消息,但当我杀死我的应用程序时,不会更多地出现。

使用Android 8.0

我的代码: AndroidManifest.xml

代码语言:javascript
复制
    <meta-data
        android:name="com.google.firebase.messaging.default_notification_icon"
        android:resource="@drawable/default_notification_icon" />
    <meta-data
        android:name="com.google.firebase.messaging.default_notification_color"
        android:resource="@color/colorPrimary" />
    <meta-data android:name="com.google.firebase.messaging.default_notification_channel_id"
        android:value="@string/default_notification_channel_id" />

    <service
        android:name=".service.PineFirebaseMessagingService"
        android:enabled="true"
        android:exported="true"
        android:permission="com.google.android.c2dm.permission.SEND">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        </intent-filter>
    </service>

    <service
        android:name=".service.PineFirebaseInstanceIDService"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
        </intent-filter>
    </service>

FirebaseMessagingService.java

代码语言:javascript
复制
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {

    channelId = getString(R.string.default_notification_channel_id);

    Log.i("Msg", "Message received [" + remoteMessage.getData() + "]");

    Intent intent = new Intent(this, HomeActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, id, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new
            NotificationCompat.Builder(this, channelId)
            .setSmallIcon(R.drawable.default_notification_icon)
            .setColor(ContextCompat.getColor(this, R.color.colorPrimary))
            .setContentTitle(remoteMessage.getData().get("title"))
            .setContentText(remoteMessage.getData().get("message"))
            .setAutoCancel(true)
            .setContentIntent(pendingIntent)
            .setSound(defaultSoundUri);

    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel mChannel = new NotificationChannel(
                channelId,
                remoteMessage.getData().get("title"),
                NotificationManager.IMPORTANCE_HIGH);
        mChannel.setDescription(remoteMessage.getData().get("message"));
        mChannel.enableLights(true);
        mChannel.enableVibration(true);
        mChannel.setLightColor(Color.BLUE);
        notificationManager.createNotificationChannel(mChannel);
        notificationManager.cancel(id);
    }

    notificationManager.notify(id, notificationBuilder.build());
}

FirebaseInstanceIdService.java

代码语言:javascript
复制
@Override
public void onTokenRefresh() {

    super.onTokenRefresh();
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    Log.d("Token", "Refreshed token: " + refreshedToken);
}

用C#编写发送推送的代码

代码语言:javascript
复制
async Task SendPushAndroidAsync(Device device, InArgumentRequest push, Notification notification)
    {
        var applicationID = configuration["Push:Google:ApplicationKey"];

        var data1 = new
        {
            to = DeviceIdEnviroment(device.Token, true),
            android = new {
                priority = "normal"
            },
            data = new
            {
                notificationId = notification.Id,
                title = notification.Title,
                message = notification.Message,
                type = notification.Type,
                date = notification.DateCreated.ToString("dd/MM/yyyy HH:mm"),
                android_channel_id = "channelidandroid"
            }
        };
        try
        {
            var jsonBody = JsonConvert.SerializeObject(data1);

            using (var httpRequest = new HttpRequestMessage(HttpMethod.Post, "https://fcm.googleapis.com/fcm/send"))
            {
                httpRequest.Headers.TryAddWithoutValidation("Authorization", "key=" + applicationID);
                httpRequest.Content = new StringContent(jsonBody, Encoding.UTF8, "application/json");

                using (var httpClient = new HttpClient())
                {
                    var result = await httpClient.SendAsync(httpRequest);

                    if (result.IsSuccessStatusCode)
                    {
                        await UpdateStatusNotification(notification, true);
                    }
                    else
                    {
                        await UpdateStatusNotification(notification, false, result.ReasonPhrase);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            string error = ex.InnerException.Message;
            await UpdateStatusNotification(notification, false, error);
        }
    }​

谢谢!

EN

回答 2

Stack Overflow用户

发布于 2018-06-16 04:32:41

你需要转到settings> battery optimization>并为你的应用程序禁用它。因为这会阻止应用程序运行后台服务

票数 0
EN

Stack Overflow用户

发布于 2018-06-16 04:56:47

消息“priority should not be nested inside android”的值应该是"high":

代码语言:javascript
复制
    var data1 = new
    {
        to = DeviceIdEnviroment(device.Token, true),
        priority = "high",
        data = new
        {
            notificationId = notification.Id,
            title = notification.Title,
            message = notification.Message,
            type = notification.Type,
            date = notification.DateCreated.ToString("dd/MM/yyyy HH:mm"),
            android_channel_id = "channelidandroid"
        }
    };

您可能没有收到消息,因为设备处于睡眠模式或应用程序处于待机模式。这是explained in the documentation

对您的消息进行更改后,您可以通过调用RemoteMessage.getOriginalPriority()来确认它是以高优先级接收的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50882199

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档