Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/182.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 通过GCM在Android应用程序中推送通知_Php_Android_Push Notification_Google Cloud Messaging - Fatal编程技术网

Php 通过GCM在Android应用程序中推送通知

Php 通过GCM在Android应用程序中推送通知,php,android,push-notification,google-cloud-messaging,Php,Android,Push Notification,Google Cloud Messaging,我是android应用程序开发新手。现在我正在开发一个简单的应用程序,用户可以通过PHP脚本将数据上传到MySQL服务器。我成功地做到了这一点。但我希望,每当用户从其应用程序向服务器上传一些数据时,所有其他应用程序用户都应该收到通知(即xyz用户添加了一个新帖子) 我已经找到了使用谷歌云信息实现这一目标的方法。但我无法在我的应用程序中实现它 我已经使用下面的PHP脚本通过web服务器上的PHP脚本成功地实现了来自web消息的GCM通知 <?php //Generic php functio

我是android应用程序开发新手。现在我正在开发一个简单的应用程序,用户可以通过PHP脚本将数据上传到MySQL服务器。我成功地做到了这一点。但我希望,每当用户从其应用程序向服务器上传一些数据时,所有其他应用程序用户都应该收到通知(即xyz用户添加了一个新帖子)

我已经找到了使用谷歌云信息实现这一目标的方法。但我无法在我的应用程序中实现它

我已经使用下面的PHP脚本通过web服务器上的PHP脚本成功地实现了来自web消息的GCM通知

<?php
//Generic php function to send GCM push notification
function sendMessageThroughGCM($registatoin_ids, $message) {
    //Google cloud messaging GCM-API url
    $url = 'https://android.googleapis.com/gcm/send';
    $fields = array(
        'registration_ids' => $registatoin_ids,
        'data' => $message,
    );
    // Update your Google Cloud Messaging API Key
    define("GOOGLE_API_KEY", "AIzaSyCVQRSnEoulXoG21uKua1DTrOUvMkxbK-U");        
    $headers = array(
        'Authorization: key=' . GOOGLE_API_KEY,
        'Content-Type: application/json'
    );
    $ch = curl_init();
    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_VERIFYHOST, 0);   
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
    $result = curl_exec($ch);               
    if ($result === FALSE) {
        die('Curl failed: ' . curl_error($ch));
    }
    curl_close($ch);
    return $result;
}
?>
<?php

//Post message to GCM when submitted
$pushStatus = "GCM Status Message will appear here";    
if(!empty($_GET["push"])) { 
    $gcmRegID  = file_get_contents("GCMRegId.txt");
    $pushMessage = $_POST["message"];   
    if (isset($gcmRegID) && isset($pushMessage)) {      
        $gcmRegIds = array($gcmRegID);
        $message = array("m" => $pushMessage);  
        $pushStatus = sendMessageThroughGCM($gcmRegIds, $message);
    }       
}

//Get Reg ID sent from Android App and store it in text file
if(!empty($_GET["shareRegId"])) {
    $gcmRegID  = $_POST["regId"]; 
    file_put_contents("GCMRegId.txt",$gcmRegID);
    echo "Done!";
    exit;
}   
?>
<html>
<head>
    <title>Google Cloud Messaging (GCM) in PHP</title>
    <style>
        div#formdiv, p#status{
        text-align: center;
        background-color: #FFFFCC;
        border: 2px solid #FFCC00;
        padding: 10px;
        }
        textarea{
        border: 2px solid #FFCC00;
        margin-bottom: 10px;            
        text-align: center;
        padding: 10px;
        font-size: 25px;
        font-weight: bold;
        }
        input{
        background-color: #FFCC00;
        border: 5px solid #fff;
        padding: 10px;
        cursor: pointer;
        color: #fff;
        font-weight: bold;
        }

    </style>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script>
    $(function(){
        $("textarea").val("");
    });
    function checkTextAreaLen(){
        var msgLength = $.trim($("textarea").val()).length;
        if(msgLength == 0){
            alert("Please enter message before hitting submit button");
            return false;
        }else{
            return true;
        }
    }
    </script>
</head>
<body>
    <div id="formdiv">
    <h1>Google Cloud Messaging (GCM) in PHP</h1>    
    <form method="post" action="/swach/gcm/gcm.php/?push=true" onsubmit="return checkTextAreaLen()">                                                                          
            <textarea rows="5" name="message" cols="45" placeholder="Message to send via GCM"></textarea> <br/>
            <input type="submit"  value="Send Push Notification through GCM" />
    </form>
    </div>
    <p id="status">
    <?php echo $pushStatus; ?>
    </p>        
</body>
</html>

PHP中的谷歌云消息(GCM)
div#formdiv,p#status{
文本对齐:居中;
背景色:#FFFFCC;
边框:2个实心#FFCC00;
填充:10px;
}
文本区{
边框:2个实心#FFCC00;
边缘底部:10px;
文本对齐:居中;
填充:10px;
字体大小:25px;
字体大小:粗体;
}
输入{
背景色:#FFCC00;
边框:5px实心#fff;
填充:10px;
光标:指针;
颜色:#fff;
字体大小:粗体;
}
$(函数(){
$(“textarea”).val(“”);
});
函数checkTextAreaLen(){
var msgLength=$.trim($(“textarea”).val()).length;
如果(msgLength==0){
警报(“请在点击提交按钮前输入消息”);
返回false;
}否则{
返回true;
}
}
PHP中的谷歌云消息(GCM)

并在我的设备上成功接收到通知

但是我想设置应用程序应该自动通知GCM发送消息,而不是使用WEB脚本。 并且该通知应发送给所有其他应用程序用户

我也经历了GCM下游和上游消息传递,但不太了解,无法成功实施

我尝试使用下面的代码设置下游,但我没有收到应用程序的通知

public class AddNewMessage extends Activity{
private Integer msgId;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_new_message);

    msgId = 1;

}
// OnClick Action to the button inside the Activity Layout
public void sendNewMessage(View view) {
    final GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
    if (view == findViewById(R.id.send_message)) {
        new AsyncTask<Void,Void,String>() {


            @Override
            protected String doInBackground(Void... params) {
                String msg = "";
                try {
                    Bundle data = new Bundle();
                    data.putString("my_message", "Hello World");
                    data.putString("my_action","SAY_HELLO");
                    String id = Integer.toString(msgId);
                    gcm.send(ApplicationConstants.GOOGLE_PROJ_ID + "@gcm.googleapis.com", id, data);
                    msg = "Sent message";
                } catch (IOException ex) {
                    msg = "Error :" + ex.getMessage();
                }
                return msg;
            }

            @Override
            protected void onPostExecute(String msg) {
                Toast.makeText(AddNewMessage.this, "send message failed: " + msg, Toast.LENGTH_LONG).show();
            }
        }.execute(null, null, null);
    }
}
}
public类AddNewMessage扩展活动{
私有整数msgId;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u add\u new\u消息);
msgId=1;
}
//在“活动”布局内的按钮上单击“操作”
公共void sendNewMessage(查看){
final GoogleCloudMessaging gcm=GoogleCloudMessaging.getInstance(this);
if(view==findviewbyd(R.id.send_message)){
新建异步任务(){
@凌驾
受保护字符串doInBackground(无效…参数){
字符串msg=“”;
试一试{
Bundle data=新Bundle();
putString(“我的消息”,“你好世界”);
putString(“我的动作”,“说你好”);
字符串id=Integer.toString(msgId);
发送(ApplicationConstants.GOOGLE_PROJ_ID+“@gcm.googleapis.com”,ID,数据);
msg=“已发送消息”;
}捕获(IOEX异常){
msg=“错误:”+ex.getMessage();
}
返回味精;
}
@凌驾
受保护的void onPostExecute(字符串msg){
Toast.makeText(AddNewMessage.this,“发送消息失败:”+msg,Toast.LENGTH_LONG.show();
}
}.执行(空,空,空);
}
}
}
谢谢您的时间。

请按照以下步骤操作: 1.获取应用程序用户设备的注册ID并将其保存到数据库中

private String getRegistrationId(Context context) 
{
   final SharedPreferences prefs = getGCMPreferences(context);
   String registrationId = prefs.getString(PROPERTY_REG_ID, "");
   if (registrationId.isEmpty()) {
       Log.d(TAG, "Registration ID not found.");
       return "";
   }
   int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
   int currentVersion = getAppVersion(context);
   if (registeredVersion != currentVersion) {
        Log.d(TAG, "App version changed.");
        return "";
    }
    return registrationId;
}
2.使用php代码。(删除HTML部分)

注意-使用注册ID数组


3.作为响应,请使用注册ID打开此php脚本。

您可以使用更长的方法将信息发送到php脚本。此php脚本将选择用户的所有注册ID,并使用foreach循环发送通知。这意味着您需要将注册ID存储在mysql数据库中

您得到了什么响应?请查看。它们处理服务器设置的大部分问题。它们有一个简单的功能,并且支持很棒的用户体验操作,比如全局解雇和跟踪通知是否被打开或解雇。以下是一个例子: