Android Gcm Basic Implementation

Android GCM basic implementation

this is incorrect

protected GCMIntentService( String senderId ) {         
super(senderId);}

As it states in the documentation. you must declare a PUBLIC, NO ARGUMENT constructor for GCMIntentService. Otherwise the GCMIntentService can't be instantiated properly by background intent services.

public GCMIntentService(){
super(senderID);}

the senderID can be a hard coded constant string because it will no longer change with the new GCM.
It's also very important you use the correct senderID. 24 hours is long enough for yours to be active so if my above solution doesn't work you are using the incorrect senderID. Everything else looks great.

The senderID is in the URL of your web browser when you are browsing the Google API access page. Click on GCM and a 12 digit number will be present in the browser URL. That is the correct key to use. NOT your API key. That is used on the App server side.

Implementation of GCM in Android

Make variables registration_ids and data to public in Content class.

public class Content implements Serializable {
public List<String> registration_ids;
public Map<String,String> data;

as jackson api reads the public variables from class or public getter/setters and in your case the variables are not public and also you didn't provide getter/setters, so the exception is.

Hope it'll work.

How to implement a GCM Hello World for Android using Android Studio

If you have read the two links in your question and understood GCM key concepts, then you can refer to the following sample codes:

Of course, let's assume that you have finished:

  • Create a project and its server API key at Google Developers Console
  • Set permissions in your AndroidManifest files like this <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 = "..."; // An API key saved on the app server that gives the app server authorized access to Google services
final String CLIENT_REG_ID = "..."; //An ID issued by the GCM connection servers to the client app that allows it to 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 from 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 at 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();
for (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>

android GCM implementation

TO receive the Notification you need to override the onMessage method from GCMIntentService class as follows

@Override
protected void onMessage(Context arg0, Intent arg1) {

Log.d("GCM", "RECIEVED A MESSAGE");
// Get the data from intent and send to notificaion bar
generateNotification(arg0, arg1.getStringExtra("**mymsg**"));
}

here "mymsg" should me match with your php message attribute. Please Note that both name should be same in php and in android otherwise you will not receive the notification.

Android GCM example - how to implement in existing project?

Hello I found what happened, I've forgotten this in Main


@Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
new IntentFilter(QuickstartPreferences.REGISTRATION_COMPLETE));
}

@Override
protected void onPause() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
super.onPause();
}

How to setup Google Cloud Messaging for Android?

If you want to execute $ant war command:

  1. first you need to download and install Apache Ant on your computer.
  2. Then you should configurate your PATH and JAVA_HOME variables like it is described here (into "Installing Apache Ant" section).
  3. And only after that you can execute ant war command into Windows command line (prompt).
    After ant war command .war file will be created.
  4. then you can deploy and run your .war file on tomcat server for example. (create Java EE project, then download and install tomcat server, configurate paths, and run your project on tomcat server...)

Adding Google Cloud Messagin (GCM) for Android - Registration process

Is my answer with source code at your question How to implement a GCM Hello World for Android using Android Studio is not enough for you to create two simple GCM projects (server-side and client-side) yet? :)

Of course, the sample code I used is just for a very basic case "server app sends, client app receives and displays message".

To sum up, you need to do the following steps:

  1. Create a new project at Google Developers Console . At this
    step, for simplicity, you just need to take note of 2 values: Project Number, which
    will be used as SENDER_ID in my client project; and API server key (created at Credentials), which
    will be used as API_KEY in my server project.
  2. Create a new simple Android project for server side (with basic source code as my answer in your previous question).
  3. Create a new simple Android project for client side (with basic source code as my answer in your previous question, I customized from the original source at Google Cloud Messaging - GitHub).
  4. Run the client app, you will get the registration token (means that your device has successfully registered). Then, paste (hard-code) this token at CLIENT_REGISTRATION_TOKEN variable in server app.
  5. Run the server app, and check the result (client app received the message or not)

Hope this helps!

P/S: I don't use any appengine-web.xml file



Related Topics



Leave a reply



Submit