首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >FCM不会立即发送数据消息

FCM不会立即发送数据消息
EN

Stack Overflow用户
提问于 2019-04-29 11:08:18
回答 1查看 1.4K关注 0票数 0

我是通过数据而不是通知发送通知的。数据的默认优先级是正常的。

当我使用admin.messaging().send()时,它甚至大部分时间都不发送。但是我不能调整admin.messaging().sendToDevice()的优先级,因为它只接受“数据”和“通知”。当我使用这个方法的时候,它根本不发送信息。我不知道send()为什么也不能工作,我想知道如何使消息具有高优先级。

测试电话:小米,中兴。

云函数代码,几乎从不发送:

代码语言:javascript
复制
 const payload = 
   {  
     "delay_while_idle": false,
      "android": 
          {
             "priority": "high",
              "ttl":0
          },
      data:
          {
           is_there_new_notification: "true"
          },
          token: token

      };

       return  admin.messaging().send(payload)
               .then((response) => {
               // Response is a message ID string.
               //console.log('Successfully sent message:', response);

                return response;
                }).catch((error) => {
               // console.log('Error sending message:', error);
                 return error;
               });

云函数代码2,不立即以打瞌睡模式发送,有时甚至在设备醒着时也不发送)

代码语言:javascript
复制
const payload =    {  
        data:
         {
            is_there_new_notification: "true"
         }

  };

  return  admin.messaging().sendToDevice(token, payload).then((response) => {
                                    // Response is a message ID string.
                                    //console.log('Successfully sent message:', response);

                                   return response;
                                    })
                                .catch((error) => {
                                  // console.log('Error sending message:', error);
                                   return error;
                                    });

编辑:

安卓服务代码:

代码语言:javascript
复制
@Override
        public void onMessageReceived(RemoteMessage remoteMessage)
            {
                super.onMessageReceived(remoteMessage);
                Log.d(TAG, "onMessageReceived: " + remoteMessage.getData());

                //This is just a string variable return "true" in string. it is being sent in order to notify there are notifications. We don't need its content.
                if(remoteMessage.getData().get(getString(R.string.notification_is_there_new_notification))!= null)
                    {
                        FirebaseMethods.checkAndShowIfThereAreNotifications(context);
                    }
            }

AndroidManifest:

代码语言:javascript
复制
 <service
            android:name=".FirebaseFCMService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

相关资源:

https://firebase.google.com/docs/cloud-messaging/concept-options https://developer.android.com/training/monitoring-device-state/doze-standby.html

EN

回答 1

Stack Overflow用户

发布于 2019-05-01 07:04:23

尝试通过代码发送通知,这对我来说很好。请参考下列代码:

FCM.java

代码语言:javascript
复制
public class FCM {

final static private String FCM_URL = "https://fcm.googleapis.com/fcm/send";

/**
 * 
 * 
 * 
 * Method to send push notification to Android FireBased Cloud messaging
 * Server.
 * 
 * 
 * 
 * @param tokenId
 *            Generated and provided from Android Client Developer
 * 
 * @param server_key
 *            Key which is Generated in FCM Server
 * 
 * @param message
 *            which contains actual information.
 * 
 * 
 * 
 */

static void send_FCM_Notification(String tokenId, String server_key, String message, String req) {

    try {

        // Create URL instance.

        URL url = new URL(FCM_URL);

        // create connection.

        HttpURLConnection conn;

        conn = (HttpURLConnection) url.openConnection();

        conn.setUseCaches(false);

        conn.setDoInput(true);

        conn.setDoOutput(true);

        // set method as POST or GET

        conn.setRequestMethod("POST");

        // pass FCM server key

        conn.setRequestProperty("Authorization", "key=" + server_key);

        // Specify Message Format

        conn.setRequestProperty("Content-Type", "application/json");

        // Create JSON Object & pass value

        JSONObject infoJson = new JSONObject();

        //infoJson.put("title", "Here is your notification.");

        infoJson.put("body", message);

        infoJson.put("msg", req);

        JSONObject json = new JSONObject();

        json.put("to", tokenId.trim());

        //json.put("notification", infoJson);

        json.put("data", infoJson);
        json.put("priority", "high");
        json.put("time_to_live",5);


        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());

        wr.write(json.toString());

        wr.flush();

        int status = 0;

        if (null != conn) {

            status = conn.getResponseCode();

        }

        if (status != 0) {

            if (status == 200) {

                // SUCCESS message

                BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

                Log.d("ResultData","Android Notification Response : " + reader.readLine());

            } else if (status == 401) {

                // client side error

                Log.d("ResultData","401 Notification Response : TokenId : " + tokenId + " Error occurred :");

            } else if (status == 501) {

                // server side error

                Log.d("ResultData","Notification Response : [ errorCode=ServerError ] TokenId : " + tokenId);

            } else if (status == 503) {

                // server side error

                Log.d("ResultData","Notification Response : FCM Service is Unavailable  TokenId : " + tokenId);

            }

        }

    } catch (MalformedURLException mlfexception) {

        // Prototcal Error

        Log.d("ResultData","Error occurred while sending push Notification!.." + mlfexception.getMessage());

    } catch (IOException mlfexception) {

        // URL problem

        Log.d("ResultData",
                "Reading URL, Error occurred while sending push Notification!.." + mlfexception.getMessage());

    } catch (JSONException jsonexception) {

        // Message format error

        Log.d("ResultData",
                "Message Format, Error occurred while sending push Notification!.." + jsonexception.getMessage());

    } catch (Exception exception) {

        // General Error or exception.

        Log.d("ResultData","Error occurred while sending push Notification!.." + exception.getMessage());

    }

}

TestActivity.java

代码语言:javascript
复制
public class TestActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.test_act);

    String tokenId;// your token ID
    String server_key; //you server key ;
    String message;// Your message

    FCM.send_FCM_Notification( tokenId,server_key,message,"Reply");
}
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55902080

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档