【发布时间】:2017-03-20 22:09:26
【问题描述】:
我一直在互联网上发现问题,为什么我在 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>
应用级分级
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 服务器脚本 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;
?>
【问题讨论】:
-
嗨维克森。今后,请始终为您的服务器密钥保密。 :) 话虽如此,如果您尝试使用主题,情况是否相同?该行为是仅使用模拟器还是您也在实际设备上测试过?
-
@AL。谢谢你的提醒。是的,我也尝试过该主题,但效果不佳。在使用 FirebaseMessaging.getInstance().subscribe() 方法订阅主题后,我可以让主题出现在 Firebase 控制台中,但是通过从 Firebase 发送带有主题的通知,我根本没有收到任何通知。我没有要测试的实际设备,我只在 Android Studio Emulator 上测试它。 API 16、API 23 和 API 24。从未成功过。 :(
-
嗨。那很奇怪。如果连主题都不起作用,那么要么是接收消息的代码有问题,要么是令牌混淆了。尽可能在实际设备上进行测试。
-
您使用的网络也有可能阻止了通知。
-
天啊@AL。感谢您的回答和提醒,我的大学 wifi 完全阻止了我的 Android 模拟器从 Firebase 接收通知的能力。使用其他 wifi 网络后,它工作正常。
标签: android firebase firebase-cloud-messaging firebase-notifications