简体   繁体   English

仅在应用程序处于前台时才收到Android通知

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

I'm trying to implement notifications to my app using FCM and have been experiencing some problems. 我正在尝试使用FCM向我的应用程序实施通知,并且遇到了一些问题。 When the app is in the foreground there is no problems and the notification is shown as expected. 当应用程序位于前台时,就没有问题,并且通知将按预期显示。 However if the app is in the background the notification won't be shown. 但是,如果应用程序在后台运行,则不会显示通知。

My manifest looks like this: 我的清单如下所示:

<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>

And my service class: 我的服务类别:

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

}

Also when a notification is recieved logcat says: 另外,收到通知时,logcat会说:

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

I have no idea what it means so I googled it and found alot of people who had the same problem. 我不知道这是什么意思,所以我用它搜索了一下,发现很多有同样问题的人。 Someone said that reinstalling Android Studio would solve the issue so I did that and updated to the latest version 2.3.3 without any luck. 有人说重新安装Android Studio可以解决此问题,所以我做到了,并且没有任何运气就更新到了最新的2.3.3版本。 I have been testing on a OnePlus 3 on android 7.1.1. 我一直在Android 7.1.1的OnePlus 3上进行测试。

My build.grade (App module): 我的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'

My backend is a python post request using the following data: 我的后端是使用以下数据的python发布请求:

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

I have also tried sending the notification from the firebase dashboard. 我也尝试过从Firebase仪表板发送通知。

Someone also suggested an unsigned APK wouldn't allow background notifications which I'm not sure about? 有人还建议未签名的APK不允许我不确定的后台通知? But as my app is on the Play Store that would not be any issue. 但是由于我的应用程序在Play商店中,所以不会有任何问题。

I have tested everything I can think but I can't find a solution! 我已经测试了所有可以想到的东西,但是找不到解决方案! It might be my phone or maybe just a stupid mistake. 这可能是我的电话,也可能只是一个愚蠢的错误。 Any help is appreciated! 任何帮助表示赞赏!

From the firebase docs 从Firebase文档

When in the background, apps receive the notification payload in the notification tray, and only handle the data payload when the user taps on the notification. 在后台时,应用程序会在通知托盘中接收通知有效载荷,并且仅在用户点击通知时处理数据有效载荷。

Someone also suggested an unsigned APK wouldn't allow background notifications which I'm not sure about? 有人还建议未签名的APK不允许我不确定的后台通知? But as my app is on the Play Store that would not be any issue. 但是由于我的应用程序在Play商店中,所以不会有任何问题。

Your application is signed by default with default keystore. 默认情况下,您的应用程序已使用默认密钥库签名。 All depends on SHA1 added to your project settings in firebase console. 全部取决于在Firebase控制台中添加到项目设置的SHA1。

For production or debug keystore, you can generate SHA1 from here 对于生产或调试密钥库,您可以从此处生成SHA1

I have tested everything I can think but I can't find a solution! 我已经测试了所有可以想到的东西,但是找不到解决方案! Try sending the notification payload contain title and body (optional) data keys 尝试发送包含标题和正文(可选)数据键的通知有效负载

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

FirebaseMessagingService's "onMessageReceived()" method doesn't get called when your App is in background or closed. 当您的应用处于后台或关闭状态时,不会调用FirebaseMessagingService的“ onMessageReceived()”方法。 It happens when you are not sending any data in your notification. 当您没有在通知中发送任何数据时,就会发生这种情况。 You need to send some values whatever you want with your notification through Data Payload from your server. 您需要通过服务器上的Data Payload随通知发送任意值。 After that it'll work in each and every situation even when app is closed or in background. 之后,即使关闭应用程序或在后台运行,它也可以在每种情况下使用。

Note: To send data in notification you need your own server, Firebase doesn't facilitate with that. 注意:要在通知中发送数据,您需要自己的服务器,Firebase对此不方便。

Check this link for more details: 检查此链接以获取更多详细信息:

How to handle notification when app in background in Firebase 当Firebase中的应用程序在后台运行时如何处理通知

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM