【发布时间】:2021-07-16 07:29:06
【问题描述】:
我创建了两个不同的 android 应用程序,一个用于管理面板,它本身只有一个用户,另一个将安装在其他安卓设备。当管理员在其应用程序中添加通知时,所有用户都会收到通知。我该怎么办?如何实现?
【问题讨论】:
标签: java android android-push-notification
我创建了两个不同的 android 应用程序,一个用于管理面板,它本身只有一个用户,另一个将安装在其他安卓设备。当管理员在其应用程序中添加通知时,所有用户都会收到通知。我该怎么办?如何实现?
【问题讨论】:
标签: java android android-push-notification
你听起来是个初学者,所以我先用简单的话解释一下。
PHP 作为您的服务器端语言,那么您可以使用我下面的代码。PHP 脚本。我假设您已经知道如何调用PHP 脚本,这与调用普通API 在Database 中进行操作相同。知道您需要遵循以下步骤的流程。
按照this 教程启动Firebase 项目并获取FCM Notification 功能。 从控制台获取 firebase api 密钥。
在您的 用户 应用程序中,使用以下代码订阅主题。用户登录应用程序后,将此代码放在Activity 的onCreate 方法中。如果您希望用户停止接收通知,请取消订阅该主题。
FirebaseMessaging.getInstance().subscribeToTopic("your topic name here"); //to subscribe
FirebaseMessaging.getInstance().unsubscribeFromTopic("your topic name here"); //to unsubscribe
将此代码放在PHP 文件中,您需要调用它来触发通知。
define('FIREBASE_API_KEY', 'your firebase api key');
$title = "this will display as notification title";
$body = "subject of notification";
$topic = "your topic name";
$message["title"] = $title;
$message["body"] = $body;
$fields = array(
'to' => '/topics/'.$topic,
'notification' => $message,
);
// Set POST variables
$url = 'https://fcm.googleapis.com/fcm/send';
$headers = array(
'Authorization: key=' . FIREBASE_API_KEY,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// Execute post
$result='';
if($title!=null){
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
}
// Close connection
curl_close($ch);
现在从您的 Admin 应用程序中调用此 PHP 脚本。您可以根据需要传递参数。您将能够在您的用户应用中收到通知。
您可以在 Android 代码中自定义通知,例如播放特定的声音。为此,您需要遵循我上面链接的官方文档指南。
【讨论】:
使用 firebase FCM 将推送通知发送到 Android 设备。在这里你会发现很多选择。 https://firebase.google.com/docs/cloud-messaging
【讨论】: