Today I am going to share very Important code for GCM(Google Cloud Messaging) for Android. I worked with php for back end .
My article have 3 category-
1)Creating a Google API Project
2)PHP Back-end
3)Android Front-end
Part-A Google API Project
1)Open Google API console from here
2)If you have not created any project create new project for your application-
8)Now from below window choose create button:
Part-B PHP Back-end Side
My article have 3 category-
1)Creating a Google API Project
2)PHP Back-end
3)Android Front-end
Part-A Google API Project
1)Open Google API console from here
2)If you have not created any project create new project for your application-
3)See your browser URL and note your project ID from above some thing like that-1080127563513
https://code.google.com/apis/console/#project:1080127563513
4)In the main Google APIs Console page, select Services.
5)Turn the Google Cloud Messaging toggle to ON.
6)In the Terms of Service page, accept the terms.
7)get API Key from main Google APIs Console page, select API Access. You will see a screen that resembles the following and click on Create new Server Key:
8)Now from below window choose create button:
9)From below window note your project id and api key:
Part-B PHP Back-end Side
Just copy below file and put into your php server inside ws folder-
1)GCM.php
'HI Sunil');
$url='https://android.googleapis.com/gcm/send';
$fields=array
(
'registration_ids'=>$registatoin_ids,
'data'=>$msg
);
$headers=array
(
'Authorization: key=AIzaSyA46UE7bBWXCpHSD5sbNxbRwI1MAKVI-jg',
'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_VERIFYPEER,false);
curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode($fields));
$result=curl_exec($ch);
curl_close($ch);
echo $result;
?>
1)MainActivity.java
package com.sunil.gcm.push;
import static com.sunil.gcm.push.CommonUtilities.SENDER_ID;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import com.google.android.gcm.GCMRegistrar;
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public class MainActivity extends Activity {
private String TAG = "** GCMPushDEMOAndroid**";
private TextView mDisplay;
String regId = "";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkNotNull(SENDER_ID, "SENDER_ID");
GCMRegistrar.checkDevice(this);
GCMRegistrar.checkManifest(this);
mDisplay = (TextView) findViewById(R.id.textView1);
regId = GCMRegistrar.getRegistrationId(this);
if (regId.equals("")) {
GCMRegistrar.register(this, SENDER_ID);
} else {
Log.v(TAG, "Already registered");
}
/**
* call asYnc Task
*/
new sendIdOnOverServer().execute();
mDisplay.setText("RegId=" + regId);
}
private void checkNotNull(Object reference, String name) {
if (reference == null) {
throw new NullPointerException(getString(R.string.error_config,
name));
}
}
@Override
protected void onPause() {
super.onPause();
GCMRegistrar.unregister(this);
}
public class sendIdOnOverServer extends AsyncTask{
ProgressDialog pd = null;
@Override
protected void onPreExecute() {
pd = ProgressDialog.show(MainActivity.this, "Please wait",
"Loading please wait..", true);
pd.setCancelable(true);
}
@Override
protected String doInBackground(String... params) {
try {
HttpResponse response = null;
HttpParams httpParameters = new BasicHttpParams();
HttpClient client = new DefaultHttpClient(httpParameters);
String url = "http://10.0.0.30//parsing/GCM.php?" + "�ID="
+ regId;
Log.i("Send URL:", url);
HttpGet request = new HttpGet(url);
response = client.execute(request);
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String webServiceInfo = "";
while ((webServiceInfo = rd.readLine()) != null) {
Log.d("****Status Log***", "Webservice: " + webServiceInfo);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
pd.dismiss();
}
}
}
2)GCMIntentService.java
package com.sunil.gcm.push;
import static com.sunil.gcm.push.CommonUtilities.SENDER_ID;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.google.android.gcm.GCMBaseIntentService;
public class GCMIntentService extends GCMBaseIntentService {
public GCMIntentService() {
super(SENDER_ID);
}
private static final String TAG = "===GCMIntentService===";
@Override
protected void onRegistered(Context arg0, String registrationId) {
Log.i(TAG, "Device registered: regId = " + registrationId);
}
@Override
protected void onUnregistered(Context arg0, String arg1) {
Log.i(TAG, "unregistered = " + arg1);
}
@Override
protected void onMessage(Context context, Intent intent) {
Log.i(TAG, "new message= ");
String message = intent.getExtras().getString("message");
generateNotification(context, message);
}
@Override
protected void onError(Context arg0, String errorId) {
Log.i(TAG, "Received error: " + errorId);
}
@Override
protected boolean onRecoverableError(Context context, String errorId) {
return super.onRecoverableError(context, errorId);
}
/**
* Issues a notification to inform the user that server has sent a message.
*/
private static void generateNotification(Context context, String message) {
int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
String title = context.getString(R.string.app_name);
Intent notificationIntent = new Intent(context, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(context, 0,
notificationIntent, 0);
notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);
}
}
3)CommonUtilities .java
package com.sunil.gcm.push;
public final class CommonUtilities {
//put here your sender Id
static final String SENDER_ID = "311451115764";
}







0 comments:
Post a Comment