google app engine - How to implement a GCM Hello World for Android using Android Studio -
i have been searching days how implement google cloud messaging android, i'm serious doubts it.
i mean, apparently google put informations online, here , here, i'm confused logic. 1 page talks client side, , server side. great, how bind of together? how implement http and/or xmpp protocol communicate gcm connection server(s)?
i implement basic helloworld gcm, work following steps:
1. app send message (say "helloworld") gcm; 2. receive message gcm , add textview.
what steps needed achieve basic app?
thank you,
if have read 2 links in question , understood gcm key concepts, can refer following sample codes:
of course, let's assume have finished:
- create project , server api key @ google developers console
- set permissions in androidmanifest files
<uses-permission android:name="android.permission.internet" />
server side:
public class mainactivity extends appcompatactivity { private textview mtextview; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); mtextview = (textview) findviewbyid(r.id.textview); new gcmrequest().execute(); } ... private class gcmrequest extends asynctask<void, void, string> { @override protected string doinbackground(void... voids) { final string api_key = "..."; // api key saved on app server gives app server authorized access google services final string client_reg_id = "..."; //an id issued gcm connection servers client app allows receive messages final string postdata = "{ \"registration_ids\": [ \"" + client_reg_id + "\" ], " + "\"delay_while_idle\": true, " + "\"data\": {\"tickertext\":\"my ticket\", " + "\"contenttitle\":\"my title\", " + "\"message\": \"test gcm message gcmserver-android\"}}"; try { url url = new url("https://android.googleapis.com/gcm/send"); httpurlconnection urlconnection = (httpurlconnection) url.openconnection(); urlconnection.setdoinput(true); urlconnection.setdooutput(true); urlconnection.setrequestmethod("post"); urlconnection.setrequestproperty("content-type", "application/json"); urlconnection.setrequestproperty("authorization", "key=" + api_key); outputstream outputstream = new bufferedoutputstream(urlconnection.getoutputstream()); bufferedwriter writer = new bufferedwriter(new outputstreamwriter(outputstream, "utf-8")); writer.write(postdata); writer.flush(); writer.close(); outputstream.close(); int responsecode = urlconnection.getresponsecode(); inputstream inputstream; if (responsecode < httpurlconnection.http_bad_request) { inputstream = urlconnection.getinputstream(); } else { inputstream = urlconnection.geterrorstream(); } bufferedreader bufferedreader = new bufferedreader(new inputstreamreader(inputstream)); string temp, response = ""; while ((temp = bufferedreader.readline()) != null) { response += temp; } return response; } catch (ioexception e) { e.printstacktrace(); return e.tostring(); } } @override protected void onpostexecute(string message) { super.onpostexecute(message); if (mtextview != null) { try { jsonobject jsonobject = new jsonobject(message); mtextview.settext(jsonobject.tostring(5)); } catch (jsonexception e) { e.printstacktrace(); mtextview.settext(e.tostring()); } } } } }
client-side:
mainactivity.java:
public class mainactivity extends appcompatactivity { private final context mcontext = this; private final string sender_id = "..."; // project number @ https://console.developers.google.com/project/... private final string shard_pref = "com.example.gcmclient_preferences"; private final string gcm_token = "gcmtoken"; public static textview mtextview; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); sharedpreferences appprefs = mcontext.getsharedpreferences(shard_pref, context.mode_private); string token = appprefs.getstring(gcm_token, ""); if (token.isempty()) { try { getgcmtoken(); } catch (exception e) { e.printstacktrace(); } } mtextview = (textview) findviewbyid(r.id.textview); } ... private void getgcmtoken() { new asynctask<void, void, void>() { @override protected void doinbackground(void... params) { try { instanceid instanceid = instanceid.getinstance(mcontext); string token = instanceid.gettoken(sender_id, googlecloudmessaging.instance_id_scope, null); if (token != null && !token.isempty()) { sharedpreferences appprefs = mcontext.getsharedpreferences(shard_pref, context.mode_private); sharedpreferences.editor prefseditor = appprefs.edit(); prefseditor.putstring(gcm_token, token); prefseditor.apply(); } log.i("gcm", token); } catch (ioexception e) { e.printstacktrace(); } return null; } }.execute(); } }
gcmservice.java:
public class gcmservice extends gcmlistenerservice { @override public void onmessagereceived(string from, bundle data) { jsonobject jsonobject = new jsonobject(); set<string> keys = data.keyset(); (string key : keys) { try { jsonobject.put(key, data.get(key)); } catch (jsonexception e) { e.printstacktrace(); } } try { sendnotification("received: " + jsonobject.tostring(5)); } catch (jsonexception e) { e.printstacktrace(); } } @override public void ondeletedmessages() { sendnotification("deleted messages on server"); } @override public void onmessagesent(string msgid) { sendnotification("upstream message sent. id=" + msgid); } @override public void onsenderror(string msgid, string error) { sendnotification("upstream message send error. id=" + msgid + ", error" + error); } private void sendnotification(final string msg) { handler handler = new handler(looper.getmainlooper()); handler.post(new runnable() { @override public void run() { if (mainactivity.mtextview != null) { mainactivity.mtextview.settext(msg); } } }); } }
androidmanifest.xml:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.gcmandroid" > <uses-permission android:name="android.permission.internet" /> <uses-permission android:name="android.permission.get_accounts" /> <uses-permission android:name="android.permission.wake_lock" /> <uses-permission android:name="com.google.android.c2dm.permission.receive" /> <permission android:name="com.example.gcm.permission.c2d_message" android:protectionlevel="signature" /> <uses-permission android:name="com.example.gcm.permission.c2d_message" /> <application android:allowbackup="true" android:fullbackupcontent="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/apptheme" > <receiver android:name="com.google.android.gms.gcm.gcmreceiver" android:exported="true" android:permission="com.google.android.c2dm.permission.send" > <intent-filter> <action android:name="com.google.android.c2dm.intent.registration" /> <action android:name="com.google.android.c2dm.intent.receive" /> <category android:name="com.example.gcm" /> </intent-filter> </receiver> <service android:name=".gcmservice" android:exported="false"> <intent-filter> <action android:name="com.google.android.c2dm.intent.receive" /> </intent-filter> </service> <activity android:name=".mainactivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> </application> </manifest>
Comments
Post a Comment