【问题标题】:How to fix notification not showing up when app is running?如何解决应用程序运行时不显示通知的问题?
【发布时间】:2019-08-22 02:55:12
【问题描述】:

我制作了一个已实现 Firebase 的测试应用程序,我正在使用 Firebase 的通知编写器,它可以正常工作,但没有达到预期的效果,因为通知仅在应用程序未处于活动状态(在屏幕上)时显示,并且我即使应用程序处于活动状态并正在运行,也需要它显示

MainActivity.java

package com.gci.gestioncapteursincendie;

import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.TextView;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.InstanceIdResult;

public class MainActivity extends AppCompatActivity {

    private TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView= findViewById(R.id.textViewToken);
        FirebaseInstanceId.getInstance().getInstanceId()
                .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
                    @Override
                    public void onComplete(@NonNull Task<InstanceIdResult> task) {
                      if(task.isSuccessful()){
                          String token = task.getResult().getToken();
                          System.out.println("token:"+token);
                          textView.setText("Token : " + token);
                        }
                        else
                      {
                          textView.setText("Token Not Generated");
                      }
                    }
                });
    }

}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.gci.gestioncapteursincendie">

    <!-- Granting Internet access permission to app -->
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:name="com.gci.gestioncapteursincendie.FirebaseActivity"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <service
            android:name=".FirebaseMessagingServiceExtended"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
        </service>

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

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

</manifest>

编辑:添加清单

【问题讨论】:

    标签: android firebase firebase-notifications


    【解决方案1】:

    当应用关闭时,您的通知将由 Google 服务进程处理,该进程负责根据需要显示您的通知,包括默认点击操作(打开应用)和通知图标。

    当应用在前台时,接收到的消息由应用处理,由于没有逻辑处理,所以什么都不会发生!

    您可以创建一个自定义的FirebaseMessagingService 来实现onMessageReceived,然后在其中创建通知..

    public class NotificationService extends FirebaseMessagingService { 
        @Override
        public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
        Notification notification = new NotificationCompat.Builder(this)
         .setContentTitle(remoteMessage.getNotification().getTitle())
         .setContentText(remoteMessage.getNotification().getBody())
         .setSmallIcon(R.mipmap.ic_launcher)
         .build();
    
        NotificationManagerCompat manager = NotificationManagerCompat.from(getApplicationContext());
        manager.notify(some_int_number (eg : 123), notification);
       }
     }
    

    并将其添加到您的清单文件

    <service android:name=”.NotificationService”>
      <intent-filter>
        <action android:name=”com.google.firebase.MESSAGING_EVENT”/>
      </intent-filter>
    </service>
    

    还要确保您在清单文件中给予适当的权限。 实施重试后,您应该会在应用处于前台时看到通知。

    【讨论】:

    • @Amine Np 再次,希望你不会被阻止,因为你的 cmets 在你问的上一个问题中被标记:)
    • 好吧,我希望不是,我真的在努力,现在是凌晨 2 点,我一直在努力,因为像下午 2 点这样很累,人们只要有机会就会攻击不要仅仅为了他们本可以帮助我而不是挑剔我而获得的几个代表点而关心你的情况。
    【解决方案2】:

    您必须在要发送到 SDK 的对象中将 show_in_foreground 设置为 Ture。

                     const objNotification = {
                        title: ‘xxxxxx’,
                        body: ‘xxxxx’,
                        sound: 'default',
                        priority: 'high',
                        show_in_foreground: true,
                      };
                      const myMessage = JSON.stringify(objNotification);
    
                      let message;
    
                        message = {
                          notification: {
                            title: ‘xxxxxx’,
                            body: `xxxxx`,
                          },
                          data: {
                            custom_notification: myMessage,
                          },
                          token: registrationToken,
                        };
    
                        admin.messaging().send(message)
                          .then((response) => {
                            res.status(200).send({ success: true, result: response, });
                          })
                          .catch((error) => {
                            console.log('Error sending message:', error);
                            res.status(400).send({ success: false, result: error });
                          });
    

    【讨论】:

      猜你喜欢
      • 2011-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-13
      相关资源
      最近更新 更多