【问题标题】:How to send notification from one android application to other android application?如何将通知从一个安卓应用程序发送到另一个安卓应用程序?
【发布时间】:2021-07-16 07:29:06
【问题描述】:

我创建了两个不同的 android 应用程序,一个用于管理面板,它本身只有一个用户,另一个将安装在其他安卓设备。当管理员在其应用程序中添加通知时,所有用户都会收到通知。我该怎么办?如何实现?

【问题讨论】:

    标签: java android android-push-notification


    【解决方案1】:

    你听起来是个初学者,所以我先用简单的话解释一下。

    • 您需要一个可以触发通知发送代码的服务器端脚本,如果您正在运行PHP 作为您的服务器端语言,那么您可以使用我下面的代码。
    • 那么您需要您的用户 应用程序订阅一个主题。主题只是一个自定义字符串。您将使用此主题字符串向特定用户或用户组发送通知。
    • 从您的 Admin 应用程序中,您需要调用服务器上可以触发通知的 PHP 脚本。我假设您已经知道如何调用PHP 脚本,这与调用普通APIDatabase 中进行操作相同。

    知道您需要遵循以下步骤的流程。

    • 按照this 教程启动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);
      
    • 现在从您的 Admin 应用程序中调用此 PHP 脚本。您可以根据需要传递参数。您将能够在您的用户应用中收到通知。

    您可以在 Android 代码中自定义通知,例如播放特定的声音。为此,您需要遵循我上面链接的官方文档指南。

    【讨论】:

      【解决方案2】:

      使用 firebase FCM 将推送通知发送到 Android 设备。在这里你会发现很多选择。 https://firebase.google.com/docs/cloud-messaging

      【讨论】:

      • 但是我的其他应用程序能否获得这些通知?
      猜你喜欢
      • 1970-01-01
      • 2012-06-02
      • 2023-03-10
      • 2021-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-04
      • 1970-01-01
      相关资源
      最近更新 更多