我正在开发使用本地主机的Firebase通知演示。
我使用 android studio 配置火碱库并将服务器密钥添加到我的 php 文件中,我在我的 Phpmyadmin(Wamp 服务器)中获得了令牌,但是当我使用 html 文件发送通知时,我无法收到通知。
我是安卓开发人员,所以我不知道php api。我认为这可能是send_ntification.php文件中的问题。
但是我使用Firebase控制台进行了测试,它工作正常。
这是我的php 文件
初始化.php
<?php
$host = "localhost";
$db_user = "root";
$db_password = "";
$db_name = "fcm_db";
$con = mysqli_connect($host,$db_user,$db_password,$db_name);
if($con)
echo "Connection Success";
else
echo"Connection Error.....";
?>
fcm_insert.php
<?php
require "init.php";
$fcm_token = $_POST["fcm_token"];
$sql = "insert into fcm_info values('".$fcm_token."');";
mysqli_query($con,$sql);
mysqli_close($con)
?>
send_notification.php
<?php
include_once("init.php");
$message =$_POST['message'];
$title = $_POST['title'];
$path_to_fcm = "https://fcm.googleapis.com/fcm/send";
$server_key = "MY SERVER KEY";
$sql = "select fcm_token from fcm_info";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_row($result);
$key = $row[0];
$headers = array(
'Authorization:key=' .$server_key,
'Content-Type:application/json'
);
$fields = array('to'=>$key,
'notification'=>array('title'=>$title,'body'=>$message));
$payload = json_encode($fields);
$curl_session = curl_init();
curl_setopt($curl_session, CURLOPT_URL, $path_to_fcm);
curl_setopt($curl_session, CURLOPT_POST, true);
curl_setopt($curl_session, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_session, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl_session, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
curl_setopt($curl_session, CURLOPT_POSTFIELDS, $payload);
$result = curl_exec($curl_session);
curl_close($curl_session);
mysqli_close($con);
?>
send_notificatiion.html
<html>
<body>
<form action="send_notification.php" method="post">
<table>
<tr>
<td> Title : </td> <td><input type="text" name="title"/></td>
<tr>
<tr>
<td>Message : <td><td><input type="text" name="message"/></td>
</tr>
<td><input type="submit" value="submit"/></td>
</tr>
</table>
</form>
</body>
</html>
这是我的安卓代码
FcmInstenceIdService.java
public class FcmInstenceIdService extends FirebaseInstanceIdService {
@Override
public void onTokenRefresh() {
String recent_token = FirebaseInstanceId.getInstance().getToken();
Log.e(TAG, "onTokenRefresh: token = "+recent_token );
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(getString(R.string.FCM_PREF), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(getString(R.string.FCM_TOKEN),recent_token);
editor.apply();
}
}
Fcm消息服务.java
public class FcmMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
String title = remoteMessage.getNotification().getTitle();
String message = remoteMessage.getNotification().getBody();
Intent intent = new Intent(this,MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentTitle(title);
builder.setContentText(message);
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setAutoCancel(true);
builder.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0,builder.build());
super.onMessageReceived(remoteMessage);
}
}
主活动.java
public class MainActivity extends AppCompatActivity {
SharedPreferences sharedPreferences ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void SendTokenToServer(View view) {
sharedPreferences = getApplicationContext().getSharedPreferences(getString(R.string.FCM_PREF), Context.MODE_PRIVATE);
Log.i("Notificatioin", "SendTokenToServer: token = "+sharedPreferences.getString(getString(R.string.FCM_TOKEN), ""));
new GetData().execute();
}
public class GetData extends AsyncTask<Void, Void, Void> {
ProgressDialog progressDialog;
String responseString;
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Please wait....");
progressDialog.setCancelable(true);
progressDialog.show();
}
@Override
protected Void doInBackground(Void... voids) {
sharedPreferences.getString(getString(R.string.FCM_TOKEN), "");
OkHttpClient client = new OkHttpClient();
RequestBody formBody = new FormBody.Builder()
.add("fcm_token", sharedPreferences.getString(getString(R.string.FCM_TOKEN), ""))
.build();
Request request = new Request.Builder()
// .url("http://192.168.1.104/fcmtest/fcm_insert.php")
.url("http://192.168.0.102/fcmtest/fcm_insert.php")
.post(formBody)
.build();
try {
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
{
responseString = response.body().string();
System.out.println(responseString);
response.body().close();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progressDialog.dismiss();
}
}
}
安卓清单.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.production.hometech.fcmdemo">
<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=".FcmInstenceIdService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<service android:name=".FcmMessagingService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
</application>
</manifest>
我不明白问题在哪里,请帮助我。任何帮助将不胜感激。 我花了3个小时来寻找解决方案。
好吧,由于服务器密钥和旧版服务器密钥之间的一些误解,我在 FCM 中遇到了同样的问题。
-
对于 FCM,请始终使用服务器密钥。我们错误地使用旧版服务器密钥,因为它的长度;我们在GCM中使用了那个简短的Web API密钥。
-
您需要在后端系统中使用发件人ID 才能发送推送通知;我们从未在 GCM 的后端中使用发件人ID。
按照这两个步骤操作,希望您能收到FCM的推送通知。