android - Google Cloud messaging with java EE -


is there tutorial documented code regarding google cloud messaging using java ee one..

http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/

using php. making chat application using websockets in android. have working code android websocket endpoint class interaction. problem how use gcm in current enviroment.

please guide

it's best gcm tutorial ever:

http://javapapers.com/android/google-cloud-messaging-gcm-for-android-and-push-notifications/

php server code:

    <?php         //generic php function send gcm push notification        function sendpushnotificationtogcm($registatoin_ids, $message) {             //google cloud messaging gcm-api url             $url = 'https://android.googleapis.com/gcm/send';             $fields = array(                 'registration_ids' => $registatoin_ids,                 'data' => $message,             );             // google cloud messaging gcm api key             define("google_api_key", "aizasyda5dllinmwvsjeutihv0u7mab82mcszbu");                     $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          //this block post message gcm on-click         $pushstatus = "";            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 = sendpushnotificationtogcm($gcmregids, $message);             }                }          //this block receive gcm regid external (mobile apps)         if(!empty($_get["shareregid"])) {             $gcmregid  = $_post["regid"];              file_put_contents("gcmregid.txt",$gcmregid);             echo "ok!";             exit;         }        ?>     <html>         <head>             <title>google cloud messaging (gcm) server in php</title>         </head>         <body>             <h1>google cloud messaging (gcm) server in php</h1>              <form method="post" action="gcm.php/?push=1">                                                                 <div>                                                     <textarea rows="2" name="message" cols="23" placeholder="message transmit via gcm"></textarea>                 </div>                 <div><input type="submit"  value="send push notification via gcm" /></div>             </form>             <p><h3><?php echo $pushstatus; ?></h3></p>                 </body>     </html> 

or java server:

index.jsp:

    <!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">     <html xmlns="http://www.w3.org/1999/xhtml">     <%         string pushstatus = "";         object pushstatusobj = request.getattribute("pushstatus");          if (pushstatusobj != null) {             pushstatus = pushstatusobj.tostring();         }     %>     <head>     <title>google cloud messaging (gcm) server in php</title>     </head>     <body>          <h1>google cloud messaging (gcm) server in java</h1>          <form action="gcmnotification" method="post">              <div>                 <textarea rows="2" name="message" cols="23"                     placeholder="message transmit via gcm"></textarea>             </div>             <div>                 <input type="submit" value="send push notification via gcm" />             </div>         </form>         <p>             <h3>                 <%=pushstatus%>             </h3>         </p>     </body>     </html> 

gcmnotification.java:

    import java.io.bufferedreader;     import java.io.filereader;     import java.io.ioexception;     import java.io.printwriter;      import javax.servlet.servletexception;     import javax.servlet.annotation.webservlet;     import javax.servlet.http.httpservlet;     import javax.servlet.http.httpservletrequest;     import javax.servlet.http.httpservletresponse;      import com.google.android.gcm.server.message;     import com.google.android.gcm.server.result;     import com.google.android.gcm.server.sender;      @webservlet("/gcmnotification")     public class gcmnotification extends httpservlet {         private static final long serialversionuid = 1l;          // put google api server key here         private static final string google_server_key = "aizasyda5dllinmwvsjeutihv0u7mab82mcszbu";         static final string message_key = "message";              public gcmnotification() {             super();         }          protected void doget(httpservletrequest request,                 httpservletresponse response) throws servletexception, ioexception {             dopost(request, response);          }          protected void dopost(httpservletrequest request,                 httpservletresponse response) throws servletexception, ioexception {               result result = null;              string share = request.getparameter("shareregid");              // gcm redgid of android device send push notification             string regid = "";             if (share != null && !share.isempty()) {                 regid = request.getparameter("regid");                 printwriter writer = new printwriter("gcmregid.txt");                 writer.println(regid);                 writer.close();                 request.setattribute("pushstatus", "gcm regid received.");                 request.getrequestdispatcher("index.jsp")                         .forward(request, response);             } else {                  try {                     bufferedreader br = new bufferedreader(new filereader(                             "gcmregid.txt"));                     regid = br.readline();                     br.close();                     string usermessage = request.getparameter("message");                     sender sender = new sender(google_server_key);                     message message = new message.builder().timetolive(30)                             .delaywhileidle(true).adddata(message_key, usermessage).build();                     system.out.println("regid: " + regid);                     result = sender.send(message, regid, 1);                     request.setattribute("pushstatus", result.tostring());                 } catch (ioexception ioe) {                     ioe.printstacktrace();                     request.setattribute("pushstatus",                             "regid required: " + ioe.tostring());                 } catch (exception e) {                     e.printstacktrace();                     request.setattribute("pushstatus", e.tostring());                 }                 request.getrequestdispatcher("index.jsp")                         .forward(request, response);             }         }     } 

for gcm on device side these thing required:

  1. google play services in sdk
  2. google apis
  3. google play services lib project android dependency
  4. google project id

in androidmanifest.xml:

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="yourpkgname" android:versioncode="1" android:versionname="1.0" >  <uses-permission android:name="android.permission.internet" /> <uses-permission android:name="android.permission.get_accounts" /> <uses-permission android:name="android.permission.wake_lock" />  <permission     android:name="yourpkgname.permission.c2d_message"     android:protectionlevel="signature" />  <uses-permission android:name="yourpkgname.permission.c2d_message" /> <uses-permission android:name="com.google.android.c2dm.permission.receive" /> <uses-permission android:name="android.permission.access_network_state" /> <uses-permission android:name="android.permission.vibrate" />  <uses-sdk     android:minsdkversion="9"     android:targetsdkversion="16" />  <application     android:icon="@drawable/ic_launcher"     android:label="@string/app_name" >     ...     <receiver         android:name=".gcmbroadcastreceiver"         android:permission="com.google.android.c2dm.permission.send" >         <intent-filter>             <action android:name="com.google.android.c2dm.intent.receive" />             <action android:name="com.google.android.c2dm.intent.registration" />             <category android:name="yourpkgname" />         </intent-filter>     </receiver>      <service android:name=".gcmnotificationintentservice" /> </application>  </manifest> 

gcmnotificationintentservice.java:

import android.app.intentservice; import android.app.notificationmanager; import android.app.pendingintent; import android.content.context; import android.content.intent; import android.os.bundle; import android.os.systemclock; import android.support.v4.app.notificationcompat; import android.util.log;  import com.google.android.gms.gcm.googlecloudmessaging;  public class gcmnotificationintentservice extends intentservice {      public static final int notification_id = 1;     private notificationmanager mnotificationmanager;     notificationcompat.builder builder;      public gcmnotificationintentservice() {         super("gcmintentservice");     }      public static final string tag = "gcmnotificationintentservice";      @override     protected void onhandleintent(intent intent) {         bundle extras = intent.getextras();         googlecloudmessaging gcm = googlecloudmessaging.getinstance(this);          string messagetype = gcm.getmessagetype(intent);          if (!extras.isempty()) {             if (googlecloudmessaging.message_type_send_error                     .equals(messagetype)) {                 sendnotification("send error: " + extras.tostring());             } else if (googlecloudmessaging.message_type_deleted                     .equals(messagetype)) {                 sendnotification("deleted messages on server: "                         + extras.tostring());             } else if (googlecloudmessaging.message_type_message                     .equals(messagetype)) {                  (int = 0; < 3; i++) {                     log.i(tag,                             "working... " + (i + 1) + "/5 @ "                                     + systemclock.elapsedrealtime());                     try {                         thread.sleep(5000);                     } catch (interruptedexception e) {                     }                  }                 log.i(tag, "completed work @ " + systemclock.elapsedrealtime());                  sendnotification("message received google gcm server: "                         + extras.get(config.message_key));                 log.i(tag, "received: " + extras.tostring());             }         }         gcmbroadcastreceiver.completewakefulintent(intent);     }      private void sendnotification(string msg) {         log.d(tag, "preparing send notification...: " + msg);         mnotificationmanager = (notificationmanager)                 .getsystemservice(context.notification_service);          pendingintent contentintent = pendingintent.getactivity(this, 0,                 new intent(this, mainactivity.class), 0);          notificationcompat.builder mbuilder = new notificationcompat.builder(                 this).setsmallicon(r.drawable.gcm_cloud)                 .setcontenttitle("gcm notification")                 .setstyle(new notificationcompat.bigtextstyle().bigtext(msg))                 .setcontenttext(msg);          mbuilder.setcontentintent(contentintent);         mnotificationmanager.notify(notification_id, mbuilder.build());         log.d(tag, "notification sent successfully.");     } } 

gcmbroadcastreceiver.java:

import android.app.activity; import android.content.componentname; import android.content.context; import android.content.intent; import android.support.v4.content.wakefulbroadcastreceiver;  public class gcmbroadcastreceiver extends wakefulbroadcastreceiver {      @override     public void onreceive(context context, intent intent) {         componentname comp = new componentname(context.getpackagename(),                 gcmnotificationintentservice.class.getname());         startwakefulservice(context, (intent.setcomponent(comp)));         setresultcode(activity.result_ok);     } } 

so need call registerinbackground() method , send regid server:

    private void registerinbackground() {         new asynctask() {             @override             protected string doinbackground(void... params) {                 string msg = "";                 try {                     if (gcm == null) {                         gcm = googlecloudmessaging.getinstance(context);                     }                     regid = gcm.register(config.google_project_id);                     log.d("registeractivity", "registerinbackground - regid: "                             + regid);                     msg = "device registered, registration id=" + regid;                     //save in preferences , send server                     storeregistrationid(context, regid);                 } catch (ioexception ex) {                     msg = "error :" + ex.getmessage();                     log.d("registeractivity", "error: " + msg);                 }                 log.d("registeractivity", "asynctask completed: " + msg);                 return msg;             }              @override             protected void onpostexecute(string msg) {                 toast.maketext(getapplicationcontext(),                         "registered gcm server." + msg, toast.length_long)                         .show();             }         }.execute(null, null, null);     } 

example of sending regid server:

    public string shareregidwithappserver(final context context, final string regid) {          string result = "";         map paramsmap = new hashmap();         paramsmap.put("regid", regid);         try {             url serverurl = null;             try {                 serverurl = new url(config.app_server_url);             } catch (malformedurlexception e) {                 log.e("apputil", "url connection error: " + config.app_server_url, e);                 result = "invalid url: " + config.app_server_url;             }             stringbuilder postbody = new stringbuilder();             iterator> iterator = paramsmap.entryset().iterator();              while (iterator.hasnext()) {                 entry param = iterator.next();                 postbody.append(param.getkey()).append('=').append(param.getvalue());                 if (iterator.hasnext()) {                     postbody.append('&');                 }             }             string body = postbody.tostring();             byte[] bytes = body.getbytes();             httpurlconnection httpcon = null;             try {                 httpcon = (httpurlconnection) serverurl.openconnection();                 httpcon.setdooutput(true);                 httpcon.setusecaches(false);                 httpcon.setfixedlengthstreamingmode(bytes.length);                 httpcon.setrequestmethod("post");                 httpcon.setrequestproperty("content-type", "application/x-www-form-urlencoded;charset=utf-8");                 outputstream out = httpcon.getoutputstream();                 out.write(bytes);                 out.close();                 int status = httpcon.getresponsecode();                 if (status == 200) {                     result = "regid shared application server. regid: " + regid;                 } else {                     result = "post failure." + " status: " + status;                 }             } {                 if (httpcon != null) {                     httpcon.disconnect();                 }             }          } catch (ioexception e) {             result = "post failure. error in sharing app server.";             log.e("apputil", "error in sharing app server: " + e);         }         return result;     } 

Comments

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -