简体   繁体   中英

Push Notification in Android App through GCM

I am new to android app development. Right now I am developing a simple application in which user can upload the data to the MySQL server through PHP scripts. I am successfully able to do that. But I want that whenever a user uploaded some data to server from his app then all other app user should receive the notification (ie xyz user has added a new post.).

I have found the way that I can achieve this using Google Cloud Messaging. But I am unable to implement it inside my application.

I have successfully implemented the GCM notification from the web message through a PHP script on web server using the below PHP script.

<?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>

and successfully received the notification on my device.

But I want to setup that app should automatically notify the GCM to send the message instead of using WEB scripts. And the notification should be received to all other app users.

I have also gone through the GCM DownStream and UpStream messaging but didn't understood much, not able to implement successfully.

I have tried to setup the Downstream using the below code but i didn't received the notification to my App

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);
    }
}
}

Thanks for your time.

Follow steps : 1. Get registration ID of app user's device and save it to your database.

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.Use your php code.(remove HTML part)

Note - use array of registration IDs

3.In response open this php script with registration ids.

You can have a longer method where you send the information to a php script. This php script will select all the registration ids of the users and use a foreach loop to send the notifications. This means you need to store the registration ids in your mysql database

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM