【问题标题】:How to stop a FCM notification from getting displayed and making sound continuously?如何阻止 FCM 通知显示并连续发出声音?
【发布时间】:2021-07-22 13:34:19
【问题描述】:

我正在尝试使用 ESP-8266 和 Mobiz 的“Firebase-ESP8266”库以 FCM 通知的形式发送我的传感器值。当应用程序处于后台或被终止时,我会定期收到包含指定消息的 FCM 通知。但问题是,每当有新通知出现时,它就会弹出/显示在屏幕上并且每次都发出声音,这很烦人。

我希望一旦收到第一个通知,那么在用户取消之前,即将到来的通知不应显示在屏幕上或发出任何声音。我只是想让他们替换通知托盘中的现有通知。

我已经能够替换通知托盘中的现有通知,但通知仍在屏幕上弹出并发出声音。有什么解决办法吗?

这是我的 manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.tokenapp">
    <uses-permission android:name="android.permission.INTERNET"
/>
    <application
        android:name=".App"
        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/Theme.TokenApp">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service
            android:name=".MyFirebaseMessagingService"
            android:exported="false">

            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
            </intent-filter>
        </service>
        <meta-data
            android:name="firebase_messaging_auto_init_enabled"
            android:value="false"/>
        <meta-data
            android:name="firebase_analytics_collection_enabled"
            android:value="false"/>
        <meta-data
            android:name="com.google.firebase.messaging.default_notification_icon"
            android:resource="@drawable/ic_baseline_api_24"/>
        <meta-data
            android:name="com.google.firebase.messaging.default_notification_color"
            android:resource="@color/green"/>
        <meta-data
            android:name="com.google.firebase.messaging.default_notification_channel_id"
            android:value="@string/channelid"/>

        <meta-data
            android:name="com.google.firebase.messaging.default_notification_tag"
            android:value="MyTAG"/>


    </application>

</manifest>

MyFirebaseMessagingService.java 类

package com.example.tokenapp;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.graphics.Color;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;

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

import static com.example.tokenapp.App.CHANNEL_ID;

public class MyFirebaseMessagingService extends FirebaseMessagingService {


    public static final String TAG = "MyTAG";

    @Override
    public void onMessageReceived(@NonNull  RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
        Log.d(TAG,"onMessageReceiveCalled");
        Log.d(TAG,"onMessageReceived:MessageReceived From: "+remoteMessage.getFrom());
        if(remoteMessage.getNotification()!=null){
            String title = remoteMessage.getNotification().getTitle();
            String body = remoteMessage.getNotification().getBody();
            long[] v={500,1000};
            Notification notification = new NotificationCompat.Builder(this,CHANNEL_ID)
                    .setSmallIcon(R.drawable.ic_baseline_api_24)
                    .setContentTitle(title)
                    .setContentText(body)
                    .setColor(Color.GREEN).setOnlyAlertOnce(true).setStyle(new NotificationCompat.BigTextStyle().bigText("")).setVibrate(v).setAutoCancel(true)
                    .build();
            NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
            manager.notify(1002,notification);
        }
        if(remoteMessage.getData().size()>0){
            Log.d(TAG,"onMessageReceived :Data:"+remoteMessage.getData().toString());
        }
    }

    @Override
    public void onDeletedMessages() {
        super.onDeletedMessages();
        Log.d(TAG,"onMessageReceiveCalled");
    }

    @Override
    public void onNewToken(@NonNull  String s) {
        super.onNewToken(s);
        Log.d(TAG,"onMessageReceiveCalled");
    }
}

App.java 类

package com.example.tokenapp;


import android.app.Application;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Build;

public class App extends Application {
    public static final String CHANNEL_ID = "channel_id";

    @Override
    public void onCreate() {
        super.onCreate();
        if(Build.VERSION.SDK_INT >=Build.VERSION_CODES.O){
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID,"Channel", NotificationManager.IMPORTANCE_LOW);
            NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

            manager.createNotificationChannel(channel);
        }
    }
}

这是我的 Arduino 代码

#if defined(ESP32)
#include <WiFi.h>
#include <FirebaseESP32.h>
#elif defined(ESP8266)
#include <ESP8266WiFi.h>
#include <FirebaseESP8266.h>
#endif
const int analogInPin =A0;
int moistureValue = 0;
//Provide the token generation process info.
#include "addons/TokenHelper.h"
//Provide the RTDB payload printing info and other helper functions.
#include "addons/RTDBHelper.h"

/* 1. Define the WiFi credentials */
#define WIFI_SSID ""
#define WIFI_PASSWORD ""

#define API_KEY "API_KEY"

#define DATABASE_URL "tokenapp-ba3e5-default-rtdb.firebaseio.com" 
#define FIREBASE_FCM_SERVER_KEY ""
#define FIREBASE_FCM_DEVICE_TOKEN_1 " "
//#define FIREBASE_FCM_DEVICE_TOKEN_2 "ANOTHER_RECIPIENT_DEVICE_TOKEN"
#define USER_EMAIL "USER_EMAIL"
#define USER_PASSWORD "USER_PASSWORD"

FirebaseData fbdo;
//int counterHigh =0, counterLow =0;
void sendLowMessage();
void sendHighMessage();
FirebaseAuth auth;
FirebaseConfig config;

unsigned long sendDataPrevMillis = 0;

void setup()
{

    Serial.begin(115200);
    Serial.println();
    Serial.println();
    pinMode(D1,OUTPUT);

    WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
    Serial.print("Connecting to Wi-Fi");
    while (WiFi.status() != WL_CONNECTED)
    {
        Serial.print(".");
        delay(300);
    }
    Serial.println();
    Serial.print("Connected with IP: ");
    Serial.println(WiFi.localIP());
    Serial.println();

    Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION);
 
    Firebase.begin(DATABASE_URL, "");

    Firebase.reconnectWiFi(true);

     fbdo.fcm.begin(FIREBASE_FCM_SERVER_KEY);

    fbdo.fcm.addDeviceToken(FIREBASE_FCM_DEVICE_TOKEN_1);

   // fbdo.fcm.addDeviceToken(FIREBASE_FCM_DEVICE_TOKEN_2);

    fbdo.fcm.setPriority("low");
    fbdo.fcm.setTimeToLive(1000);

     if (!Firebase.beginStream(fbdo, "/PUMP_STATUS"))
        Serial.printf("stream begin error, %s\n\n", fbdo.errorReason().c_str());
        fbdo.setBSSLBufferSize(512, 2048);
}
void loop()
{
  moistureValue= analogRead(analogInPin);
  Serial.println("Moisture Reading = ");
  Serial.print(moistureValue);
  if (Firebase.ready() && (millis() - sendDataPrevMillis > 5000 || sendDataPrevMillis == 0))
    {
        sendDataPrevMillis = millis();
             
        Firebase.setIntAsync(fbdo, "/MOISTURE_READ", moistureValue);
        
        
    }
    if(moistureValue<300 )
    {
      
        sendLowMessage(); 
      
        
     
      }

      if(moistureValue>550 )
      {

       
           sendHighMessage();
                 
      }


     if (Firebase.ready())
    {

        if (!Firebase.readStream(fbdo))
            Serial.printf("sream read error, %s\n\n", fbdo.errorReason().c_str());

        if (fbdo.streamTimeout())
            Serial.println("stream timeout, resuming...\n");

        if (fbdo.streamAvailable())
        {
          
                          if(fbdo.stringData()== "ON"){
                           digitalWrite(D1,HIGH);
                          }
                          else{
                            digitalWrite(D1,LOW);
                          }
        }
    }  
}  




void sendHighMessage()
{
      fbdo.fcm.setCollapseKey("MyKey");
     fbdo.fcm.addCustomNotifyMessage("tag","MoistureNotification");
   
    fbdo.fcm.setNotifyMessage("Heya User", "The value of moisture in the soil is " + String(moistureValue) + "\n Please Switch ON the water pump");

    //fbdo.fcm.setDataMessage("{\"myData\":" + String(moistureValue) + "}");

    //Firebase.broadcastMessage(fbdo)
    //Firebase.sendTopic(fbdo)
    Serial.printf("Send message... %s\n", Firebase.sendMessage(fbdo, 0) ? "ok" : fbdo.errorReason().c_str());
   
    if (fbdo.httpCode() == FIREBASE_ERROR_HTTP_CODE_OK)
        Serial.println(fbdo.fcm.getSendResult());
        
    Serial.println();
    

}

void sendLowMessage()
{

      fbdo.fcm.setCollapseKey("MyKey");
     fbdo.fcm.addCustomNotifyMessage("tag","MoistureNotification");
    fbdo.fcm.setNotifyMessage("Heya User", "The value of moisture in the soil is " + String(moistureValue) + "\n Please Switch OFF the water pump");

    //fbdo.fcm.setDataMessage("{\"myData\":" + String(moistureValue) + "}");

    //Firebase.broadcastMessage(fbdo)
    //Firebase.sendTopic(fbdo)
    Serial.printf("Send message... %s\n", Firebase.sendMessage(fbdo, 0) ? "ok" : fbdo.errorReason().c_str());
       if (fbdo.httpCode() == FIREBASE_ERROR_HTTP_CODE_OK)
        Serial.println(fbdo.fcm.getSendResult());
        
    Serial.println();
}

在我的 MainActivity.java 类中,我只是检索我的设备令牌而已。

【问题讨论】:

    标签: android firebase firebase-cloud-messaging android-notifications arduino-esp8266


    【解决方案1】:

    请试试这个

    PendingIntent pendingIntent = PendingIntent.getActivity(ctx, notificationNumber, intent,PendingIntent.FLAG_UPDATE_CURRENT);
    

    请尝试从下面的链接实现这种方式可能对您有所帮助

    https://stackoverflow.com/a/68487811/4042384

    【讨论】:

      猜你喜欢
      • 2021-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多