簡體   English   中英

如何從一個 android 應用程序向其他 android 應用程序發送通知?

[英]How to send notification from one android application to other android application?

我創建了兩個不同的 android 應用程序,一個用於管理面板,它本身只有一個用戶,另一個將安裝在其他 android 設備上 當管理員在他的應用程序中添加通知時,所有用戶都會收到通知 我應該怎么辦? 如何實施?

使用 firebase FCM 將推送通知發送到 android 設備。 在這里你會發現很多選擇。 https://firebase.google.com/docs/cloud-messaging

你聽起來是個初學者,所以我先用簡單的話解釋一下。

  • 您需要一個可以觸發通知發送代碼的服務器端腳本,如果您正在運行PHP作為服務器端語言,那么您可以使用下面的代碼。
  • 然后您需要您的用戶應用程序訂閱一個主題。 主題只是一個自定義字符串。 您將使用此主題字符串向特定用戶或用戶組發送通知。
  • 從您的管理應用程序中,您需要調用服務器上可以觸發通知的PHP腳本。 我假設您已經知道如何調用PHP腳本,這與調用普通的APIDatabase中進行操作相同。

了解流程后,您需要執行以下步驟。

  • 按照教程啟動Firebase項目並獲取FCM Notification功能。 從控制台獲取 firebase api 密鑰。

  • 在您的用戶應用程序中使用以下代碼訂閱主題。 用戶登錄應用程序后,將此代碼放在ActivityonCreate方法中。 如果您希望用戶停止接收通知,請取消訂閱該主題。

     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);
  • 現在從您的管理應用程序中調用此PHP腳本。 您可以根據需要傳遞參數。 您將能夠在您的用戶應用程序中收到通知。

您可以在Android代碼中自定義通知,例如播放特定的聲音。 為此,您需要遵循我上面鏈接的官方文檔指南。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM