Saturday, July 27, 2013

GCM_Registration_Example

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />
<permission android:name="com.kundan.gcmproject.permission.C2D_MESSAGE" 
    android:protectionLevel="signature" />
<uses-permission android:name="com.kundan.gcmproject.permission.C2D_MESSAGE" /> 
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" /> 
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.kundan.gcmproject.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>
    <receiver android:name=".MyBroadcastReceiver" 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="com.kundan.gcmproject" />
  </intent-filter>
</receiver>
    </application>

</manifest>


ActivityMain.java
--------------------
package com.kundan.gcmproject;

import android.os.Bundle;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
Button btn1,btn2;
TextView tv;
public static final String SenderID="1096002802846";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1=(Button) findViewById(R.id.button1);
btn2=(Button) findViewById(R.id.button2);
tv=(TextView) findViewById(R.id.textView2);
btn1.setOnClickListener(new OnClickListener() {

public void onClick(View v) {

Intent registrationIntent = new Intent("com.google.android.c2dm.intent.REGISTER");

registrationIntent.putExtra("app", PendingIntent.getBroadcast(v.getContext(), 0, new Intent(), 0));
registrationIntent.putExtra("sender",SenderID);
startService(registrationIntent);
System.out.println("**********"+MyBroadcastReceiver.registrationId);
tv.setText(MyBroadcastReceiver.registrationId);
Log.i("button", "button press");
}
});
        
        btn2.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
Intent unregIntent = new Intent("com.google.android.c2dm.intent.UNREGISTER");
unregIntent.putExtra("app", PendingIntent.getBroadcast(v.getContext(), 0, new Intent(), 0));
startService(unregIntent);

}
});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}


}

MyBroadcastReceiver.java
-------------------------------
package com.kundan.gcmproject;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class MyBroadcastReceiver extends BroadcastReceiver{
String data1,data2;
Context ctx;
public static String registrationId;
public static String error;
public static String unregistered;
@Override
public void onReceive(Context context, Intent intent) {
ctx = context;
try {
            String action = intent.getAction();
            if (action.equals("com.google.android.c2dm.intent.REGISTRATION")) {
                handleRegistration(intent);
            } else if (action.equals("com.google.android.c2dm.intent.RECEIVE")) {
               handleMessage(intent);
            }
        } finally {
           
           
        }
}
@SuppressWarnings("deprecation")
private void handleRegistration(Intent intent) {
       registrationId = intent.getStringExtra("registration_id");
       error = intent.getStringExtra("error");
       unregistered = intent.getStringExtra("unregistered");       
       // registration succeeded
       if (registrationId != null) {
        new MyFileaccess().Load_Data("REGID", registrationId, ctx);
       
        NotificationManager mNotificationManager = (NotificationManager)ctx.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = new Notification(R.drawable.ic_launcher,"Registration Successful", System.currentTimeMillis());
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        Intent i = new Intent(ctx, MainActivity.class);
        PendingIntent activity = PendingIntent.getActivity(ctx, 0, i, 0);
        notification.setLatestEventInfo(ctx, "Registration Success", registrationId, activity);        
        mNotificationManager.notify(0, notification);
       
          
       }            
      
       if (unregistered != null) {
        new MyFileaccess().Load_Data("REGID","0", ctx);
        NotificationManager mNotificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = new Notification(R.drawable.ic_launcher,"UnRegistration Successful", System.currentTimeMillis());
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notification.number += 1;
        PendingIntent activity = PendingIntent.getActivity(ctx, 0, null, 0);
        notification.setLatestEventInfo(ctx, "UnRegistration Success", unregistered, activity);
        mNotificationManager.notify(0, notification);
       
           
       }            
       
       if (error != null) {
           if ("SERVICE_NOT_AVAILABLE".equals(error)) {
            NotificationManager mNotificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = new Notification(R.drawable.ic_launcher,"Error", System.currentTimeMillis());
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notification.number += 1;
        PendingIntent activity = PendingIntent.getActivity(ctx, 0, null, 0);
        notification.setLatestEventInfo(ctx, "Error in registration", error, activity);
        mNotificationManager.notify(0, notification);              
             
           } else {
              
              
           }
       }
   }
@SuppressWarnings("deprecation")
private void handleMessage(Intent intent) {        
       String data1 = intent.getStringExtra("data1");
       String data2 = intent.getStringExtra("data2");
       
   NotificationManager mNotificationManager = (NotificationManager)ctx.getSystemService(Context.NOTIFICATION_SERVICE);
      Notification notification = new Notification(R.drawable.ic_launcher,"Message recieved from server", System.currentTimeMillis());
      notification.flags |= Notification.FLAG_AUTO_CANCEL;
      notification.number += 1;
      Intent i = new Intent(ctx, MainActivity.class);
      PendingIntent activity = PendingIntent.getActivity(ctx, 0, i, 0);
      notification.setLatestEventInfo(ctx,data1, data2, activity);
      mNotificationManager.notify(0, notification);
      
   }

}

MyFileaccess.java
----------------------
package com.kundan.gcmproject;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.content.Context;

public class MyFileaccess {
@SuppressWarnings("static-access")
public void Load_Data(String filename, String Datastring, Context context) {
FileOutputStream fos;

try {
fos = context.openFileOutput(filename, context.MODE_PRIVATE);
fos.write(Datastring.getBytes());
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block

} catch (IOException e) {
// TODO Auto-generated catch block

}

}
public String get_Data(String filename,Context context)
{
FileInputStream f = null;
String temp="";
try {
f= context.openFileInput(filename);
int n = f.available();
for(int i=0;i<n;i++)
{
temp=temp+(char)f.read();
}
f.close();
}catch (IOException e)
{
}
return temp;
}

}

activity_main.xml
------------------------
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/RelativeLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textView1"
        android:textColor="#990000"
      
        android:text=" "
        android:textAppearance="?android:attr/textAppearanceSmall" />

    <Button
        android:id="@+id/button1"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button2"
        android:layout_below="@+id/textView2"
        android:layout_marginTop="73dp"
        android:text="Activate" />

    <Button
        android:id="@+id/button2"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView2"
        android:layout_below="@+id/button1"
        android:text="Deactivate" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="17dp"
        android:text="Your Reg IDs is..."
        android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>




No comments:

Post a Comment