未收到 Firebase Cloud Messaging 的 Android 后台通知

2023-12-05

我搜索了很多有关应用程序在后台或关闭时的通知的信息。顺便说一句,我正在使用 Firebase 云消息传递。这对我不起作用。我使用了 Android 设置,当应用程序位于前台或手机未锁定时,会收到通知。

  • 安装后,令牌会正确打印并订阅该主题。
  • 当我在应用程序运行时发送通知时活跃在前台(因此屏幕已解锁并显示应用程序)我收到通知和标题,如onMessageReceived.
  • 当我在应用程序运行时发送通知时未显示但仍在最近的应用程序中并且屏幕是unlocked我收到标题和消息的通知,如中所述notification payload.
  • 当我在应用程序运行时发送通知时未显示但仍在最近的应用程序中并且屏幕是locked什么也没收到。
  • 当我在应用程序运行时发送通知时*关闭并从最近的应用程序中删除什么也没收到。

如何更改此设置,以便应用程序始终收到通知,即使在关闭或手机锁定时也是如此?

诗。我读到了有关受保护应用程序的 Doze 模式的信息,即使我将我的应用程序与受保护的应用程序放在一起,我也没有收到任何消息。我正在华为 P8 Lite 上进行测试。

Android清单

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme" >
    <activity android:name=".activities.MainActivity"
        android:configChanges="orientation"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <service
        android:name=".services.MyAppFirebaseMessagingService"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT"/>
        </intent-filter>
    </service>
    <service
        android:name=".services.FirebaseIDService"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
        </intent-filter>
    </service>
    <receiver android:name=".services.NotificationReceiver" />
</application>

Gradle

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.google.firebase:firebase-core:9.2.0'
    compile 'com.google.firebase:firebase-messaging:9.2.0'
}

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

Firebase消息服务

public class MyAppFirebaseMessagingService extends FirebaseMessagingService {
    private static final String TAG = "FCM Service";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // TODO: Handle FCM messages here.
        // If the application is in the foreground handle both data and notification messages here.
        // Also if you intend on generating your own notifications as a result of a received FCM
        // message, here is where that should be initiated.
        Log.d(TAG, "From: " + remoteMessage.getFrom());
        Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());

        showNotification(getApplicationContext());
    }

    public static void showNotification(Context context){
        Intent intent = new Intent(context, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle("FCM Message")
            .setContentText("FCM Body")
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setPriority(Notification.PRIORITY_MAX)
            .setContentIntent(pendingIntent);

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

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

FirebaseInstanceID服务

public class FirebaseIDService extends FirebaseInstanceIdService {

    private static final String TAG = "FirebaseIDService";

    @Override
    public void onTokenRefresh() {
        // Get updated InstanceID token.
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "Refreshed token: " + refreshedToken);

        System.out.println("Devicetoken: " + refreshedToken);

        FirebaseMessaging.getInstance().subscribeToTopic("/topics/myapp");

        // TODO: Implement this method to send any registration to your app's servers.
        sendRegistrationToServer(refreshedToken);
     }

    /**
     * Persist token to third-party servers.
     *
     * Modify this method to associate the user's FCM InstanceID token with any server-side account
     * maintained by your application.
     *
     * @param token The new token.
     */
    private void sendRegistrationToServer(String token) {
         // Add custom implementation, as needed.
    }
}

通知负载

{
    "to": "/topics/mytopic",
    "priority": "high",
    "notification": {
        "sound": "default",
        "badge": "1",
        "body": "the body text",
        "title": "title text"
     },
     "data": {
         "id": "id",
         "channel": "channel"
     }
}

编辑 - 添加 WakeFulBroadcastReceiver 的代码

public class NotificationReceiver extends WakefulBroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        // cancel any further alarms
        AlarmManager alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        alarmMgr.cancel(alarmIntent);
        completeWakefulIntent(intent);

        // start the GcmTaskService
        MyAppFirebaseMessagingService.showNotification(context);
    }
}

更新有效负载

如果我将我的有效负载更改为评论中建议的方式,这样它仍然无法工作。也许这与我正在测试的安装了 Android 6.0.1 的华为 P8 Lite 有关。

{
    "to": "/topics/mytopic",
    "priority": "high",
    "data": {
        "sound": "default",
        "badge": "1",
        "body": "the body text",
        "title": "title text"
    }
}

更新2.0

我已经在多个设备和版本上进行了测试。在 Android 5 的设备上,它运行良好,也无需打开应用程序和锁定屏幕。唯一无法正常工作的设备是我自己的华为 P8 Lite。仍然不明白为什么它不起作用。


当应用程序关闭时,它会关闭服务。您必须重新启动该服务。

在您的 Application 类上,实现 ActivityLifecycleCallbacks 并在 onActivityDestroyed 上通过警报重新启动服务。

public class YourApplication extends Application implements Application.ActivityLifecycleCallbacks {
    @Override
    public void onCreate() {
        super.onCreate();
        registerActivityLifecycleCallbacks(this);
    }

    @Override
    public void onActivityDestroyed(Activity activity) {
            Intent restartService = new Intent(getApplicationContext(), MyAppFirebaseMessagingService.class);
            PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(),1,restartService,PendingIntent.FLAG_ONE_SHOT);
            AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            alarmManager.set(AlarmManager.ELAPSED_REALTIME,5000,pendingIntent);
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

未收到 Firebase Cloud Messaging 的 Android 后台通知 的相关文章

随机推荐

  • 主屏幕网络应用程序的 Facebook 身份验证已损坏!+

    使用元名称 apple mobile web app capable 内容 yes 删除所有移动 safari ui 时 Facebook connect js js api 无法与主屏幕 web 应用程序一起使用 经过身份验证后 我会看到
  • 从活动之外的类启动意图

    我有两项活动 其中一项称为MyActivity 我希望他们都能够使用位于我们可以调用的类中的函数MyClass In MyClass 我尝试使用意图来启动活动AnotherActivity 由于构造函数采用上下文作为参数 因此我只是尝试在构
  • Hibernate @Version 注释

    hibernate version 和 ManyToOne Mapping 之间的关系是什么 假设我有两个表 部门 和 员工 这是部门是主表 和明细表中的员工 在 Employee 表中 部门 ID 作为外键引用 这是我的课程 Public
  • 在 PowerShell 上将节点从一个 XML 导入到另一个 XML

    我需要将名称为 ProjectOptions 的节点从default xml 复制到original xml 而不修改任何其他内容 原始 xml
  • 如何将 Google 数据存储用于未托管在 Google 应用引擎中的网络应用?

    我想在我的网络应用程序中使用谷歌的数据存储 但不想将其托管在谷歌应用程序引擎中 我想将其托管在其他机器上 那么我如何在这样的网络应用程序中使用数据存储 会更经济吗 您需要遵循从其他平台访问 Cloud Datastore API程序 本部分
  • 列表的 ViewModel 验证

    我有以下视图模型定义 public class AccessRequestViewModel public Request Request get private set public SelectList Buildings get pr
  • Rust *准确地*如何查找模块?

    Rust 用于从文件中查找模块的确切规则集是什么 我在网上找到的关于模块的每一个解释都说 这是模块的目的 这是一个例子 没有一个给出完整 全面 100 准确的解释Rust 如何查找模块 就连铁锈参考没有告诉您板条箱根和导入文件是否都需要声明
  • 使用 printf 连续打印数字并填充零

    在 C 中 使用 printf 我想打印一个数字序列 所以我从 for 循环中得到 1 2 9 10 11 我根据这些数字创建文件 但是当我使用 ls 列出它们时我得到 10 11 1 2 因此 我不知道如何打印 而不是尝试使用 bash
  • 使用 FileSavePicker 在 Windows Phone 8.1 中保存图像

    我想使用文件保存选择器保存图像 我在用this保存链接 但它仅适用于文本 我如何修改它以保存图像 正如你所提供的the link那么我假设你设法得到了存储文件 after 延续 这就是它在 WP8 1 运行时的工作方式 我还假设你有一个St
  • Scala 的 apply() 方法魔法是如何工作的?

    在 Scala 中 如果我定义一个名为apply在类或顶级对象中 每当我将一对括号附加到该类的实例 并为apply 在他们之间 例如 class Foo x Int def apply y Int x x y y val f new Foo
  • ASP.Net Ajax - PageMethods 同步调用和检索结果

    如何在ASP Net Ajax PageMethods中同步调用并检索结果 目前我正在做以下事情async调用并处理数据 function checkName name PageMethods IsAvailable name onSucc
  • 发送带有返回路径的电子邮件不起作用

    我在用System Net Mail电子邮件 在代码中 我设置电子邮件的返回路径如下 string sReturnPath ConfigurationManager AppSettings ReturnPath ToString if sR
  • event 是一个全局变量,可以在回调链中的任何地方访问吗?

    我只是用 DOM 和 Javascript 来玩弄事件监听器 并注意到了这一点 function chained msg console log msg event function onClick chained the body was
  • 即使没有网络可用,如何保存 WebView 内容以供显示?

    我正在创建一个应用程序并使用 WebView 来打开 URL 我看到一些应用程序向用户提供 保存页面 网页 选项 我想知道如何从 WebView 保存页面 以便我可以在用户请求时将其显示给用户 也许使用缓存是最好的方法 为此你应该检查htt
  • 为什么这个 jQuery 事件不会在 Gmail 中触发?

    我在将 jQuery 事件绑定到 gmail body 时遇到问题 body on click function event console log Entered function 访问 IMDB com 例如 并在 Google Chr
  • 使用 DOMPDF 和重定向创建 PDF

    在 PHP 项目中 我需要创建一个 PDF 文件 并在用户单击 提交 按钮时重定向到另一个页面 我已经成功使用创建了 pdf 文件DOMPDF PDF 创建在单独的文件中完成 PDFRecipt php 当用户单击主页上的按钮时 我已调用该
  • Lambda 表达式返回错误

    这是我的代码 SomeFunction m gt ViewData AllEmployees Where c gt c LeaderID m UserID 它返回此错误 并非所有代码路径都返回 lambda 表达式类型的值System Fu
  • SDK19 启动时相机2 库崩溃的 Android 应用程序

    我在我的应用程序中使用 androidx camera camera2 库 该库适用于 SDK 21 及更高版本 但我希望允许用户在没有camera2支持的情况下启动SDK 19的应用程序 我在代码中检查了 SDK 版本 但应用程序在启动时
  • Laravel 5:找不到“HTML”类

    我刚刚开始使用 Laravel 我处于控制器方法中 我说 return View make scrape data 然后在 scrape blade php 中我有 extends layouts master 最后 在 layouts m
  • 未收到 Firebase Cloud Messaging 的 Android 后台通知

    我搜索了很多有关应用程序在后台或关闭时的通知的信息 顺便说一句 我正在使用 Firebase 云消息传递 这对我不起作用 我使用了 Android 设置 当应用程序位于前台或手机未锁定时 会收到通知 安装后 令牌会正确打印并订阅该主题 当我