我一直在互联网上发现问题为什么Android Studio中的模拟器没有收到来自我的PHP backend_API或Firebase控制台的通知,但大多数都没有解决我的问题。有很多关于Firebase在前台/后台没有收到通知的问题。但我的问题是onMessageReceived
根本没有被调用,我甚至没有在Firebase的任何情况下成功收到任何回复或通知,但我100%确定我可以从Firebase获得令牌。
我能够从PHP后端获得成功响应。但是再一次,Firebase从来没有任何通知!
{"multicast_id":5857046882374247095,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1490047410456686%14ffa3cf14ffa3cf"}]}
我使用各种方法在前景或背景上测试了大约50次。我也尝试过其他几个教程,他们只是无法对我工作。我已经使用断点测试onMessageReceived
,在Android监视器上观察网络状态(0 kb / s flat =无响应),在网上搜索。没运气!!!
我使用的代码基本上与我在Youtube上获得的教程100%相似,他的Android模拟器确实收到了通知,但不是我的相同代码。有人能帮帮我吗?我花了3天但仍无济于事。
FirebaseMessagingService.java
public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService{
private static final String TAG = "succcess";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
String title = remoteMessage.getData().get("title");
String body = remoteMessage.getData().get("body");
Log.i(TAG, title);
showNotification(title, body);
}
private void showNotification(String title, String body) {
Intent i = new Intent(this,MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,i,PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setContentTitle(title)
.setContentText(body)
.setSmallIcon(R.mipmap.ic_launcher)
.setAutoCancel(true)
.setContentIntent(pendingIntent);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(0,builder.build());
}
}
FirebaseInstanceIDService.java
public final class FirebaseInstanceIdReceiver extends WakefulBroadcastReceiver {
public FirebaseInstanceIdReceiver() {
}
public void onReceive(Context var1, Intent var2) {
if(this.isOrderedBroadcast()) {
this.setResultCode(500);
}
var2.setComponent((ComponentName)null);
var2.setPackage(var1.getPackageName());
if(VERSION.SDK_INT <= 18) {
var2.removeCategory(var1.getPackageName());
}
String var3 = var2.getStringExtra("gcm.rawData64");
if(var3 != null) {
var2.putExtra("rawData", Base64.decode(var3, 0));
var2.removeExtra("gcm.rawData64");
}
String var4 = null;
String var5 = var2.getStringExtra("from");
if(!"com.google.android.c2dm.intent.REGISTRATION".equals(var2.getAction()) && !"google.com/iid".equals(var5) && !"gcm.googleapis.com/refresh".equals(var5)) {
if("com.google.android.c2dm.intent.RECEIVE".equals(var2.getAction())) {
var4 = "com.google.firebase.MESSAGING_EVENT";
} else {
Log.d("FirebaseInstanceId", "Unexpected intent");
}
} else {
var4 = "com.google.firebase.INSTANCE_ID_EVENT";
}
int var6 = -1;
if(var4 != null) {
var6 = this.zza(var1, var4, var2);
}
if(this.isOrderedBroadcast()) {
this.setResultCode(var6);
}
}
public int zza(Context var1, String var2, Intent var3) {
return zzg.zzabT().zzb(var1, var2, var3);
}
}
的AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.project.firebasepushnotification23">
<uses-permission android:name="android.permission.INTERNET"/>
<application
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">
<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=".FirebaseMessagingService">
<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>
</application>
</manifest>
App Level Gradel
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
applicationId "com.project.firebasepushnotification23"
minSdkVersion 23
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.3.0'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12'
compile 'com.google.firebase:firebase-core:10.2.0'
compile 'com.google.firebase:firebase-messaging:10.2.0'
compile 'com.squareup.okhttp3:okhttp:3.2.0'
}
apply plugin: 'com.google.gms.google-services'
PHP服务器脚本1
<?php
include "con.php";
$message = array("title" => "Title", "body" => "body");
function fetchFirebaseTokenUsers($message, $connect) {
$query = "SELECT token FROM notification";
$fcmRegIds = array();
if($query_run = mysqli_query($connect, $query)) {
while($query_row = mysqli_fetch_assoc($query_run)) {
array_push($fcmRegIds, $query_row['token']);
}
}
if(isset($fcmRegIds)) {
foreach ($fcmRegIds as $key => $token) {
$pushStatus = sendPushNotification($token, $message);
}
}
}
function sendPushNotification($registration_ids, $message) {
ignore_user_abort();
ob_start();
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array(
'to' => $registration_ids,
'data' => $message,
);
define('GOOGLE_API_KEY', 'Key');
$headers = array(
'Authorization:key='.GOOGLE_API_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if($result === false)
die('Curl failed ' . curl_error());
curl_close($ch);
return $result;
ob_flush();
}
echo $return = fetchFirebaseTokenUsers($message, $connect);
?>
PHP Server Script 2
<?php
include "con.php";
function send_notification ($tokens, $message, $messagebody)
{
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array(
'registration_ids' => $tokens,
'notification' => $message,
'data' => $messagebody
);
$headers = array(
'Authorization:key = Key',
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
curl_close($ch);
return $result;
}
$sql = "select token from notification";
$result = mysqli_query($connect,$sql);
$tokens = array();
if(mysqli_num_rows($result) > 0 ){
while ($row = mysqli_fetch_assoc($result)) {
$tokens[] = $row['token']; }
}
mysqli_close($connect);
$message = array("title" => "Title", "body" => "body");
$messagebody = array("title" => "Title", "body" => "body");
$message_status = send_notification($tokens, $message, $messagebody);
echo $message_status;
?>
答案 0 :(得分:0)
使用大学/公司网络与FCM合作时,您应参考documentation中的说明:
如果您的组织有防火墙限制进出互联网的流量,则需要将其配置为允许与FCM连接,以便Firebase云消息传递客户端应用程序接收邮件。要打开的端口是:5228,5229和5230.FCM通常仅使用5228,但有时使用5229和5230.FCM不提供特定的IP,因此您应该允许防火墙接受包含的所有IP地址的传出连接在Google的ASN 15169中列出的IP块中。
或者只是使用您自己的不阻止FCM的连接。