Saturday, 31 January 2015

How to set the Alarm in Android ?

* Once we have the time instance in milliseconds as a Calendar object and the pending intent pointing to the receiver, we can set up an alarm by calling the set() method of the alarm manager.


*If you use AlarmManager.RTC_WAKEUP, the alarm will wake up the device.

* Or you can use AlarmManager.RTC in its place to deliver the intent when the device wakes up.

* The time specified by the second argument is the instance in time specified by the calendarObject that was created earlier.

* This time in milliseconds since 1970.This also coincides with the Java Calendar object default.

* When the method is called, the alarm manager will invoke the TestReceiver in 30 seconds after the time when the method is called.

Thursday, 29 January 2015

How to Create a Receiver and PendingIntent suitable for an alarm ?

Creating a Receiver for the alarm:
Now, we need a receiver to set against the alarm.

public class TestReceiver extends BroadcastReceiver
      public static final String tag = "TestReceiver";
      public void onReceive(Context context, Intent intent)
      Log.d ( tag, "Intent=" + intent );
      String message = intent.getStringExtra("message");
      Log.d ( tag, message );


You will need to register this receiver in the manifest file using the <receiver> tag.

Creating a PendingIntent suitable for an alarm:

Once we have a receiver, we can set up a PendingIntent, which is needed to set the alarm.
However, we need an intent to create a pending intent. So, we start by creating a regular intent
that can invoke the TestReceiver.

* Creating an Intent pointing to TestReceiver

Intent intent = new Intent(mContext, TestReceiver.class);
intent.putExtra("message", "Single shot alarm");

Once we have this regular intent pointing to a receiver, we need to create a pending intent that is necessary to pass to an alarm manager.

* Creating a Pending Intent

PendingIntent pi = PendingIntent.getBroadcast(
                                            mContext,  // context, or activity, or service
                                            1,              // request id, used for disambiguating this intent
                                             intent,       // intent to be delivered
                                             0);           // pending intent flags

How to Access the Alarm Manager and set up the time for Alarm ?

Getting An Alarm Manager :

AlarmManager am = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);

The variable mContext refers to a context object.

For Example: 
If  you are invoking this code from an activity menu, the context variable will be the activity.

Setting Up the Time for the Alarm :

To set the alarm for a particular date and time, you will need an instance in time identified by a Java Calendar object.

public class Utils {

public static Calendar getTimeAfterInSecs(int secs){
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, secs) ;
return cal;

public static Calendar getCurrentTime(){
Calendar cal = Calendar.getInstance();
return cal;

public static Calendar getTodayAt(int hours){
Calendar today = Calendar.getInstance();
Calendar cal = Calendar.getInstance();

int year = today.get(Calendar.YEAR);
int month = today.get(Calendar.MONTH);
int day = today.get(Calendar.DATE);
return cal;

public static String getDateTimeString(Calendar cal){
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss");
String s = df.format(cal.getTime());
return s;


From this list of Utilities , we will use the function getTimeAfterInSecs(), to look for a time instance that is 30 seconds from now.

Calendar cal = Utils.getTimeAfterInSecs(30);

Tuesday, 27 January 2015

What are the steps to set up a simple alarm in android ?

Setting an alarm at a particular time and having it call a broadcast receiver.Once the broadcast receiver is invoked, we can use the information to perform both simple and long-running operations in that broadcast receiver.

The steps are as follows :

  1. Get access to the alarm manager.
  2. Come up with a time to set the alarm.
  3. Create a receiver to be invoked.
  4. Create a pending intent that can be passed to the alarm manager to invoke the receiver at the appointed time.
  5. Use the time instance from step 2 and the pending intent from step 4 to set the alarm.
  6. See the receiver from step 3 invoked.

Monday, 26 January 2015

Life Cycle of a Widget in Android.

The life cycle of a widget has the following phases :

  1. Widget definition.
  2. Widget instance creation.
  3. onUpdate() (when the time interval expires).
  4. Responses to clicks (on the widget view on the home screen).
  5. Widget deletion (from the home screen).
  6. Uninstallation.

Saturday, 24 January 2015

What do you understand by Widget Configurator ?

* A widget definition optionally includes a specification of an activity called a widget configurator activity.

* When you choose a widget from the home page widget pick list to create the widget instance, Android invokes the corresponding widget configuration activity.

* This activity is something you need to write, which is then responsible for configuring the widget instance.

For Example:

- In the case of our Birthday Widget, this configuration activity will prompt you for the name of the person and the upcoming birth date.

- It is the responsibility of the configurator to save this information in a persistent place so that when an update is called on the widget provider, the widget provider will be able to locate this information and update the view with proper values that are set by the configurator.

Tuesday, 20 January 2015

What are Home Screen Widgets ?

* Home screen widgets are views that can be displayed on a home page and updated frequently.

* As a view, a widget's look and feel is defined through a layout XML file.

* For a widget, in addition  to the layout of the view, you will need to define how much space the view
of the widget will need on the home screen.

* A widget definition also includes a couple of java classes that are responsible for initializing the view and updating it frequently.

* These java classes are responsible for managing the life cycle of the widget on the home screen.

* These classes respond when the widget is dragged onto the home page, when the widget needs
to be updated, and when the widget is uninstalled by dragging it to the trash can.

A widget definition contains the following :

1- A view layout to be displayed on the home screen, along with how big it should be(at a minimum)
to fit on a home page.Keep in mind that this is just the view without any data.It will be the responsibility of a Java class to update the view.

2- A timer that specifies the frequency of updates.

3- A broadcast receiver Java class called a widget provider that can respond to timer updates in order to alter the view in some fashion by populating with the data.

* Once a widget is defined and the Java classes are provided, the widget will be available for the user to drag onto a home page.

Monday, 19 January 2015

What is Provider Life Cycle in Android ?

* Content Provider are another story.Clients, both internal and external, interact with a content provider synchronously.

* For external clients, content providers use a thread pool to satisfy this requirement.

* Like broadcast receivers, content providers do not have a particular life cycle.

* They get started when needed and stay around as long as the process stays around.

* Even though they are synchronous for external clients, they will run not on the main thread but on a thread pool of the process that they reside in, similar to a web client and a web server.

* The client  thread will wait until the call comes back.

* When there are on clients around, the process gets reclaimed as per the reclamation rules of a process, depending on what other components are defined and active in that process.

Friday, 16 January 2015

Receiver Life Cycle in Android ?

* Broadcast receivers us a call-and-be-gone model.

* The process hosting the broadcast receiver will be around only for the lifetime of the receiver and no longer.

* Also, the broadcast receiver runs only for the main thread, and it has a hard ten-second timeframe to finish its work.

* You have to follow a pretty roundabout protocol to acomplish more complicated and time-consuming work in a broadcast receiver.

* If you have a broadcast receiver that takes longer than ten seconds, you will need to follow a protocol such as the following :

1- Get hold of a wakelock in the receiver code ( no later ) so that the device is at least partially awake.

2- Issue a startService() call so that the process is tagged as sticky and restartable, if needed, and hangs around.Note that you cannot do the work in the service directly, because it would take more than ten seconds and that would hold up the main thread.This is because the service also runs on the main thread.

3- Start a worker thread from the service.

4- Have the worker thread post a message through a handler to the service or issue a stopService() call on the service.

Thursday, 15 January 2015

What do you understand by Handlers in Android ?

* A Handler is a mechanism to drop a message on the main queue (more precisely, the queue attached to the thread on which the handler is instantiated) so that the message can be processed at a later point in time by the main thread.

* The message that is dropped has an internal reference pointing to the handler that dropped it.

* When the main thread gets around to processing that message, it invokes the handler that dropped the message through a callback method on the handler object.This callback method is called handleMessage.

* The Key players that work together when we talk about handlers are :

- Main thread.

- Main thread queue.

- Handler.

- Message.

Wednesday, 14 January 2015

Implications of the Signing Process.

* We now can see that we cannot have two distinct signatures for the same package name.

* Signatures are sometimes referred to as public key infrastructure (PKI) certificates.

* More accurately stated, you would use a PKI certificate to sign a bundle, a JAR file, or a DLL or
an application.

* The PKI certificate is tied to the package name to ensure that two developers cannot install a package that carries the same package name.

* However, the same certificate can be used to sign any number of packages.

* I other words one PKI certificate supports many packages.This relationship is one-to-many.

* However one package has one,and only one,signature through its PKI certificate.

* A developer then protects the private key of a certificate with a password.

* These facts are important not only for new releases of the same package but also to share data
between packages when the packages are signed with the same signature.

Tuesday, 13 January 2015

Revisiting the Package Signing Process in Android.

A process is tied to a package name, and a package name is tied to its signature, signatures play a
role in securing the data belonging to a package.

For Example :

When we download an application and install it on Windows or another operating systems,
we don't need to sign it. Why is signing mandated on an Android device ? What does the signing process really mean? What does it ensure? We will cover it in further posts.

As packages are installed onto a device, it is necessary that each installed package has a unique
or distinct Java package name.

If you try to install a new package with an existing name, the device will disallow the installation
until the previous package is removed.

To allow this type of package upgrading,you must ensure that the same application publisher
is associated with that package.

Signing an .apk file ensures that, as a developer, you reserve that package name for you through
your digital signature.

Monday, 12 January 2015

Pinch Gesture in Android.

* One of the cool applications of multitouch is the pinch gesture,which is used for zooming.

* The idea is that if you place two fingers on the screen and spread them apart,the application should
respond by zooming in.If your fingers come together,the application should zoom out.

* The application is usually showing images,which could be maps.

* GestureDetecter class is used to implement this.

* Its purpose in life is to receive MotionEvent objects and tell us when a sequence of events looks
like a common gesture.

Saturday, 10 January 2015

What do you understand by Gestures in Android ?

* Gestures are a special type of a touch screen event.

* The term Gesture is used for a variety of things in Android, from a simple touch sequence like a
fling or a pinch.

* Flings , pinches , long presses , and scrolls have expected behaviors with expected triggers.

* That is, it is pretty clear to most people that a fling is a gesture where a finger touches the screen,
drags somewhat quickly off in a single direction,and then lifts up.

* For Example : When someone use a fling in the Gallery application ( the one that shows images in a
left-to-right chain ), the images will move sideways to show new images to the user.

Friday, 9 January 2015

What do you understand by Multitouch in Android ?

* Multitouch has gained a lot of interest ever since the TED conference in 2006 at which Jeff Han
demonstrated a multitouch surface for a computer user interface.

* Using multiple fingers on a screen opens up a lot of possibilities for manipulating what's on the screen.

* For Ex. putting two fingers on an image and moving them apart could zoom in on the image.

* By placing multiple fingers on an image and turning clockwise , you could rotate the image on the
screen. These are standard touch operations in Google Maps, for instance.

* Android introduced support for multitouch with Android SDK 2.0.

* In that release you were able to ( technically ) use up to three fingers on a screen at the same time
to perform actions such as zoom,rotate,or whatever else you could imagine doing with multiple touches ( we say "technically" because the first Android devices to support multitouch only supported two fingers ).

Thursday, 8 January 2015

How to use VelocityTracker to handle touch screen ?

* Android provides a class to help handle touch screen sequences,and that class is VelocityTracker.

* When a finger is in motion on a touch screen,it might be nice to know how fast it is moving 
across the surfaces.

* For Example, if the user is dragging an object across the screen and lets go,your application 
probably wants to show that object flying across the screen accordingly.

* Android provides VelocityTracker to help with the math involved.

* To use VelocityTracker, you first get an instance of a VelocityTracker by calling the static method

* You can then add MotionEvent objects to it with the addMovement(MotionEvent ev) method.

* You would call this method in your handler that receives MotionEvent objects,from a handler 
method such as onTouch(),or from a view's onTouchEvent().

* The VelocityTracker uses the MotionEvent objects to figure out what is going on with the user's
touch sequence.

* Once VelocityTracker has at least two MotionEvent objects in it.

* The two VelocityTracker methods- getXVelocity() and getYVelocity() - return the corresponding velocity of the finger in the X and Y directions.

Tuesday, 6 January 2015

What is MotionEvent Object when user touches on the screen in Android ?

* When a user touches the touch screen of an Android device, a MotionEvent object is created.

* The MotionEvent contains information about where and when the touch took place,as well as other
details of the touch event.

* The MotionEvent object gets passed to an appropriate method in our application.

* This could be the onTouchEvent() method of a View object.

* Remember that the View class is the parent of quite a few classes in Android including Layouts,
Buttons,Lists,Surfaces,Clocks and more.

* This means we can interact with all of these different types of View objects using touch events.

* When the method is called,it can inspect the MotionEvent object to decide what to do.

* For Example : A MapView could use touch events to move the map sideways to allow the user to
pan the map to other points of interest.

* Or a Virtual Keyboard object could recieve touch events to activate the virtual keys to provide text
input to some other part of the User Interface ( UI ).

About Touch Screens in Android.

* Many Android devices incorporate touch screens.When a device does not have a physical keyboard,
much of the user input must come through the touch screen.

* Therefore,your applications will often need to be able to deal with touch input from the user.

* You've most likely already seen the virtual keyboard that displays on the screen when text input is
required from the user.

* The implementation of the touch screen interface have been hidden from you so far,but now we'll
show you how to take advantage of the touch screen.

It is made up of 4 major parts : 

i)- MotionEvent
ii)- Velocity Tracker
iii)- Multitouch
iv)- Gestures.

Monday, 5 January 2015

Using the HttpURLConnection when dealing with HTTP Services.

*Android provides another way to deal with HTTP services, and that is using the,HttpURLConnection class.

* This is not unlike the HttpClient classes,but HttpURLConnection tends to require more
statements to get things done.

* On the other hand , this class is much smaller and lightweight than HttpClient.

* Starting with the Gingerbread release, it is also fairly stable.

* So,you should consider it for apps on more recent devices when you just need basic
HTTP features and you want a compact application.