【问题标题】:GCM pass variable and do somethingGCM 传递变量并做一些事情
【发布时间】:2014-03-12 09:55:40
【问题描述】:

我正在开发的应用程序可以通过 Google Cloud Messaging 接收通知。 但是现在我想知道是否可以从PHP代码中发送变量,并在后台处理它们以执行函数?

我还想知道,一旦用户单击通知,我是否可以对随通知一起发送的变量执行某些操作。

我一直在寻找一个示例,但我找不到使用 Google Cloud Messaging 的示例。 也许我没有使用正确的关键字/标签来找到它。

我很抱歉在这里问这种问题,它可能就像找到正确的东西一样简单,然后找到一个代码/项目示例。

【问题讨论】:

标签: php android google-cloud-messaging


【解决方案1】:

androidhive 教程使用已弃用的 GCM 处理方法,其 GCMIntentService 是 com.google.android.gcm.GCMBaseIntentService 包的一部分。处理 GCM 的较新方法使用 PlayServices API,其 GCMIntentService 是 com.google.android.gms.gcm.GoogleCloudMessaging 包的一部分。

但是,无论在客户端中使用哪种方法,您最终都会检查额外的意图以提取消息的元素(在 onMessage() 中用于旧方式和 onHandleIntent() 用于较新的方法)。 PHP 服务器端保持不变。

如果您使用

在这个小 php 示例中传递消息

someurl/example.php?message=这是一条消息

<?php session_start();
   require 'vals.php';
   $randomNum=rand(10,100);
   $registrationIDs[] = $regidOne;
   $message =  $_GET['message'];
   $morestuff = 'More text for you';

   $url = 'https://android.googleapis.com/gcm/send';
   $fields = array(
           'registration_ids' => $registrationIDs,
             'data' => array( "message" => $message,
                              "moredata" => $morestuff),
             'delay_while_idle'=> false,
             'time_to_live' => 86400,
             'collapse_key'=>"".$randomNum.""
            );
   $headers = array(
        'Authorization: key=' . $apiKey,
         '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 );
   curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
   curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode( $fields ));

   // Execute post
   $result = curl_exec($ch);
   // Close connection
   curl_close($ch);
   echo "Your message has been sent, the results from the Cloud Server were :\n$
   echo "<p>";
   echo $result;
?>

然后你会在客户端选择消息:

if (intent.hasExtra("message")) {
  String theMessage = intent.getStringExtra("message");
  //do something
}

并处理您所需的额外数据:

if (intent.hasExtra("moredata")) {
  String moreData = intent.getStringExtra("moredata");
  //do something else
}

通常,“做某事”可能是启动 Activity。

【讨论】:

    猜你喜欢
    • 2016-09-22
    • 2022-09-27
    • 2014-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-17
    • 2021-10-17
    • 2017-08-24
    相关资源
    最近更新 更多