Saturday, 3 March 2012

C2DM Push notification for Android


Cloud to device messaging
Android Cloud to Device Messaging (C2DM) is a service that helps developers send data from servers to their applications on Android devices. The service provides a simple, lightweight mechanism that servers can use to tell mobile applications to contact the server directly, to fetch updated application or user data. The C2DM service handles all aspects of queuing of messages and delivery to the target application running on the target device. In a C2DM you have three involved parties. The application server which wants to push messages to the Android device, Googles C2DM servers and the Android app. The program on the application server can be written in any programming language, e.g. Java, PHP, Python, etc
When the application server needs to push a message to the Android application, it sends the message via an HTTP POST to Google’s C2DM servers.
The C2DM servers route the message to the device. If the device is not online, the message will be delivered once the device is available. Once the message is received, an Broadcast Intent is created. The mobile app has registered an Intent Receiver for this Broadcast. The app is started and processes the message via the defined Intent Receiver.
C2DM messages are limited in size to 1024 bytes and are intended to inform the device about new data not to transfer it. The typical workflow is that Googles C2DM servers notify the Android app that new data is available. Afterwards the Android app fetches the data from a different server.
Android maintain an connection to the Android Marketplace. C2DM uses this existing connections to the Google servers. This connection is highly optimize to minimize bandwidth and battery consumption.
C2DM is currently still in beta and you need to apply to use it. C2DM applies a limit of approximately 200 000 messages per sender per day and is currently free of charge.
To start with C2DM you need to register a Gmail ID through which your notifications will be sent signup page

#  Polling  vrs. Push

Polling architectures, as pervasive as they are today, did not come about due to their efficiency. Whether you are maintaining a popular endpoint (Twitter), or trying to get near real-time news (RSS), neither side benefits from this architecture. Over the years we've built a number of crutches in the form of Cache headers, ETags, accelerators, but none have fundamentally solved the problem -because the client remains 'dumb' the burden is still always on the server. For that reason, it's worth paying attention to some of the technologies which are seeking to reverse this trend

PUSH architectures, are nothing more but a means to push information to the end-device without the end-device having to maintain a persistent connection with the server, thus lowering the bandwidth and resources of the solution. Live APPS Push architectures reduces the cost for Network Operators as end-devices does not need to maintain a persistent connection with the WAP Proxy.

#  Requirements

C2MD is available as of Android 2.2 and requires that Android Market application is installed on the device.
To use C2DM on the Android simulator you also need to use a Google device with API 8 or higher and to register with a Google account on the emulator via the Settings.

#  Permissions

To use C2DM in your application to have to register for the following permissions
·         com.google.android.c2dm.permission.RECEIVE
·         android.permission.INTERNET
Your application should also declare the permission "applicationPackage + ".permission.C2D_MESSAGE" with the "android:protectionLevel" of "signature" so that other applications cannot register and receive message for the application. [android:protectionLevel="signature" ] ensures that applications with request a permission must be signed with same certificate as the application that declared the permission.

#  Intent Receiver

Your application must register an intent receiver for the two intents:
·         com.google.android.c2dm.intent.REGISTRATION
·         com.google.android.c2dm.intent.RECEIVE
The receiver for "com.google.android.c2dm.intent.RECEIVE" will be called once a new message is received, while the receiver for "com.google.android.c2dm.intent.REGISTRATION" will be called once the registration code for the app is received.

Limitations

C2DM imposes the following limitations:
  • The message size limit is 1024 bytes.
  • Google limits the number of messages a sender sends in aggregate, and the number of messages a sender sends to a specific device. Please refer to the section on quotas for more information.


Enjoy.... 
Do post your doubts, queries or suggestions in this blog.


Thursday, 23 February 2012

Implementing Remote Interface Using AIDL in Android

Each application in Android runs in its own process. An application cannot directly access another application's memory space. This is called application sandboxing.

In order to allow cross-application communication, Android provides an implementation of interprocess communication (IPC) protocol. IPC protocols tend to get complicated because of all the marshaling/un marshaling of data that is necessary.

To help with this, Android provides Android Interface Definition Language, or AIDL. It is a lightweight implementation of IPC using a syntax that is very familiar to Java developers, and a tool that automates the stub creation.

In order to allow for one application to call into another, we typically have to:

1. Define the AIDL interface
2. Implement the Stub for the remote service
3. Expose the remote service to the local client


Defining the AIDL

The AIDL syntax is very similar to regular Java interface. You simply define the method signature. The datatypes supported by AIDL are somewhat different than regular Java interfaces. For one, all Java primitive datatypes are supported. So are StringListMap, and CharSequence classes. Also, all other AIDL datatypes that you defined are supported. In addition to that, all Parcelable classes are supported, but this is not going to be covered in this example. I'm trying to keep this example somewhat simpler to start with.


/src/com.sourav/IAdditionService.aidl


Code:
package com.sourav;

// Declare the interface.
interface IAdditionService {
    // You can pass values in, out, or inout. 
    // Primitive datatypes (such as int, boolean, etc.) can only be passed in.
    int add(in int value1, in int value2);
}



Implementing the Remote Service

Once you create your AIDL file and put it in the right place, the Eclipse+AIDL tool will generate a file with the same name, but .java extension. So I now have /gen/com.sourav.com/IAdditionService.java file. This is an auto-generated file so you don't want to edit it. What is important is that it contains a Stub class that we'll want to implement for our remote service.

To implement our remote service, we'll return the IBinder from onBind() method in our service class,AdditionService. The IBinder represents the implementation of the remote service. To implementIBinder, we subclass IAddtionService.Stub class from the auto-generated Java code, and provide implementation for our AIDL-defined methods, in this case add().

/src/com.sourav/AdditionService.java


Code:
package com.sourav;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

/**
 * This class exposes the remote service to the client
 */
public class AdditionService extends Service {
  private static final String TAG = "AdditionService";
  
  @Override
  public void onCreate() {
    super.onCreate();
    Log.d(TAG, "onCreate()");
  }
  
  @Override
  public IBinder onBind(Intent intent) {

    return new IAdditionService.Stub() {
      /**
       * Implementation of the add() method
       */
      public int add(int value1, int value2) throws RemoteException {
        Log.d(TAG, String.format("AdditionService.add(%d, %d)",value1, value2));
        return value1 + value2;
      }

    };
  }

  @Override
  public void onDestroy() {
    super.onDestroy();
    Log.d(TAG, "onDestroy()");
  }
}

Exposing the Service Locally

Once we have the service implement the onBind() properly, we are ready to connect to that service from our client. In this case, we have AIDLDemo activity connecting to that service. To establish the connection, we need to implement ServiceConnection class. Our activity in this example provides this implementation in AdditionServiceConnection inner class by implementing onServiceConnected() and onServiceDiconnected() methods. Those callbacks will get the stub implementation of the remote service upon connection. We need to cast them from stubs to our AIDL service implementation. To do that, we use the IAdditionService.Stub.asInterface((IBinder) boundService) helper method.

From that point on, we have a local service object that we can use to make calls against the remote service.

/src/com.sourav/AIDLDemo.java


Code:
package com.sourav;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class AIDLDemo extends Activity {
  private static final String TAG = "AIDLDemo";
  IAdditionService service;
  AdditionServiceConnection connection;

  /**
   * This class represents the actual service connection. It casts the bound
   * stub implementation of the service to the AIDL interface.
   */
  class AdditionServiceConnection implements ServiceConnection {

    public void onServiceConnected(ComponentName name, IBinder boundService) {
      service = IAdditionService.Stub.asInterface((IBinder) boundService);
      Log.d(AIDLDemo.TAG, "onServiceConnected() connected");
      Toast.makeText(AIDLDemo.this, "Service connected", Toast.LENGTH_LONG)
          .show();
    }

    public void onServiceDisconnected(ComponentName name) {
      service = null;
      Log.d(AIDLDemo.TAG, "onServiceDisconnected() disconnected");
      Toast.makeText(AIDLDemo.this, "Service connected", Toast.LENGTH_LONG)
          .show();
    }
  }

  /** Binds this activity to the service. */
  private void initService() {
    connection = new AdditionServiceConnection();
    Intent i = new Intent();
    i.setClassName("com.sourav", com.sourav.AdditionService.class.getName());
    boolean ret = bindService(i, connection, Context.BIND_AUTO_CREATE);
    Log.d(TAG, "initService() bound with " + ret);
  }

  /** Unbinds this activity from the service. */
  private void releaseService() {
    unbindService(connection);
    connection = null;
    Log.d(TAG, "releaseService() unbound.");
  }

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    initService();

    // Setup the UI
    Button buttonCalc = (Button) findViewById(R.id.buttonCalc);

    buttonCalc.setOnClickListener(new OnClickListener() {
      TextView result = (TextView) findViewById(R.id.result);
      EditText value1 = (EditText) findViewById(R.id.value1);
      EditText value2 = (EditText) findViewById(R.id.value2);

      public void onClick(View v) {
        int v1, v2, res = -1;
        v1 = Integer.parseInt(value1.getText().toString());
        v2 = Integer.parseInt(value2.getText().toString());

        try {
          res = service.add(v1, v2);
        } catch (RemoteException e) {
          Log.d(AIDLDemo.TAG, "onClick failed with: " + e);
          e.printStackTrace();
        }
        result.setText(new Integer(res).toString());
      }
    });
  }

  /** Called when the activity is about to be destroyed. */
  @Override
  protected void onDestroy() {
    releaseService();
  }

}



The UI in this case is very simple. There are couple of TextViews and EditText fields and a button The button handles its events in an anonymous inner class OnClickListener. The button simply invokes theadd() method on the service as if it was a local call.


The layout for this example is not that significant, but I'm including it here for completeness purposes.

/res/layout/main.xml


Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical" android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <TextView android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:text="AIDL Demo"
    android:textSize="22sp" />
  <EditText android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:id="@+id/value1"
    android:hint="Value 1"></EditText>
  <TextView android:id="@+id/TextView01" android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:text="+"
    android:textSize="36sp"></TextView>
  <EditText android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:id="@+id/value2"
    android:hint="Value 2"></EditText>
  <Button android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:id="@+id/buttonCalc"
    android:text="="></Button>
  <TextView android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:text="result"
    android:textSize="36sp" android:id="@+id/result"></TextView>
</LinearLayout>



The output of your code should look like this:


Additional Resources
I highly recommend getting the details on AIDL from Designing a Remote Interface Using AIDL.

Enjoy.... 
Do post your doubts, queries or suggestions in this blog.


Friday, 17 February 2012

All about 9-patch image in android.

While I was working on my Android App I found 9-patch (aka 9.png) to be confusing and poorly documented. After a little while, I finally picked up on how it works and decided to throw together something to help others figure it out. As Android devices come in many shapes and sizes, often making it very difficult for developers to design applications that look great on all the various screen sizes and orientations. For addressing this challenge,9-patch  can be indispensable. In this article, I will discuss what the 9-patch graphics format is, how it works, and when to use it.
What is the 9-patch  !!! 
Android supports 9-patch Stretchable Graphics for the controlled scaling of images. 9-patch graphics uses .png transparency to do an advanced form of 9-slice or scale9  that have patches, or regions of the image, defined to scale and stretch in the appropriate areas instead of scaling the entire image as one unit, which often obscures the details of the graphic. Generally, the center patch is transparent or solid, With  parts of the edges set to remain fixed, other edge parts set to stretch, and the corners set to remain fixed.


Here’s a basic guide map:


As you can see, you have guides on each side of your image. The TOP and LEFT guides are for scaling your image (i.e. 9-slice), while the RIGHT and BOTTOM guides define the fill area.
The black guide lines are cut-off/removed from your image – they won’t show in the app.  Guides must only be one pixel wide, so if you want a 48×48 button, your png will actually be 50×50. Anything thicker than one pixel will remain part of your image. (My examples have 4-pixel wide guides for better visibility. They should really be only 1-pixel).
Your guides must be solid black (#000000). Even a slight difference in color (#000001) or alpha will cause it to fail and stretch normally. This failure won’t be obvious either*, it fails silently! Yes. Really. Now you know.
Also you should keep in mind that remaining area of the one-pixel outline must be completely transparent. This includes the four corners of the image – those should always be clear. This can be a bigger problem than you realize. For example, if you scale an image in Photoshop it will add anti-aliased pixels which may include almost-invisible pixels which will also cause it to fail*. If you must scale in Photoshop, use the Nearest Neighbor setting in the Resample Image pull down menu (at the bottom of the Image Size pop-up menu) to keep sharp edges on your guides. This is actually a “fix” in the latest dev kit. Previously it would manifest itself as all of your other images and resources suddenly breaking, not the actually broken 9-patch image.
The TOP and LEFT guides are used to define the scalable portion of your image – LEFT for scaling height, TOP for scaling width. Using a button image as an example, this means the button can stretch horizontally and vertically within the black portion and everything else, such as the corners, will remain the same size. This allows you to have buttons that can scale to any size and maintain a uniform look.
It’s important to note that 9-patch images don’t scale down – they only scale up. So it’s best to start as small as possible.
Also, you can leave out portions in the middle of the scale line. So for example, if you have a button with a sharp glossy edge across the middle, you can leave out a few pixels in the middle of the LEFT guide. The center horizontal axis of your image won’t scale, just the parts above and below it, so your sharp gloss won’t get anti-aliased or fuzzy.

Fill area guides are optional and provide a way define the area for stuff like your text label. Fill determines how much room there is within your image to place text, or an icon, or other things. 9-patch isn’t just for buttons; it works for background images as well.
The above button & label example is exaggerated simply to explain the idea of fill – the label isn’t completely accurate. To be honest, I haven’t experienced how Android does multi-line labels, but there’s a good explanation of how to do them on Stack Overflow. Usually, a button label is usually a single row of text.
Finally, here’s a good demonstration of how scale and fill guides can vary, such as a LinearLayout with a background image & fully rounded sides:
Creating 9-patch Graphics
Let's give it a try. I've created a really basic PNG file called bluenotstretchy.png. To create a NinePatch graphic from this PNG file using the Draw 9-patch tool, perform the following steps:
1.       Launch Draw 9-patch.bat in your Android SDK /tools directory.
2.       Drag the PNG file into the left-hand pane (or use File -> Open NinePatch…)
3.       Click the "Show Patches" checkbox at the bottom of the left pane.
4.       Set your Patch Scale appropriately (higher to see more obvious results).
5.       To set a horizontal patch guide, click along the right edge of your graphic.
6.       To set a vertical patch guide, click along the top edge of your graphic.
7.       View the results in the right pane, and move patch guides until the graphic stretches the way you intend it. 
8.       If you need to delete a patch guide, press Shift and click on the guide pixel (black).
9.       Save your graphic with the extension .9.png (e.g., blue.9.png).

Loading 9-patch Graphic Resources from java file :
9-patch resources are simply another kind of Drawable subclass called NinePatchDrawable. Most of the time, you'll need only the resource ID of the image, to set as an attribute of View or layout. Occasionally you might need to act on the resource programmetically.
To create a NinePatchDrawable object from a NinePatch drawable resource, use the resource'sgetDrawable() method. If the drawable is a NinePatch, the getDrawable() method will return a NinePatchDrawable instead of a generic BitmapDrawable object.
For example, to load a NinePatch drawable resource called blue.9.png, you could use the following code:
import android.graphics.drawable.NinePatchDrawable;
NinePatchDrawable myNinePatchDrawable = (NinePatchDrawable) getResources().getDrawable(R.drawable.blue);
You can then use the NinePatchDrawable object much as you would any BitmapDrawable.

Enjoy.... 
Do post your doubts, queries or suggestions in this blog.


Tuesday, 31 January 2012

Setting external front or Typeface in android

In this tutorial i will show how you can use external fonts in your Android application instead of regular fonts.
The first step is that you need to download a front (.ttf file) from internet which you want to use. It's easy. You can search for free fonts and download the one which you want to use. Here in this tutorial we will be using two fonts - RockFont font and FeastOfFlesh font as shown below.

Now inside the assets folder of your project create a new folder and name it as fonts. Copy the font(.ttf) files in this folder. In our case the font files are RockFont.ttf and FEASFBRG.TTF.
If you are using Eclipse refresh your project directory tree once. Now copy the following code in the main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"                                                                                                                                          
    android:id="@+id/main_root" 
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:id="@+id/text1"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
   />
<TextView  
    android:id="@+id/text2"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    />
</LinearLayout>
Now if you want your TextViews to have this external front you need to perform the below code in your activity 
  @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Typeface font1 = Typeface.createFromAsset(getAssets(), "fonts/RockFont.ttf");
        Typeface font2 = Typeface.createFromAsset(getAssets(), "fonts/FEASFBRG.TTF");
        TextView customText1 = (TextView)findViewById(R.id.text1);
        TextView customText2 = (TextView)findViewById(R.id.text2);


        customText1.setTypeface(font1);     // to set the font
        customText1.setTextSize(40.f);        // to set the text size
        customText1.setText("Hello! This is a custom font...");   // to set the text to be displayed 
        
        customText2.setTypeface(font2);
        customText2.setTextSize(30.f);
        customText2.setText("Developed by www.bOtskOOl.com");
    }
The Typeface class specifies the typeface and intrinsic style of a font. We have created two objects of this class - font1 and font2 and assigned them the path of two font files by using creatFromAsset() method.
After this we declare two objects of TextView class and assign them the ids of our XML layout. We then define what type of font to use by using setTypeface() function. We can alter the default textsize by using setTextSize() method. And finally we define the text to be displayed via setText() method.
Now if you are working with a layout where you want to set custom font on multiple objects ,instead of calling all the TextView,EditText ,Button etc in your Activity you can simply use this method.First get the root view in your onCreate then call the method with this two parameters. 
Typeface font1 = Typeface.createFromAsset(getAssets(), "fonts/RockFont.ttf");  
ViewGroup rootVIew = (ViewGroup) findViewById(R.id.main_root);                                                                                                                                                           see  the id of LinearLayout in main.xml
public static void setTypeFaceForChilds(ViewGroup viewGroup,Typeface typeface) {
                          final int childCount = viewGroup.getChildCount();
                          for (int i = 0; i < childCount; i++) {
                         View view = viewGroup.getChildAt(i);
                                    if (view instanceof ViewGroup) {
                                  setTypeFaceForChilds((ViewGroup) view,typeface);
                                   } else if(view instanceof TextView){
                                              ((TextView) view).setTypeface(typeface);
                                               }
                            }
}
This is a recursive method it will get all the child's under the root layout and then set the  Typeface .It will not wor with Spinners.It will only wor on the ViewGroup child objects (TextView,EditText ,Button etc.)
Enjoy.... 
Do post your doubts, queries or suggestions in this blog.