Splash Screen in Xamarin.Forms cross platform app (Android & iOS)

Practically there is no way to show Splash Screen/ Launch Screen using Xamarin.Forms because Xamarin.Forms libraries load after loading of AppDelegate (iOS) or MainActivity (Android) is completed. There is no point in showing splash screen at this point of application lifecycle because splash screens are meant to be displayed while app libraries are loading and we don’t want to show users a blank dark screen.

Keeping that in mind we have to configure it separately in each platform. Our splash screen will contain a solid colored background and a logo placed on center of the screen. Follow below links for detailed walk-through to add splash screen on each of he platform. Keep on reading

Add Splash Screen in Xamarin.Forms cross platform app – iOS

For showing splash screen in Xamarin forms iOS app we will need to follow below steps

  • Prepare/ Gather Images

We will be preparing our splash screen with a logo and solid color filled background. So for that we have two options that is prepare image for each of resolution type suggested by Apple or have and PDF format vector image through other resolutions are generated at run time. Keep in mind that PDF vector option will work only for iOS 8 and later. Keep on reading

Sample Code – Android share action with chooser to display system default share chooser dialog

This post is for helping those you are looking to implement share feature in there android application and ending up with default ShareActionProvider which is too basic and doesn’t look good at all.

Solution to this problem is “chooser”. below is the sample of how you can share any data with ACTION_SEND intent by setting text and subject and at the end call start activity with createChooser.

      Intent sendIntent = new Intent();
      sendIntent.setAction(Intent.ACTION_SEND);
      String text = "";
      String url = "";
      sendIntent.putExtra(Intent.EXTRA_SUBJECT, text);
      sendIntent.putExtra(Intent.EXTRA_TEXT, text + " nn" + url);
      sendIntent.setType("text/plain");
      context.startActivity(Intent.createChooser(sendIntent, "Share"));

There are many advantages of using chooser

  • Even if you has selected any default application of this action your application will share chooser dialog so that user can select any other application without going to settings
  • You have option to set title for your share action chooser dialog
  • If no matching application found (I don’t think if this will happen to anyone in real world) then android displays a system message.

Adding Share Action on Android Application ActionBar (appcompat v7)

Adding share action on android application action bar is simple and straight forward.

There are mainly 3 steps that you have to follow:

1. Add Share Action Item in your menu

To add share action item in your menu simply add below item in your menu layout:

<item
	android:id="@+id/menu_item_share"
	app:showAsAction="ifRoom"
	android:title="Share"
	app:actionProviderClass="android.support.v7.widget.ShareActionProvider" />

And don’t forget to add res-auto schema on your menu. Your final menu layout should contain below details:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
	xmlns:app="http://schemas.android.com/apk/res-auto"
	xmlns:tools="http://schemas.android.com/tools">
	<item
		android:id="@+id/menu_item_share"
		app:showAsAction="ifRoom"
		android:title="Share"
		app:actionProviderClass="android.support.v7.widget.ShareActionProvider" />
</menu>

You can set showAsAction to any other value like always, never, withText etc
2. Create ShareActionProvider in your activity

No you have to create ShareActionProvider in your activity where you want to show and handle action share event.

For that first declare ShareActionProvider object

private ShareActionProvider mShareActionProvider;

override onCreateOptionMenu in your activity and add below code:

@Override
public boolean onCreateOptionsMenu(Menu menu) 
{
	// Inflate menu resource file.
	getMenuInflater().inflate(R.menu.menu_main, menu);

	// Locate MenuItem with ShareActionProvider
	MenuItem item = menu.findItem(R.id.menu_item_share);

	// Fetch and store ShareActionProvider
	mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(item);

	setShareIntent();
	// Return true to display menu
	return true;
}

Here menu_main should be your menu xml file name and menu_item_share is the id of share item added in the menu.

You many notice that we have called a method setShareIntent at the end just before returning. This is not an inbuilt method. We will define this in next step.

3. Set Share Intent

Here we will set the intent of the share action so that we can control what will be shared if user proceeds to go further with sharing.

private void setShareIntent() 
{
	if (mShareActionProvider != null) 
	{
		Intent myShareIntent = new Intent(Intent.ACTION_SEND);
		myShareIntent.setType("text/plain");

		myShareIntent.putExtra(Intent.EXTRA_SUBJECT, "");
		myShareIntent.putExtra(Intent.EXTRA_TEXT, "");

		mShareActionProvider.setShareIntent(myShareIntent);
	}
}

You can specify different share intent type like in our case we have set text/plain because we are sharing plain text. Similarly you can set other type like view, images etc.

After that put extras based on based on your share intent type. For text/plain we have set subject and text.

=&0=& Whenever in your activity life cycle if your share content (subject and text in our case) is changed just call this method setShareIntent, no need to create ShareActionProvider again.

Speed up Android WebView App by localising static resources

Recently I was developing an android app which was using a WebView to display some graphs on dashboard. Rest of application was build on native android code and only this dashboard portion was using webview to load a specific URL where dashboard graphs were displayed.

I used webview to load graphs because creating graphs is too complicated in android as compared to web. Also most of the android graph tools I found were not created to draw attractive graphs.

So I used WebView to display my graphs on android app but things become even worse because I was using this webview dashboard in my main activity. So every time when I open the app it was taking almost 15 to 20 seconds to load and this time is long enough to make users a safe distance from your app.

After searching for some time and doing some tweaking I reached to one of the most effective solution (at-least for my app scenario) and want other to get benefit from it.

=&0=& So first thing we should do is copy all the external static resources (like css, js, fonts files etc) of the webpage to assets folder of your android project. If your project doesn’t have assets folder then you can create one on app root and copy all external static content of your page on this file.

This is specially helpful because most of the time a page takes to load is because of loading external resources like css, jquery file and other external file like in my case there were css, jquery, bootstrap file, fonts, morris chart js and css etc. So if we will load all these files from local devices instead of an http url then it will make a big difference.

=&1=&. Now next thing to do is rewrite your all you links to your static resources to local relative URLs. For example if you have added any script reference on your page like this

<script src="https://www.edunyte.com/script.js" type="text/javascript"></script>

or

<script src="../script.js" type="text/javascript"></script>

then change it to like this

<script src="script.js" type="text/javascript"></script>

Here we have assumed that script.js file was on your website root and you have copied it directly in assets folder. If you used to place all js in one folder (may be scripts) and all css in other (may be styles) then you can copy this complete folder to your asset toot and us link in your page like this:

<script src="scripts/script.js" type="text/javascript"></script>

and

<link href="styles/style.css" rel="stylesheet" type="text/css" />

=&2=& Now after this we have to get the webpage content using http request. I normally use Volley StringRequest class for this. You can see code below to get HTML content of any webpage using Volley StringRequest:

  StringRequest strReq = new StringRequest(Request.Method.GET, String.format(Config.URL_DASHBOARD, apiKey, studentId),
            new Response.Listener<String>() {
       @Override
       public void onResponse(String response) {
           //You will get the page HTML in response string object
       }
   }, new Response.ErrorListener() {
       @Override
       public void onErrorResponse(VolleyError error) {
        //If anything goes wrong you can handle that here
       }
   }
  );
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(strReq);

In above code you will notice that I have used MyApplication class and added my request in it. This is class which manages the request queue using Singleton architecture. You can get code of this class from here.

=&3=& Now comes the final step. In OnResponse method we will get the complete HTML string of page in response String object. This string we will us to load webview by making file:///android_asset/ as root of the page. There is a method loadDataWithBaseURL which gives us option to set page root, specify HTML string to load along with specifying encoding etc. Se below

myWebView.loadDataWithBaseURL("file:///android_asset/", response, "text/html", "utf-8", null);

Now as soon as we call loadDataWithBaseURL method your html string content will load in webview and all the external static content you have used in the page will be loaded from assets folder of your app (provided that you have already copied these resource in assets folder and used proper linking on the page).

That’s all from my side for this article. Please write in comments section below if you any question or facing any problem.

Get Day, Month, Year, Day of week etc from date in JAVA

Many times in your project you might need each part of date separately. For example I wanted to show date with a different format in my android app (see image below).

So for above I wanted day, month and year separately which I can get using get and getDisplayName method of Calender class.

Below is a sample code to get day part of the date object using calender object:

public int getDayFromDate(Date date)
 {
            Calendar cal = Calendar.getInstance();
     cal.setTime(date);
     return cal.get(Calendar.DAY_OF_MONTH);
 }

Similarly we can get year of the date just by replacing Calendar.DAY_OF_MONTH with Calendar.YEAR.

For getting month and day of the week from date object these is a different method that is by using getDisplayName method.

public String getMonthFromDate(Date date)
 {
            Calendar cal = Calendar.getInstance();
     cal.setTime(date);
     return cal.getDisplayName (Calendar.MONTH);
 }

Similarly we can also get day of the week from date object and for that we just have to replace Calendar.MONTH with Calendar.DAY_OF_WEEK.

Similarly for all those date part which are in string format we have to call getDisplayName method and for others which are expacted to be integer we should call get method.

I hope this information will help beginner JAVA developers as well as some intermediate. Stay tuned with us to get more useful articles and codes.

Show Splash Screen While Android WebView is Loading

In one of my recent application (which was a webview app) my client suggested to show splash screen while we are loading the application data (obviously client does not bother if this is webview app or native one) so here I am with a sample for all those who are in similar situation.

I am not going to explain all the basic things like create project and activity etc as we have already discussed this in my previous articles.

1. First thing we have to do is create layout for our webview screen. We will name this layout file activity_main.xml. This file will contain webview element and splash screen element.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">
 <RelativeLayout
     android:id="@+id/splach_screen"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:background="@drawable/splash_bg"
     android:visibility="visible" >
 
     <ImageView
         android:id="@+id/imgLogo"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
      android:layout_centerHorizontal="true"
      android:layout_centerVertical="true"
         android:contentDescription="@string/splash_image_desc"
         android:src="@drawable/ic_logo" />
    
     <ProgressBar
      android:id="@+id/webViewProgress"
      android:layout_centerHorizontal="true"
      android:layout_centerVertical="true"
      android:layout_width="wrap_content"
         android:layout_height="wrap_content"
      android:layout_below="@+id/imgLogo" />
    
     <TextView
         android:id="@+id/error"
      android:layout_centerHorizontal="true"
      android:layout_centerVertical="true"
      android:layout_width="wrap_content"
         android:layout_height="wrap_content"
      android:layout_below="@+id/imgLogo"
         android:textColor="@color/loading_error"
         android:textSize="@dimen/loading_error"
         android:text="@string/loading_error"
      android:visibility="invisible"/>
    
     <Button
         android:id="@+id/reload"
      android:layout_centerHorizontal="true"
      android:layout_centerVertical="true"
      android:layout_width="wrap_content"
         android:layout_height="wrap_content"
      android:layout_below="@+id/error"
      android:text="@string/reload"
      android:onClick="reload"
      android:visibility="invisible" />
 
     <TextView
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:layout_marginBottom="10dp"
         android:textSize="12sp"
         android:textColor="#454545"
         android:gravity="center_horizontal"
         android:layout_alignParentBottom="true"
         android:text="@string/splash_loading_text" />
 </RelativeLayout>
 <LinearLayout
     android:id="@+id/main_view"
     android:orientation="vertical"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
    android:visibility="invisible">
     <WebView android:id="@+id/web_engine"
         android:layout_width="fill_parent"
         android:layout_height="fill_parent" />
 </LinearLayout>
</LinearLayout>

In this layout we have one main layouts and two sub layouts. One of the two sub layouts contains our splash screen contents and other contains webview.

We have set splash screen layout to visible and webview layout to invisible which will be later changed when webview content is loaded.

2. Now we will create our application’s main activity. We will name it MainActivity.java and its code will be as below:

package com.edunyte.webviewsplashscreen;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends Activity {
@SuppressLint("SetJavaScriptEnabled")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

WebView myWebView = (WebView) findViewById(R.id.web_engine);

myWebView.setWebViewClient(new MyBrowser());
myWebView.clearCache(true);
myWebView.clearHistory();

myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.getSettings().setLoadsImagesAutomatically(true);
myWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
myWebView.loadUrl("https://edunyte.com/");
}

private class MyBrowser extends WebViewClient {
@Override
public void onPageFinished(WebView view, String url) {
if (findViewById(R.id.splach_screen).getVisibility() == View.VISIBLE) {
// show webview
findViewById(R.id.main_view).setVisibility(View.VISIBLE);
// hide splash screen
findViewById(R.id.splach_screen).setVisibility(View.GONE);
}
}
}
}

 

In this code we have loaded URL in webview and set webview client to handle onPageFilished event. onPageFinished event we will hide splash screen layout and show webview layout.

Apart from these two file you may need to add few more files like string.xml, style.xml, color.xml etc.

For complete code of this sample click here to download.

Create custom listview and bind with ArrayList (using adapter) in android

So in this article we will learn how to bind a ListView with JSONArray in Android. We are using Eclipse as reference IDE for this article.

  1. First of all we have to create new project. So open eclipse -> select New (from file menu) -> select Android Application Project -> type application name, project name, package name and select target sdk, theme etc and click next -> click next two times (use default selecting for these two steps) -> select blank activity and click Next again -> Enter name of your main activity and view. We are going to use default values that is MainActivity (activity) and activity_main (view)
  2. After step 1 you will get default project configured with blank activity. We will add ListView in our view file that is activity_main.xml
    <ListView
    android:id="@+id/listView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:listitem="@layout/list_item"
    android:dividerHeight="5dp"
    android:divider="#000000"></ListView>

     

  3. Create event class (if you want to bind your ListView with ArrayList)
    package com.edunyte.listdemo;
    public class Event {
    //TODO add vairble used for creating list
    private String title;
    private String day;
    private String month;
    private String location;
    
    public String getTitle() {
    return title;
    }
    
    public void setTitle(String title) {
    this.title = title;
    }
    
    public String getDay() {
    return day;
    }
    
    public void setDay(String day) {
    this.day = day;
    }
    
    public String getMonth() {
    return month;
    }
    
    public void setMonth(String month) {
    this.month = month;
    }
    
    public String getLocation() {
    return location;
    }
    
    public void setLocation(String location) {
    this.location = location;
    }
    }
    

     

  4. Create ListAdapter
    package com.edunyte.listdemo;
    import android.content.Context;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.Button;
    import android.widget.TextView;
    
    import java.util.ArrayList;
    
    import com.exponyte.listdemo.R;
    
    public class ListAdapter extends BaseAdapter {
    private ArrayList<Event> list;
    private Context context;
    
    public ListAdapter(Context context, ArrayList<event> list) {
    this.list = list;
    this.context = context;
    }
    
    @Override
    public int getCount() {
    return list.size();
    }
    
    @Override
    public long getItemId(int i) {
    return i;
    }
    
    @Override
    public Object getItem(int i) {
    return list.get(i);
    }
    
    @Override
    public View getView(int position, View contentView, ViewGroup viewGroup) {
    ViewHolder holder;
    if (contentView == null) {
    contentView = LayoutInflater.from(context).inflate(R.layout.list_item, viewGroup, false);
    holder = new ViewHolder();
    //TODO init variables of holder class
    holder.titleTextView = (TextView) contentView.findViewById(R.id.title_textview);
    holder.dayTextView = (TextView) contentView.findViewById(R.id.day_textview);
    holder.button = (Button) contentView.findViewById(R.id.button);
    //TODO handle button click event
    holder.button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
    // get position of item which is clicked
    int position = (Integer) view.getTag();
    //TODO handle click event
    }
    });
    contentView.setTag(holder);
    } else {
    holder = (ViewHolder) contentView.getTag();
    }
    // TODO set text to textview of list item
    Event event = list.get(position);
    holder.titleTextView.setText(event.getTitle());
    holder.dayTextView.setText(event.getDay());
    holder.button.setTag(position);
    
    return contentView;
    }
    
    public static class ViewHolder {
    public TextView titleTextView;
    public TextView dateTextView;
    public TextView locationTextView;
    public TextView dayTextView;
    public TextView monthTextView;
    public Button button;
    }
    }
    

     

  5. Create layout of list items
    <LinearLayout
    android:id="@+id/date_container"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/gradient_red"
    android:orientation="vertical"
    android:padding="8dp">
    <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:text="september"
    android:textAllCaps="true"
    android:textAppearance="@android:style/TextAppearance.Medium"
    android:textColor="@android:color/white"
    android:textStyle="bold" />
    
    <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:text="08"
    android:textAllCaps="true"
    android:textAppearance="@android:style/TextAppearance.Medium"
    android:textColor="@android:color/white"
    android:textSize="30sp"
    android:textStyle="bold" />
    
    <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:text="2016"
    android:textAllCaps="true"
    android:textAppearance="@android:style/TextAppearance.Medium"
    android:textColor="@android:color/white"
    android:textStyle="bold" />
    
    </LinearLayout>
    
    <Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_centerVertical="true"
    android:background="@drawable/ic_action_play"
    android:minHeight="10dp"
    android:minWidth="10dp" />
    
    <TextView
    android:id="@+id/title_textview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="8dp"
    android:layout_toRightOf="@+id/date_container"
    android:text="WWE Raw"
    android:textAllCaps="true"
    android:textAppearance="@android:style/TextAppearance.Medium"
    android:textColor="@android:color/white"
    android:textStyle="bold" />
    
    <TextView
    android:id="@+id/location_textview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/title_textview"
    android:layout_alignStart="@+id/title_textview"
    android:layout_below="@+id/title_textview"
    android:layout_gravity="center_horizontal"
    android:layout_marginTop="4dp"
    android:text="Moline, IL"
    android:textAllCaps="true"
    android:textAppearance="@android:style/TextAppearance.Medium"
    android:textColor="@color/gray_light"
    android:textStyle="bold" />
    
    <TextView
    android:id="@+id/day_textview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/title_textview"
    android:layout_alignStart="@+id/title_textview"
    android:layout_below="@+id/location_textview"
    android:layout_gravity="center_horizontal"
    android:layout_marginTop="4dp"
    android:text="Moline, IL"
    android:textAllCaps="true"
    android:textAppearance="@android:style/TextAppearance.Medium"
    android:textColor="@color/gray_light"
    android:textStyle="bold" />

     

  6. Create ArrayList of Event class and ListAdapter in onCreate method of MainActivity.java
    adapter = new ListAdapter(getApplicationContext(), eventList);ListView listView = (ListView) findViewById(R.id.listView);
    listView.setAdapter(adapter);
    addEvents();
    

     

  7. Create addEvents method to add your events details in the ArrayList. For this example I am hard-coding entries but you can use any mother like reading from database or getting it from web service. You should keep only on thing in mind that is calling adapter.notifyDataSetChanged(); after adding all entries to the list.
    private void addEvents()
    {
    Event evt = new Event();
    evt.setDay("26");
    evt.setMonth("January");
    evt.setTitle("Event Title");
    evt.setLocation("Event Location");
    eventList.add(evt);
    evt.setDay("26");
    evt.setMonth("January");
    evt.setTitle("Event Title");
    evt.setLocation("Event Location");
    eventList.add(evt);
    evt.setDay("26");
    evt.setMonth("January");
    evt.setTitle("Event Title");
    evt.setLocation("Event Location");
    eventList.add(evt);
    evt.setDay("26");
    evt.setMonth("January");
    evt.setTitle("Event Title");
    evt.setLocation("Event Location");
    eventList.add(evt);
    evt.setDay("26");
    evt.setMonth("January");
    evt.setTitle("Event Title");
    evt.setLocation("Event Location");
    eventList.add(evt);
    evt.setDay("26");
    evt.setMonth("January");
    evt.setTitle("Event Title");
    evt.setLocation("Event Location");
    eventList.add(evt);
    evt.setDay("26");
    evt.setMonth("January");
    evt.setTitle("Event Title");
    evt.setLocation("Event Location");
    eventList.add(evt);
    }

Now run the project and see the if it is working or not. This sample might need some more work related to values.xml and drawable. You can download the complete working Eclipse project code from here
 
Create custom listview and bind with ArrayList (using adapter) in android

Register for GCM registration id in android application and receive and show notification

So after learning GCM process flow and how to create a project on Google Developer Console now its time to learn how to register device and android app on GCM and get registration id. This registration id is then used to send notification message on GCM server and GCM server delivers this message to our android device.

So first thing we need to do is install Google Play Services using Android SDK Manager. You can find Google Play Services under Extras heading in android SDK manager.

Setup Google Play Service

After installing google play service we have to follow below steps to start using google play services in our project

  1. Import google-play-services_lib project from C:Program Files (x86)Androidandroid-sdkextrasgooglegoogle_play_serviceslibproject (or C:Program FilesAndroidandroid-sdkextrasgooglegoogle_play_serviceslibproject) to your work space.
  2. Right click on your project in package explorer of Eclipse IDE and go toProperties -> Android -> Library -> Add. Now select google-play-services_lib project and click ok.Again click ok to close project properties. Now we are ready to start coding.

Implement Google Play Service

Now we are ready to start implementing notification service in Android application

  1. Add import statement for com.google.android.gms.common.ConnectionResult and com.google.android.gms.common.GoogleApiAvailability in your MainActivity.java
    import com.google.android.gms.common.ConnectionResult; 
    import com.google.android.gms.common.GoogleApiAvailability;

     

  2. Add a TextView and a ProgressBar in your activity layout
    <TextView android:text="@string/registering_message" android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/informationTextView"
    android:textAppearance="?android:attr/textAppearanceMedium" />
    <ProgressBar
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/registrationProgressBar" />

     

  3. Add below object declaration in your MainActivity
    private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
    private BroadcastReceiver mRegistrationBroadcastReceiver;
    private ProgressBar mRegistrationProgressBar;
    private TextView mInformationTextView;

     

  4. Initialize BroadcastReceiver object and override OnReceive action. Use below code in your OnCreate method of MainActivity to do so
          mRegistrationProgressBar = (ProgressBar) findViewById(R.id.registrationProgressBar);
    mRegistrationBroadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
    mRegistrationProgressBar.setVisibility(ProgressBar.GONE);
    SharedPreferences sharedPreferences =                       PreferenceManager.getDefaultSharedPreferences(context);
    boolean sentToken = sharedPreferences                      .getBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false);
    if (sentToken) {
    mInformationTextView.setText(getString(R.string.gcm_send_message));
    } else {
    mInformationTextView.setText(getString(R.string.token_error_message));
    }
    }
    };
    
    mInformationTextView = (TextView) findViewById(R.id.informationTextView);
  5. Override two methods (onResult and OnPause) and define one more method (checkPlayService).
    @Override
    protected void onResume() {
           super.onResume();
          
     LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver, new IntentFilter(QuickstartPreferences.REGISTRATION_COMPLETE));
       }
    @Override
    protected void onPause() {
    
    LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
    super.onPause();
    }
    
    private boolean checkPlayServices() {
    GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
    int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
    if (resultCode != ConnectionResult.SUCCESS) {
    if (apiAvailability.isUserResolvableError(resultCode)) {
    apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST).show();
    }
    else {
    Log.i(TAG, "This device is not supported.");
    finish();
    }
    return false;
    }
    return true;
    }

     

  6. We are done with the MainActivity and layout. Now we need to add four classes in our application package- MyGcmListenerService extended from GcmListenerService – Download
    – MyInstanceIDListenerService extended from InstanceIDListenerService – Download
    – QuickstartPreferences for static final string to use with SharedPreferences – Download
    – RegistrationIntentService extended from IntentService – Download
  7. Update AndroidManifest.xmlAdd Permission
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.INTERNET" />

    Add meta data tag. This is very important

    <meta-data android:name="com.google.android.gms.version"  android:value="@integer/google_play_services_version" />

    Add receiver and services

    <!-- [START gcm_receiver] -->
            <receiver
                android:name="com.google.android.gms.gcm.GcmReceiver"
                android:exported="true"
                android:permission="com.google.android.c2dm.permission.SEND" >
                <intent-filter>
                    <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                    <category android:name="gcm.play.android.samples.com.gcmquickstart" />
                </intent-filter>
            </receiver>
            <!-- [END gcm_receiver] -->
    <!-- [START gcm_listener] -->
    <service
    android:name="com.example.myfirstapp.MyGcmListenerService"
    android:exported="false" >
    <intent-filter>
    <action android:name="com.google.android.c2dm.intent.RECEIVE" />
    </intent-filter>
    </service>
    <!-- [END gcm_listener] -->
    <!-- [START instanceId_listener] -->
    <service
    android:name="com.example.myfirstapp.MyInstanceIDListenerService"
    android:exported="false">
    <intent-filter>
    <action android:name="com.google.android.gms.iid.InstanceID"/>
    </intent-filter>
    </service>
    <!-- [END instanceId_listener] -->
    <service
    android:name="com.example.myfirstapp.RegistrationIntentService"
    android:exported="false">
    </service>

Now we are done with all needed code and configuration. Just run app on device and get the registration id in logs.