Monday, October 17, 2011

Application Components in Android

  • Application components are the essential building blocks of an Android application.
  • Each component is a different point through which the system can enter your application. Not all components are actual entry points for the user and some depend on each other, but each one exists as its own entity and plays a specific role.
  • There are four different types of application components in android. And they are as follows:
    1.  Activities.
    2. Services.
    3. Content Providers.
    4. Broadcast Receiver
  • Android applications have more than one entry point. Whereas, java has only a single entry point. ( main() is the entry point in java)
  • Activities:
    •  An activity represents a single screen with a user interface.  For example consider an Email application, the following are called activities.
      1. Showing list of mails.
      2.  Composing a new mail.
      3. Reading a mail.
    •  Each activity is independent of the other activity. And can work together.
      • For example, Camera application can start an activity in the e-mail application that composes a new mail in order to share a picture.
    •  Each one is implemented as a subclass of the Activity base class.
    •  An application might consist of just a single activity or can contain multiple activities.
    •  Typically, one activity in an application specified as the main activity, which is presented to the user when an application is launching for the first time.
    •  Each activity can start another in order to perform some actions. When a new activity started the previous activity is stopped and pushed on to the back stack. The back stack works on LIFO (Last in First Out) mechanism.
    • Each activity gives a window to draw its user interface.
    • Typically, the window fills the screen, but it might be smaller than the screen and may float on top of other windows.
  • Services:
    •  A service does not have a visual user interface.
    •  A service is a component that runs in the background to perform long running operations or to perform work for remote processes.
      • Example:
        • Playing the music while the user is in a different application.
        • Fetching the data over the network without disturbance.
    •  Each service extends the Service base class.
    •  A service runs in the main thread of its hosting process—the service does not create its own thread and does not run in a separate process.
  • Broadcast Receivers:
    • A broadcast receiver is a component that does nothing but receives and reacts to broadcast announcements.
    • Broadcast announcements are of two types.
      1. System originated.
      2. Applications initiated.
      • System Originated:
        • Following are the examples of system originated broadcast announcements.

*       The screen has turned off.
*       Battery is low.
*       Picture has been captured.
*       The time zone has changed.


      • Application initiated:
        • Applications can also initiate the broadcast announcements
          • Announcing to other applications that some data has been downloaded to the device and is available for them to use.
    •  A broadcast receiver is just a gate way to other components and intended to do a very minimal amount of work.
      • Example: It might initiate a service to perform some work based on an event.
  • Content Providers:
    • A content Provider makes a specific set of the application's data available to other applications.
    • We can store the data in file system, an SQLite Database, on the web or any other persistent storage location your application can access.
    • The content provider extends the ContentProvider base class to implement a standard set of methods that enable other applications to retrieve and store data of the type it controls.
    • However, applications do not call these methods directly. Rather they use a ContentResolver object and call its methods instead. A ContentResolver can talk to any content provider; it cooperates with the provider to manage any inter process communication that's involved.

Friday, September 23, 2011

Android Application Fundamentals

  •  Android applications are written in the Java programming language.
  • The Android SDK tools compile the code—along with any data and resource files—into an Android package, an archive file with an .apk suffix.
    • By using the aapt tool, the data and resources bundled into a package.
    •   aapt- android asset packaging tool.
    • apk- android package kit.
  • The .apk file is used to install the applications on Android-powered devices.
  • Each Android application lives in its own world:
    •  By default, every application runs in its own Linux process.
    • Android starts the process when any of the application's code needs to be executed, and shuts down the process when it's no longer needed or when some system resources are required by other applications.
    •  Each process has its own virtual machine (VM), so application code runs in isolation from the code of all other applications.
    •  By default, each application is assigned a unique Linux user ID.
    • Permissions are set so that the application's files are visible only to that user, and to the application itself.
    • There are ways to export them to other applications as well:
      • It's possible to arrange for two applications to share the same user ID, in which case they will be able to see each other's files.
      • To conserve system resources, applications with the same ID can also arrange to run in the same Linux process, sharing the same VM.
  • An application can request permission to access device data such as the user's contacts, SMS messages, the mountable storage (SD card), camera, Bluetooth, and more. All application permissions must be granted by the user at install time.

Friday, September 16, 2011

Location Based Services in Android


Location Based Services
  •   Android gives our applications access to the location services through the classes in the android.location package.
  •  We can utilize GPS and Android’s Network Location Provider to acquire the user location.
  •   GPS provider:
    •  GPS is most accurate.
    •  It works only outdoors.
    •  Quickly consumes battery power.
    •  Doesn't return the location as quickly as user want.
  •  Network Location Provider:
    •  Determines the user location using the cell-tower and Wi-Fi signals.
    • It works indoors and outdoors.
    • Responds faster.
    • It uses less battery.
  • To obtain the user location we can use both GPS and Network Location Provider or just one.
  • Key classes:
    • LocationManager.
    • LocationProvider.
  • LcoationManager provides access to the system location services. This is done through getSystemService.
  • Using LocationManager class we can obtain periodic updates of the locations.
  • We can request location updates of devices using requestLocationUpdates() method. This method takes four parameters:
    •  Provider - The name of the location provider you wish to use.
    • minTime - The minimum time interval for notifications, in milliseconds.
    •  minDistance - The minimum distance interval for notifications, in meters.
    • listener - An object whose onLocationChanged() method will be called for each location update.
  •  In order to receive location updates we must request user permissions.
    •    NETWORK_PROVIDER – android.permission.ACCESS_COARSE_LOCATION.
    • GPS_PROVIDER -  android.permission.ACCESS_FINE_LOCATION.
  • The following statement should be added to the AndroidManifest.xml
    • < uses-permission android:name=”android.permission.ACCESS_FINE_LOCATION” />
  • If we are using both NETWORK_PROVIDER and GPS_PROVIDER, then we need to request only the ACCESS_FINE_LOCATION permission, because it includes permission for both providers.
  •   Using DDMS we can simulate location data in several ways through Emulator Controls. They are as follows:
    • Manually send individual longitude/latitude coordinates to the device.
    • Use a GPX file describing a route for playback to the device.
    • Use a KML file describing individual place marks for sequenced playback to the device.
  • To send location data through DDMS we must be sure that a device selected in the Devices panel. (Available from Window > Show View > Other > Devices).
Ø  Example:
Main.xml:
<?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="@string/hello"
    />
    <Button
       android:id="@+id/retrieve_location_button"
       android:text="Get Location"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       />
</LinearLayout>

GeoCoderActivity.java:
          package com.snigdha.android;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class GeoCoderExampleActivity extends Activity {
    /** Called when the activity is first created. */
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1;
    private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000;
    protected LocationManager locationManager;
   protected Button retrieveLocationButton;
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
 retrieveLocationButton = (Button) findViewById(R.id.retrieve_location_button);
 locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER,                              MINIMUM_TIME_BETWEEN_UPDATES,MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
                                   new MyLocationListener()   );
   retrieveLocationButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) { showCurrentLocation();
                               }
                       });                              
                       }  
   protected void showCurrentLocation() {
   Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    if (location != null) {
  String message = String.format( "Current Location \n Longitude: %1$s \n Latitude: %2$s",   location.getLongitude(), location.getLatitude()   );
   Toast.makeText(GeoCoderExampleActivity.this, message,                    Toast.LENGTH_LONG).show();
                  }
              } 
   private class MyLocationListener implements LocationListener {
       public void onLocationChanged(Location location) {
    String message = String.format( "New Location \n Longitude: %1$s \n Latitude: 2$s",   location.getLongitude(), location.getLatitude()       );
 Toast.makeText(GeoCoderExampleActivity.this, message, oast.LENGTH_LONG).show();
                           }
      public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(GeoCoderExampleActivity.this, "Provider status changed",
                                       Toast.LENGTH_LONG).show();
                           }
 public void onProviderDisabled(String s) {
Toast.makeText(GeoCoderExampleActivity.this, "Provider disabled by the user. GPS turned off", Toast.LENGTH_LONG).show();
        }
 public void onProviderEnabled(String s) {                        Toast.makeText(GeoCoderExampleActivity.this, "Provider enabled by the user. GPS turned on", Toast.LENGTH_LONG).show();
                           }
}
}
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.snigdha.android"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="8" />
   
    <uses-permission  android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

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

    </application>                                     
</manifest>
Screen Shots:

Figure-1                                                    


Figure - 2
Figure - 4
Figure - 3


                                                                                                                                                


  •  Figure-2 displaying the current location data retrieved by the provider.
  • Figure-3 and Figure -4 showing a toast messages when the GPS is disabled and enabled by the user.

Wednesday, September 14, 2011

Architecture of Android



Android Architecture
·                The following diagram shows the various layers that make up the Android operating system (OS).


·          Linux Kernel:
Ø  Android relies on Linux version 2.6 for core system services such as security, memory management, process management, network stack, and driver model.
Ø  The kernel also acts as an abstraction layer between the hardware and the rest of the software stack.
·          Android Runtime:
Ø  Core Libraries: Android includes a set of core libraries that provides most of the functionality available in the core libraries of the Java programming language.

Ø  Dalvik Virtual machine:
üEvery Android application runs in its own process, with its own instance of the Dalvik virtual machine.

üDalvik has been written so that a device can run multiple VMs efficiently. The Dalvik VM executes files in the Dalvik Executable (.dex) format which is optimized for minimal memory footprint.

üThe VM is register-based, and runs classes compiled by a Java language compiler that have been transformed into the .dex format by the included "dx" tool.

üThe Dalvik VM relies on the Linux kernel for underlying functionality such as threading and low-level memory management.

·         Libraries:
Ø  Android includes a set of C/C++ libraries used by various components of the Android system. These capabilities are exposed to developers through the Android application framework. Some of the core libraries are listed below:
ü  System C library - a BSD-derived implementation of the standard C system library (libc), tuned for embedded Linux-based devices
ü  Media Libraries - based on PacketVideo's OpenCORE; the libraries support playback and recording of many popular audio and video formats, as well as static image files, including MPEG4, H.264, MP3, AAC, AMR, JPG, and PNG
ü  Surface Manager - manages access to the display subsystem and seamlessly composites 2D and 3D graphic layers from multiple applications
ü  LibWebCore - a modern web browser engine which powers both the Android browser and an embeddable web view
ü  SGL - the underlying 2D graphics engine
ü  3D libraries - an implementation based on OpenGL ES 1.0 APIs; the libraries use either hardware 3D acceleration (where available) or the included, highly optimized 3D software rasterizer
ü  FreeType - bitmap and vector font rendering
ü  SQLite - a powerful and lightweight relational database engine available to all applications

·         Application Framework:
Ø   Android offers developers the ability to build extremely rich and innovative applications.
Ø   Developers are free to take advantage of the device hardware, access location information, run background services, set alarms, add notifications to the status bar, and much, much more.
Ø  Full access to the same framework APIs used by the core applications.
Ø  The application architecture is designed to simplify the reuse of components; any application can publish its capabilities and any other application may then make use of those capabilities.
Platform Services
Activity Manager
Hardware Services
Telephony Service
Package Manager
Bluetooth Service
Window Manager
Wi-Fi Service
Resource Manager
USB Service
Content Providers
Sensor Service
View System



Ø  Applications are the general applications that are pre shipped with the phone or downloaded and installed from the market.
Example:
§  A set of core applications including an email client, SMS program, calendar, maps, browser, contacts, and others.
Ø  All applications are written using the Java programming language.
Ø  Applications make use of Application Framework.