Friday 10 May 2013

Push notification Example

1) create a java file named C2DM_To_GCM.java
=============================
package com.mrs.aspi_motors;

import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class C2DM_To_GCM {
   
    public static final String TAG="GCM";
    public static final String REGISTER_ACTION="com.google.android.c2dm.intent.REGISTER";
    public static final String RECEIVE_ACTION="com.google.android.c2dm.intent.RECEIVE";
    public static final String REGISTRATION_ACTION="com.google.android.c2dm.intent.REGISTRATION";
   
    public static final class REGISTER{
        public static final String APP="app";
        public static final String SENDER="sender";
        /**GCM Project ID (Sender id)*/
//        public static final String PROJECT_ID="103628028734";
        public static final String PROJECT_ID=Constant.PUSH_NOTIFICATION.PROJECT_ID;
        public static final String REGISTRATION_ID="registration_id";
    }
   
    public static final class RECEIVE{
        public static final String MESSAGE=Constant.PUSH_NOTIFICATION_RECEIVE_KEY.MESSAGE;
//        public static final String TITLE = "title";
//        public static final String DESCRIPTION = "discription";
//        public static final String DATE = "date";
        public static final String KEY = Constant.PUSH_NOTIFICATION_RECEIVE_KEY.KEY;
        public static final String TITLE = Constant.PUSH_NOTIFICATION_RECEIVE_KEY.TITLE;
        public static final String DESC = Constant.PUSH_NOTIFICATION_RECEIVE_KEY.DESC;
        public static final String DATE = Constant.PUSH_NOTIFICATION_RECEIVE_KEY.DATE;
        public static final String CAR_CHASIS_NUMBER = Constant.PUSH_NOTIFICATION_RECEIVE_KEY.CAR_CHASIS_NUMBER;
        public static final String BRAND = Constant.PUSH_NOTIFICATION_RECEIVE_KEY.BRNAD;
        public static final String PRODUCT = Constant.PUSH_NOTIFICATION_RECEIVE_KEY.PRODUCT;
        public static final String MODEL = Constant.PUSH_NOTIFICATION_RECEIVE_KEY.MODEL;
    }
   
    public static void GCM_Register(Context context){
        Intent mIntent = new Intent(REGISTER_ACTION);
        mIntent.putExtra(REGISTER.APP, PendingIntent.getBroadcast(context, 0, new Intent(), 0));
//        Sender currently not used[This changes for different users]
        mIntent.putExtra(REGISTER.SENDER,REGISTER.PROJECT_ID);
        context.startService(mIntent);
        Log.e(C2DM_To_GCM.TAG,"Registration Action");
    }
}
2)create a java file named C2DMMessageReceiver.java
=================================
package com.mrs.aspi_motors;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

public class C2DMMessageReceiver extends BroadcastReceiver
{
    private String Date= "";
    private String Title= "";
    private String Desc= "";
    private String Message= "";
    private String strChassisNumber = "";
    private String strBrand = "";
    private String strProduct = "";
    private String strModel = "";
   
    @Override
    public void onReceive(Context context, Intent intent)
    {
        //obtain the action of the intent that is broadcasted to this application
        String ACTION = intent.getAction();
        //compare the action with the desired action
        if (C2DM_To_GCM.RECEIVE_ACTION.equalsIgnoreCase(ACTION))
        {
            /*the data is sent from the app server to the c2dm server in a key/value pair fashion
             * that is sent again to the application in the same fashion in the form of an intent
             * The data is obtained from the intent by specifying the appropriate keys used in the
             * server*/
            String Message = intent.getStringExtra(C2DM_To_GCM.RECEIVE.MESSAGE);
            String Key = intent.getStringExtra(C2DM_To_GCM.RECEIVE.KEY);
           
            Title = intent.getStringExtra(C2DM_To_GCM.RECEIVE.TITLE);
            Desc = intent.getStringExtra(C2DM_To_GCM.RECEIVE.DESC);
            Date = intent.getStringExtra(C2DM_To_GCM.RECEIVE.DATE);
            strChassisNumber = intent.getStringExtra(C2DM_To_GCM.RECEIVE.CAR_CHASIS_NUMBER);
            strBrand = intent.getStringExtra(C2DM_To_GCM.RECEIVE.BRAND);
            strProduct = intent.getStringExtra(C2DM_To_GCM.RECEIVE.PRODUCT);
            strModel = intent.getStringExtra(C2DM_To_GCM.RECEIVE.MODEL);
           
            String Res="Response Title = " + Title + " Desc = " + Desc + "Date = " +Date;
            Log.e(C2DM_To_GCM.TAG,Res);
            //Toast.makeText(context, Res, Toast.LENGTH_SHORT).show();
            createNotification(context, Res);
        }
    }
   
    public void createNotification(Context context, String notify){
        NotificationManager notificationManager = (NotificationManager)context.getSystemService(context.NOTIFICATION_SERVICE);
        Notification notification = new Notification(R.drawable.ic_logo, Constant.PUSH_NOTIFICATION.INSURANCE_NOTIFICATION_TITLE, System.currentTimeMillis());
        notification.flags |= Notification.FLAG_SHOW_LIGHTS;
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notification.defaults = notification.DEFAULT_ALL;
        Intent intent = new Intent(context,Popup_Notification.class);
        intent.putExtra(Constant.POP_UP_NOTIFICATION.KEY_TITLE, Title);
        intent.putExtra(Constant.POP_UP_NOTIFICATION.KEY_DATE, Date);
        intent.putExtra(Constant.POP_UP_NOTIFICATION.KEY_DESCRIPTION, Desc);
        intent.putExtra(Constant.POP_UP_NOTIFICATION.KEY_CHASSIS_NUMBER, strChassisNumber);
        intent.putExtra(Constant.POP_UP_NOTIFICATION.KEY_BRAND, strBrand);
        intent.putExtra(Constant.POP_UP_NOTIFICATION.KEY_PRODUCT, strProduct);
        intent.putExtra(Constant.POP_UP_NOTIFICATION.KEY_MODEL, strModel);
        intent.setAction(String.valueOf(System.currentTimeMillis()));
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
        notification.setLatestEventInfo(context, context.getResources().getString(R.string.app_name).toString(), Constant.PUSH_NOTIFICATION.INSURANCE_NOTIFICATION_MESSAGE, pendingIntent);
        notificationManager.notify((int) System.currentTimeMillis(), notification);
    }
}

3)create a java file named C2DMRegistrationReceiver.java
===================================
package com.mrs.aspi_motors;

import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import com.mrs.aspi_motors.C2DM_To_GCM.REGISTER;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.provider.Settings.Secure;
import android.util.Log;
import android.widget.Toast;

public class C2DMRegistrationReceiver extends BroadcastReceiver {
    private CommanClass mCommanClass = null;
    private String strMessage = null;
    private String strUserId = null;
    private SharedPreferences mSharedPreferencesRead=null;
    private String strDeviceID = null;
    private String strRegisterID = null;
    @Override
    public void onReceive(Context context, Intent intent) {
        mCommanClass = new CommanClass();
        mSharedPreferencesRead = context.getSharedPreferences(Constant.SHAREDPREFERENCES.SHAREDPREFERENCE, context.MODE_WORLD_READABLE);
        strUserId = mSharedPreferencesRead.getString(Constant.LOGIN_SHAREPREFERENCE.LS_USER_ID, "");
       
        String ACTION = intent.getAction();
        if (C2DM_To_GCM.REGISTRATION_ACTION.equalsIgnoreCase(ACTION)){
            String RegistrationId = intent.getStringExtra(REGISTER.REGISTRATION_ID);
            Log.e(C2DM_To_GCM.TAG, "RegistrationId = " + RegistrationId);

            strRegisterID = intent.getStringExtra(REGISTER.REGISTRATION_ID);
            Log.e(C2DM_To_GCM.TAG, "RegistrationId = " + RegistrationId);
            //Toast.makeText(context, "Register Successfully.", Toast.LENGTH_SHORT).show();
            strDeviceID = Secure.getString(context.getContentResolver(),Secure.ANDROID_ID);
            if(strRegisterID!= null){
                new GET_GCM_REGISTERATION_ID().execute("");
            }
        }
    }
   
    //************************************************************************************************************************************
    //This class is used for get Add appointment
        private class GET_GCM_REGISTERATION_ID extends AsyncTask<String, String, String>
        {
             protected String doInBackground(String... params){
                    String strURL = (Constant.PUSH_NOTIFICATION.C2DM_REGISTRATION_URL);                   
                     ArrayList<NameValuePair> mNameValuePair = new ArrayList<NameValuePair>();
                    mNameValuePair.add(new BasicNameValuePair(Constant.C2DM_REGISTRATION_REQUEST.ID, strUserId.toString()));
                    mNameValuePair.add(new BasicNameValuePair(Constant.C2DM_REGISTRATION_REQUEST.DEVICEID, strDeviceID.toString()));
                    mNameValuePair.add(new BasicNameValuePair(Constant.C2DM_REGISTRATION_REQUEST.REGISTERID, strRegisterID.toString()));
                    System.out.println("Add AppintmentName Value ==="+mNameValuePair.toString());
                    return mCommanClass.PostConnection(strURL, mNameValuePair); 
             }
             protected void onPostExecute(String result){
                 if(result!=null){   
                     System.out.println("GCM Regiasteration Response====="+result.toString());
                     try {
                        JSONObject mJSONOBJECT = new JSONObject(result);
                        String strType = mJSONOBJECT.getString(Constant.JSON.TYPE);
                    
                         if(strType.equalsIgnoreCase(Constant.JSON.OK)){
//                             JSONObject mJSONOBJECT_RESULT = mJSONOBJECT.getJSONObject(Constant.JSON.RESULT);
//                            strMessage = mJSONOBJECT_RESULT.getString(Constant.C2DM_REGISTRATION_RESPONSE.MESSAGE);
                        }
                       
                    } catch (Exception e) {
                        e.printStackTrace();
                    }                           
                 }  
                 else{
                    //Toast.makeText(this,Constant.SERVERCONNERROR, Toast.LENGTH_SHORT).show();    
                 }
                 super.onPostExecute(result);
             }                
        }
}
4)create a java file named  Popup_Notification.java
==============================
package com.mrs.aspi_motors;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class Popup_Notification extends Activity{

    private TextView Heading = null;
    private TextView Date = null;
    private TextView Msg = null;
    private TextView txtChassisNumber = null;
    private TextView txtBrand = null;
    private TextView txtProduct = null;
    private TextView txtModel = null;
    private Button SHOW_HISTORY = null;
    private ImageView CLOSE = null;
    private String strTitle = null;
    private String strDate = null;
    private String strDiscription = null;
    private String strChasisNumber = null;
    private String strBrand = null;
    private String strProduct= null;
    private String strModel = null;
    private String btn_val = null;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);   
        setContentView(R.layout.popup_notification_mob);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
      
        get_Init();
        set_Data();
    }
       
    private void get_Init() {
        Heading = (TextView) findViewById(R.id.NOTIFICATION_HEAD);   
        Date = (TextView) findViewById(R.id.DATE);       
        Msg = (TextView) findViewById(R.id.NOTIFICATION_MSG);   
        txtChassisNumber = (TextView)findViewById(R.id.txtChasisNumber);
        txtBrand = (TextView)findViewById(R.id.txtBrand);
        txtProduct = (TextView)findViewById(R.id.txtProduct);
        txtModel = (TextView)findViewById(R.id.txtModel);
       
        CLOSE = (ImageView) findViewById(R.id.CLOSE);
        CLOSE.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
       
        SHOW_HISTORY = (Button) findViewById(R.id.SHOW_HISTORY);
        SHOW_HISTORY.setOnClickListener(new OnClickListener() {
           
            @Override
            public void onClick(View v) {
                Intent mIntent = new Intent(Popup_Notification.this, InsuranceHistory.class);
                startActivity(mIntent);
                finish();
            }
        });
       
    }
   
    private void set_Data(){
        strTitle = getIntent().getStringExtra(Constant.POP_UP_NOTIFICATION.KEY_TITLE);
        strDiscription = getIntent().getStringExtra(Constant.POP_UP_NOTIFICATION.KEY_DESCRIPTION);
        strDate = getIntent().getStringExtra(Constant.POP_UP_NOTIFICATION.KEY_DATE);
        strChasisNumber = getIntent().getStringExtra(Constant.POP_UP_NOTIFICATION.KEY_CHASSIS_NUMBER);
        strBrand = getIntent().getStringExtra(Constant.POP_UP_NOTIFICATION.KEY_BRAND);
        strProduct = getIntent().getStringExtra(Constant.POP_UP_NOTIFICATION.KEY_PRODUCT);
        strModel = getIntent().getStringExtra(Constant.POP_UP_NOTIFICATION.KEY_MODEL);
       
        Heading.setText(strTitle);
        Date.setText(strDate);
        Msg.setText(strDiscription);
        txtChassisNumber.setText(" : "+strChasisNumber);
        txtBrand.setText(" : "+strBrand);
        txtProduct.setText(" : "+strProduct);
        txtModel.setText(" : "+strModel);
       
    }
}
5)write in constant
============
    public static final class PUSH_NOTIFICATION_RECEIVE_KEY{
        public static final String MESSAGE="message";
        public static final String KEY="key";
        public static final String TITLE="title";
        public static final String DESC="description";
        public static final String DATE="due_date";
        public static final String CAR_CHASIS_NUMBER="car_chasis_number";
        public static final String BRNAD="brand";
        public static final String PRODUCT="product";
        public static final String MODEL="model";
    }
    public static final class PUSH_NOTIFICATION{
        //KEY = AIzaSyC-CbNfTi9Jmm1Wvtv2Aks96_qlD-rXjFM/
        public static final String C2DM_REGISTRATION_URL = "http://192.168.0.103/php-projects/aspi_cms/api/c2dm_registration/";
        public static final String PROJECT_ID = "484482594029";
        public final static String UPDATE_DATE = "Update Date";
        public final static String UPDATED_DT = "updated_dt";
        public final static String INSURANCE_NOTIFICATION_TITLE = "Insurance Notification";
        public final static String INSURANCE_NOTIFICATION_MESSAGE = "Insurance Notification";
    }
    //for pass intent in popup notitfication screen
    public static final class POP_UP_NOTIFICATION{
        public static final String KEY_TITLE= "title";
        public static final String KEY_DESCRIPTION= "description";
        public static final String KEY_DATE= "due_date";
        public static final String KEY_CHASSIS_NUMBER= "car_chasis_number";
        public static final String KEY_BRAND= "brand";
        public static final String KEY_PRODUCT= "product";
        public static final String KEY_MODEL= "model";
        public static final String KEY_MESSAGE= "message";
        public static final String KEY_PUSH_MSG_FUN= "push_message";
    }
   // id/226/deviceid/2345/registerid/abcd
    public static final class C2DM_REGISTRATION_REQUEST{
        public static final String ID = "id";
        public static final String DEVICEID = "deviceid";
        public static final String REGISTERID = "registerid";
    }
    public static final class C2DM_REGISTRATION_RESPONSE{
        public static final String MESSAGE = "Message";
    }

6) create xml file named popup_notification_mob.xml
================================
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#90000000"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="20dip"
    android:id="@+id/ll_pop_hot">
    <LinearLayout
        android:layout_width="270dp"
        android:layout_height="270dp"
        android:background="@drawable/bg_light"
        android:orientation="vertical" >
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_margin="5dip"
            android:background="@drawable/bg_light"
            android:orientation="vertical">
           <LinearLayout
               android:layout_width="fill_parent"
               android:layout_height="wrap_content"
               android:orientation="horizontal" >
                <TextView
                    android:id="@+id/NOTIFICATION_HEAD"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:focusable="false"
                    android:focusableInTouchMode="false"
                    android:text="HEADING"
                    android:textColor="@color/BLACK"
                    android:textSize="18sp"
                    android:textStyle="bold"/>
                <ImageView
                    android:id="@+id/CLOSE"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/close_hd"
                    android:layout_gravity="right|top"/>
           </LinearLayout>
           <LinearLayout
               android:layout_width="fill_parent"
               android:layout_height="wrap_content"
               android:orientation="horizontal" >
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/chasis_number"
                    android:textColor="@color/BLACK"
                    android:textSize="14sp" />
               <TextView
                    android:id="@+id/txtChasisNumber"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="2323232"
                    android:textColor="@color/BLACK"
                    android:textSize="14sp" />
           </LinearLayout>
           <LinearLayout
               android:layout_width="fill_parent"
               android:layout_height="wrap_content"
               android:orientation="horizontal" >
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/brand"
                    android:textColor="@color/BLACK"
                    android:textSize="14sp" />
               <TextView
                    android:id="@+id/txtBrand"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="2323232"
                    android:textColor="@color/BLACK"
                    android:textSize="14sp" />
           </LinearLayout>
           <LinearLayout
               android:layout_width="fill_parent"
               android:layout_height="wrap_content"
               android:orientation="horizontal" >
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/Product"
                    android:textColor="@color/BLACK"
                    android:textSize="14sp" />
               <TextView
                    android:id="@+id/txtProduct"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="2323232"
                    android:textColor="@color/BLACK"
                    android:textSize="14sp" />
           </LinearLayout>
           <LinearLayout
               android:layout_width="fill_parent"
               android:layout_height="wrap_content"
               android:orientation="horizontal" >
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/model"
                    android:textColor="@color/BLACK"
                    android:textSize="14sp" />
               <TextView
                    android:id="@+id/txtModel"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="2323232"
                    android:textColor="@color/BLACK"
                    android:textSize="14sp" />
           </LinearLayout>
            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:orientation="vertical" >
                <ScrollView
                            android:layout_width="fill_parent"
                            android:layout_height="fill_parent">
                <TextView
                    android:id="@+id/NOTIFICATION_MSG"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:scrollbars="vertical"
                    android:layout_marginTop="5dip"
                    android:text="Notification Data"
                    android:textColor="@color/BLACK"
                    android:textSize="18sp" />
                </ScrollView>
            </LinearLayout>
             <TextView
                    android:id="@+id/DATE"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="16-Apr-2013"
                    android:textColor="@color/BLACK"
                    android:textSize="14sp"
                    android:layout_gravity="right"
                    android:layout_marginBottom="10dip"/>      
            <Button
                android:id="@+id/SHOW_HISTORY"
                android:layout_width="180dip"
                android:layout_height="40dip"
                android:layout_gravity="bottom|center_horizontal"
                android:gravity="center"
                android:layout_marginLeft="1dip"
                android:background="@color/BLUE" 
                android:text="@string/insurance_history_button"             
                android:textColor="@color/WHITE"
                android:textSize="18sp" />
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

7)in manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ovte.gcm" android:versionCode="1" android:versionName="1.0">
   
    <uses-sdk android:minSdkVersion="8" />
   
    <permission android:name="com.ovte.gcm.permission.C2D_MESSAGE"
                android:protectionLevel="signature" />
   
    <uses-permission android:name="com.ovte.gcm.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.VIBRATE"/>

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".Popup_Notification"
                  android:label="@string/app_name"
                  android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name=".C2DMRegistrationReceiver"
            android:permission="com.google.android.c2dm.permission.SEND">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.REGISTRATION"></action>
                <category android:name="com.ovte.gcm" />
            </intent-filter>
        </receiver>

        <receiver android:name=".C2DMMessageReceiver"
            android:permission="com.google.android.c2dm.permission.SEND">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE"></action>
                <category android:name="com.ovte.gcm" />
            </intent-filter>
        </receiver>
    </application>
</manifest>

No comments:

Post a Comment