Tuesday 16 December 2014

GCM Integration (Android App)

Hello Friends,

Here i will show code for client side android.

Manifest file


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.blogspot.longjamcode"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="19" />

<--give all these uses-permission-->
    <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="in.blogspot.longjamcode.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

    <uses-permission android:name="com.example.gcmdemo.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" />
 
 
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <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>

<--here is Receiver-->
        <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="in.blogspot.longjamcode" />
            </intent-filter>
        </receiver>
    </application>

</manifest>


Simple Layout file 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:gravity="center"
    tools:context="in.blogspot.longjamcode.MainActivity" >
<--This button is for Registering with cloud server-->
    <Button
        android:id="@+id/registerButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Register with cloud server" />
<--This button is to share RegisterId with App server-->
    <Button
        android:id="@+id/sendButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        android:text="Share register id with app server" />

</LinearLayout>

Following is MainActivity.java file


package in.blogspot.longjamcode;

import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.SSLPeerUnverifiedException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

private final String PROJECT_NUMBER = "YOUR PROJECT NUMBER";
private Button registerButton, sendButton;
private SharedPreferences preferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerButton = (Button) findViewById(R.id.registerButton);
sendButton = (Button) findViewById(R.id.sendButton);
preferences = getSharedPreferences("gcm", Context.MODE_PRIVATE);
registerButton.setOnClickListener(register);
sendButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
MyAsynClass asynClass = new MyAsynClass();
asynClass.execute("http://YOUR IP ADDRESS:8080/GCMServer/RegisterServlet");
}
});
}
OnClickListener register = new OnClickListener() {
@Override
public void onClick(View v) {

//Getting gcm_id from preference and check it whether it exist or not if not call registerWithCloudServer() method

if(preferences.getString("gcm_id", "").length() == 0) {
registerWithCloudServer();
}
else {
Toast.makeText(MainActivity.this, "Already Register", Toast.LENGTH_SHORT).show();
}
}
};

//Method to register with cloud server
public void registerWithCloudServer(){
Intent registrationIntent=new Intent("com.google.android.c2dm.intent.REGISTER");
registrationIntent.putExtra("app", PendingIntent.getBroadcast(this, 0, new Intent(), 0));
registrationIntent.putExtra("sender", PROJECT_NUMBER);
startService(registrationIntent);
}

private class MyAsynClass extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... params) {
HttpPost httpPost= new HttpPost(params[0]);
DefaultHttpClient client = new DefaultHttpClient();
try {
List<NameValuePair> list = new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair("gcm_id", preferences.getString("gcm_id", "")));
httpPost.setEntity(new UrlEncodedFormEntity(list));
HttpResponse response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
String responseText = EntityUtils.toString(entity);
return responseText;
}catch (SSLPeerUnverifiedException e) {
e.printStackTrace();
return null;
}catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
}

Following is receiver....

package in.blogspot.longjamcode;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.content.WakefulBroadcastReceiver;
import android.widget.Toast;

public class GCMBroadcastReceiver extends WakefulBroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {      
String action=intent.getAction();
if(action.equalsIgnoreCase("com.google.android.c2dm.intent.REGISTRATION")){
onRegistration(context,intent);
}else if(action.equalsIgnoreCase("com.google.android.c2dm.intent.RECEIVE")){
NotificationManager notificationManager = (NotificationManager) 
context.getSystemService(context.NOTIFICATION_SERVICE); 
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, new Intent(), Intent.FLAG_ACTIVITY_NEW_TASK);
Notification notify=new Notification(R.drawable.ic_launcher,"icon",System.currentTimeMillis());
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if(alarmSound!=null)
notify.sound = alarmSound;
notify.setLatestEventInfo(context, "Notification", intent.getExtras().getString("message"), pendingIntent);
notificationManager.notify(0, notify); 
}
}
public void onRegistration(Context context,Intent intent){
String registrationID=intent.getStringExtra("registration_id");
if(registrationID!=null){
SharedPreferences preferences = context.getSharedPreferences("gcm", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("gcm_id",registrationID);
editor.commit();
Toast.makeText(context, ""+registrationID, Toast.LENGTH_SHORT).show();
}else
Toast.makeText(context, "error in registration" , Toast.LENGTH_LONG).show();
}
}

And don't to add google-play-services-lib to your project

The output will be like


when message came it will notify on notification bar like...






No comments:

Post a Comment