簡體   English   中英

僅在應用程序處於前台時才收到Android通知

[英]Android notifications only received if app is in foreground

我正在嘗試使用FCM向我的應用程序實施通知,並且遇到了一些問題。 當應用程序位於前台時,就沒有問題,並且通知將按預期顯示。 但是,如果應用程序在后台運行,則不會顯示通知。

我的清單如下所示:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="xxx">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

<uses-sdk android:minSdkVersion="19" />

<application
    android:allowBackup="true"
    android:icon="@drawable/icon"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <service
        android:name=".NotificationService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT"/>
        </intent-filter>
    </service>

    <service
        android:name=".FirebaseInstanceIDService">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
        </intent-filter>
    </service>

    <activity android:name=".MainActivity" android:launchMode="singleTask">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />

    <meta-data android:name="com.google.android.gms.games.APP_ID"
        android:value="@string/app_id" />


    <meta-data
        android:name="io.fabric.ApiKey"
        android:value="xxx" />
     </application>
   </manifest>

我的服務類別:

 package pw.ckies.snakegame;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

import java.util.Random;

public class NotificationService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMsgService";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        String title = "Empty";
        String message = "Emptyyy";
        if(remoteMessage.getNotification() != null) {
            if (remoteMessage.getNotification().getTitle() != null) {
                title = remoteMessage.getNotification().getTitle();
            }


            if (remoteMessage.getNotification().getBody() != null) {
                message = remoteMessage.getNotification().getBody();
            }
        }

        Log.e("notification","recieved");


        sendNotification(title, message);
    }

    private void sendNotification(String title, String message) {

        Intent intent = new Intent(this, MainActivity.class);

        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_people_black_24dp)
                .setLargeIcon(BitmapFactory.decodeResource(this.getResources(),
                        R.mipmap.ic_launcher))
                .setContentTitle(title)
                .setContentText(message)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

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

    private static int getRequestCode() {
        Random rnd = new Random();
        return 100 + rnd.nextInt(900000);
    }

}

另外,收到通知時,logcat會說:

07-01 23:09:14.050? W / GCM-DMM:廣播意圖回調:result = CANCELLED forIntent {act = com.google.android.c2dm.intent.RECEIVE flg = 0x10000000 pkg = xxx(有其他功能)}

我不知道這是什么意思,所以我用它搜索了一下,發現很多有同樣問題的人。 有人說重新安裝Android Studio可以解決此問題,所以我做到了,並且沒有任何運氣就更新到了最新的2.3.3版本。 我一直在Android 7.1.1的OnePlus 3上進行測試。

我的build.grade(應用模塊):

 ...
    dependencies {
        compile fileTree(include: ['*.jar'], dir: 'libs')
        testCompile 'junit:junit:4.12'
        compile "com.google.android.gms:play-services-games:${gms_library_version}"
        compile project(':BaseGameUtils')
        compile 'com.android.support:appcompat-v7:24.0.0'

        compile 'com.android.support:design:24.0.0'
        compile 'com.android.support:support-annotations:24.0.0'
        compile 'com.google.firebase:firebase-ads:11.0.1'
        compile 'com.google.firebase:firebase-core:11.0.1'
        compile 'com.google.firebase:firebase-messaging:11.0.1'
        compile('com.crashlytics.sdk.android:crashlytics:2.6.6@aar') {
            transitive = true;
        }
    }

    apply plugin: 'com.google.gms.google-services'

我的后端是使用以下數據的python發布請求:

{
    "notification": {"title": "Title goes here", "body": "Body goes here" },
    "to": token
}

我也嘗試過從Firebase儀表板發送通知。

有人還建議未簽名的APK不允許我不確定的后台通知? 但是由於我的應用程序在Play商店中,所以不會有任何問題。

我已經測試了所有可以想到的東西,但是找不到解決方案! 這可能是我的電話,也可能只是一個愚蠢的錯誤。 任何幫助表示贊賞!

從Firebase文檔

在后台時,應用程序會在通知托盤中接收通知有效載荷,並且僅在用戶點擊通知時處理數據有效載荷。

有人還建議未簽名的APK不允許我不確定的后台通知? 但是由於我的應用程序在Play商店中,所以不會有任何問題。

默認情況下,您的應用程序已使用默認密鑰庫簽名。 全部取決於在Firebase控制台中添加到項目設置的SHA1。

對於生產或調試密鑰庫,您可以從此處生成SHA1

我已經測試了所有可以想到的東西,但是找不到解決方案! 嘗試發送包含標題和正文(可選)數據鍵的通知有效負載

  {
    "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
    "notification" : {
      "body" : "great match!",
      "title" : "Portugal vs. Denmark",
      "icon" : "myicon"
    }
  }

當您的應用處於后台或關閉狀態時,不會調用FirebaseMessagingService的“ onMessageReceived()”方法。 當您沒有在通知中發送任何數據時,就會發生這種情況。 您需要通過服務器上的Data Payload隨通知發送任意值。 之后,即使關閉應用程序或在后台運行,它也可以在每種情況下使用。

注意:要在通知中發送數據,您需要自己的服務器,Firebase對此不方便。

檢查此鏈接以獲取更多詳細信息:

當Firebase中的應用程序在后台運行時如何處理通知

暫無
暫無

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

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