Thursday, 28 March 2013

How To Send GCM Push Notification + Android


Step 1:Get your application ID and Sender ID from https://code.google.com/apis/console/

Step 2:Get Device ID using Sender ID in device  following way




/*
 * Copyright 2012 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

  • Add permission into your menifiest

     <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  
        <uses-permission android:name="android.permission.WAKE_LOCK" />

    <permission
        android:name="com.app.getgcmkey.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <uses-permission android:name="com.app.getgcmkey.permission.C2D_MESSAGE" />

  • Add below Receiver and Service into your menifiest

 <receiver
            android:name="com.google.android.gcm.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="com.app.getgcmkey" />
            </intent-filter>
        </receiver>
       
       
         <service android:name="GCMIntentService" >
        </service>
        


 Here com.app.getgcmkey is your application package name
  • Add gcm.jar from Android SDK into your libs folder

  • Add GCMIntentService service into your application package


package com.app.getgcmkey;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gcm.GCMBaseIntentService;


public class GCMIntentService extends GCMBaseIntentService {

    @SuppressWarnings("hiding")
    private static final String TAG = "GCMIntentService";

    public GCMIntentService() {
        super("senderid");
    }

    @Override
    protected void onError(Context arg0, String arg1) {
        // TODO Auto-generated method stub

    }

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

       
        // Get the data from intent and send to notificaion bar
        String response = arg1.getStringExtra("message");
        Log.e("GCM:received", response);
        try {
           
           
        //    Toast.makeText(getApplicationContext(), response, 1).show();

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    @Override
    protected void onRegistered(Context arg0, String registrationId) {
       
        // TODO Auto-generated method stub
        if (registrationId != null) {
        Log.d("regid",registrationId);
       
        }
    }

    @Override
    protected void onUnregistered(Context arg0, String arg1) {
        // TODO Auto-generated method stub
        //Logger.logger("unregistered", arg1);
    }

}

  • Write code to get GCM ID in your activity/service
public void getGCMDeviceID()  {
      
        GCMRegistrar.checkDevice(this);
        GCMRegistrar.checkManifest(this);

        if (GCMRegistrar.isRegistered(this)) {
            Log.d("info", GCMRegistrar.getRegistrationId(this));
        }
      
        String regId = GCMRegistrar.getRegistrationId(this);
      
        if (regId.equals("")) {
            // replace this with the project ID
            GCMRegistrar.register(this, "909849023929");
          
          
          
          
          
            regId = GCMRegistrar.getRegistrationId(this);
            Log.e("info:regid",   regId);
        } else {
            Log.e("info:regid", "already registered as" + regId);
        }
      
   
   
    }


Server side code: Dot Net 3.5 using web service

using System;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Net;
using System.Text;
using System.IO;

 [WebMethod]
    public string SendNotification(string deviceId, string message)
    {
        string GoogleAppID = "your app id;
        // 
        var SENDER_ID = "sender id";

        var value = message;
        WebRequest tRequest;
        tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
        tRequest.Method = "post";
        tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8";
        tRequest.Headers.Add(string.Format("Authorization: key={0}", GoogleAppID));

        tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));

        string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message=" + value + "&data.time=" + System.DateTime.Now.ToString() + "&registration_id=" + deviceId + "";
        Console.WriteLine(postData);
        Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
        tRequest.ContentLength = byteArray.Length;

        Stream dataStream = tRequest.GetRequestStream();
        dataStream.Write(byteArray, 0, byteArray.Length);
        dataStream.Close();

        WebResponse tResponse = tRequest.GetResponse();

        dataStream = tResponse.GetResponseStream();

        StreamReader tReader = new StreamReader(dataStream);

        String sResponseFromServer = tReader.ReadToEnd();


        tReader.Close();
        dataStream.Close();
        tResponse.Close();
        return sResponseFromServer;
    }


Thanks..............................................................




Tuesday, 26 March 2013

Using the viewport meta tag to control layout on mobile/Phone gap platform

<meta name="viewport" content="width=device-width,
 initial-scale=1, maximum-scale=1">

Disable Telephone Number/Email Detection in PhoneGap

<head>
    <meta name="format-detection" content="telephone=no" />
    <meta name="format-detection" content="email=no" />
</head>

Friday, 8 February 2013

Check Internet connection + android

public static boolean CheckNetwork(Context mContext)
 {

        ConnectivityManager connectivity = (ConnectivityManager) mContext
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netinfo = connectivity.getActiveNetworkInfo();
        if (netinfo != null && netinfo.isConnected() == true) {

            return true;
        } else {

            return false;
        }

    }

Press control + shift + O for importing required library

Friday, 4 May 2012

Android
  • It is open source but yet Google has the central control over it.
  • It has support for multiple networks AT&T, T-Mobile, Verizon, Sprint.
  • Support for many phone manufacturers,HTC,Sony,Motorola,Samsung,LG,DELL and many more.
  • Android OS is not only running in cell phones, it is now being used in cars, tablets, HDTV and the list is growing on and on. Even in the near future it will be used in medical equipment, scientific equipment.
  • The processor power is one feature notable enough, Nexus one had a 1GHz Qualcomm snapdragon processor with 512 MB RAM is almost twice the power and speed of the iPhone’s processor.
  • Application software is also open, which has really made a great impact on the developer’s community, although the number of apps is still far less than that of iPhone but still in such a short span of time more than 20,00 have been developed and this number is growing constantly.
  • Multi-touch screen is one another feature that stands out.