簡體   English   中英

應用程序被殺死時Firebase不會收到消息-Android Oreo

[英]Firebase don't receive message when app is killed - Android Oreo

我知道關於這個主題有很多問題,但是在我的項目中沒有人工作,我也不知道為什么。

我正在使用Firebase,如果我的應用程序處於“打開”或在“背景”中,他會收到消息,但是當我殺死我的應用程序時,它不會再顯示了。

使用Android 8.0

我的代碼:AndroidManifest.xml

    <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

@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

@Override
public void onTokenRefresh() {

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

C#中的代碼發送推送

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);
        }
    }​

謝謝!

您需要轉到設置>電池優化>並為您的應用禁用它。 因為這會阻止您的應用程序運行后台服務

消息priority 不應嵌套android內部,其值應為“ high”:

    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"
        }
    };

由於設備處於打ze模式或應用程序處於應用待機模式,因此您可能沒有收到消息。 文檔中對此進行了說明

對郵件進行更改后,您可以通過調用RemoteMessage.getOriginalPriority()來確認已優先接收該郵件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM