Friday, 26 December 2014

Android Application Fundamentals

Android apps are written in the Java programming language. The Android SDK tools compile your code—along with any data and resource files—into an APK: an Android package, which is an archive file with an .apk suffix. One APK file contains all the contents of an Android app and is the file that Android-powered devices use to install the app.

Once installed on a device, each Android app lives in its own security sandbox:

·         The Android operating system is a multi-user Linux system in which each app is a different user.

·         By default, the system assigns each app a unique Linux user ID (the ID is used only by the system and is unknown to the app). The system sets permissions for all the files in an app so that only the user ID assigned to that app can access them.

·         Each process has its own virtual machine (VM), so an app's code runs in isolation from other apps.

·         By default, every app runs in its own Linux process. Android starts the process when any of the app's components need to be executed, then shuts down the process when it's no longer needed or when the system must recover memory for other apps.

·         It's possible to arrange for two apps to share the same Linux user ID, in which case they are able to access each other's files. To conserve system resources, apps with the same user ID can also arrange to run in the same Linux process and share the same VM (the apps must also be signed with the same certificate).

·         An app 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 app permissions must be granted by the user at install time.

·         The core framework components that define your app.

·         The manifest file in which you declare components and required device features for your app.

·         Resources that are separate from the app code and allow your app to gracefully optimize its behavior for a variety of device configurations.


Android Application Building Blocks

App components are the essential building blocks of an Android app. Each component is a different point through which the system can enter your app. 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—each one is a unique building block that helps define your app's overall behavior.

There are 4 building blocks in android:

1.       Activity    
2.       Service 
3.       Content Provider
4.       Broadcast Receiver

Activity:

An activity represents a single screen with a user interface. For example, an email app might have one activity that shows a list of new emails, another activity to compose an email, and another activity for reading emails. Although the activities work together to form a cohesive user experience in the email app, each one is independent of the others. As such, a different app can start any one of these activities (if the email app allows it). For example, a camera app can start the activity in the email app that composes new mail, in order for the user to share a picture.

Services:

A service is a component that runs in the background to perform long-running operations or to perform work for remote processes. A service does not provide a user interface. For example, a service might play music in the background while the user is in a different app, or it might fetch data over the network without blocking user interaction with an activity. Another component, such as an activity, can start the service and let it run or bind to it in order to interact with it.

Content providers:

A content provider manages a shared set of app data. You can store the data in the file system,  SQLite database, on the web, or any other persistent storage location your app can access. Through the content provider, other apps can query or even modify the data (if the content provider allows it). For example, the Android system provides a content provider that manages the user's contact information. As such, any app with the proper permissions can query part of the content provider (such as ContactsContract.Data) to read and write information about a particular person.

Content providers are also useful for reading and writing data that is private to your app and not shared. For example, the Note Pad sample app uses a content provider to save notes.

Broadcast receiver:

A broadcast receiver is a component that responds to system-wide broadcast announcements. Many broadcasts originate from the system—for example, a broadcast announcing that the screen has turned off, the battery is low, or a picture was captured. Apps can also initiate broadcasts—for example, to let other apps know that some data has been downloaded to the device and is available for them to use. Although broadcast receivers don't display a user interface, they may create a status bar notification to alert the user when a broadcast event occurs. More commonly, though, a broadcast receiver is just a "gateway" to other components and is intended to do a very minimal amount of work. For instance, it might initiate a service to perform some work based on the event.

Activating Components

Three of the four component types—activities, services, and broadcast receivers—are activated by an asynchronous message called an intent. Intents bind individual components to each other at runtime (you can think of them as the messengers that request an action from other components), whether the component belongs to your app or another.

An intent is created with an Intent object, which defines a message to activate either a specific component or a specific type of component—an intent can be either explicit or implicit, respectively.

For activities and services, an intent defines the action to perform (for example, to "view" or "send" something) and may specify the URI of the data to act on (among other things that the component being started might need to know). For example, an intent might convey a request for an activity to show an image or to open a web page. In some cases, you can start an activity to receive a result, in which case, the activity also returns the result in an Intent (for example, you can issue an intent to let the user pick a personal contact and have it returned to you—the return intent includes a URI pointing to the chosen contact).

For broadcast receivers, the intent simply defines the announcement being broadcast (for example, a broadcast to indicate the device battery is low includes only a known action string that indicates "battery is low").

The other component type, content provider, is not activated by intents. Rather, it is activated when targeted by a request from a ContentResolver. The content resolver handles all direct transactions with the content provider so that the component that's performing transactions with the provider doesn't need to and instead calls methods on the ContentResolver object. This leaves a layer of abstraction between the content provider and the component requesting information (for security).

There are separate methods for activating each type of component:

·         You can start an activity (or give it something new to do) by passing an Intent to startActivity() or startActivityForResult() (when you want the activity to return a result).

·         You can start a service (or give new instructions to an ongoing service) by passing an Intent to startService(). Or you can bind to the service by passing an Intent to bindService().

·         You can initiate a broadcast by passing an Intent to methods like sendBroadcast(), sendOrderedBroadcast(), or sendStickyBroadcast().

·         You can perform a query to a content provider by calling query() on a ContentResolver.

Shutting down Components

There are separate methods for shutting down each type of component:

·         You can stop an activity by calling finish() (Call this when your activity is done and should be closed.)or finishActivity() (Force finish another activity that you had previously started with startActivityForResult()).

·         You can stop a service by calling stopSelf() (Stop the service, if it was previously started.) or stopSelfResult()  (Be careful about ordering of your calls to this function.. If you call this function with the most-recently received ID before you have called it for previously received IDs, the service will be immediately stopped anyway) or Context.stopService() (Request that a given application service be stopped. If the service is not running, nothing happens. Otherwise it is stopped. Note that calls to startService() are not counted -- this stops the service no matter how many times it was started) or Context.unbindService() (Disconnect from an application service. You will no longer receive calls as the service is restarted, and the service is now allowed to stop at any time).

·         You can unregister a BroadcastReceiver by calling Context. unregisterReceiver() (Unregister a previously registered BroadcastReceiver. All filters that have been registered for this BroadcastReceiver will be removed).

Tuesday, 9 December 2014

Android Environment Setup

System requirements:

Operating Systems

·         Windows XP (32-bit), Vista (32- or 64-bit), or Windows 7 (32- or 64-bit)
·         Mac OS X 10.8.5 or later
·         Linux 64-bit distribution capable of running 32-bit applications
·         GNU C Library (glibc) 2.11 or later is required.
·         Tested on Ubuntu 12.04, Precise Pangolin

Development tools

·         JDK 6 (JRE alone is not sufficient)
·         Apache Ant 1.8 or later
·         Not compatible with Gnu Compiler for Java (gcj)

Note: Some Linux distributions may include JDK 1.4 or Gnu Compiler for Java, both of which are not supported for Android development.

Setup Java Development Kit (JDK)

You can download the latest version of Java JDK from Oracle's Java site: http://www.oracle.com/technetwork/java/javase/downloads/index.html. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively. 
If you are running Windows and installed the JDK in C:\jdk1.6.0_15, you would have to put the following line in your C:\autoexec.bat file. 
set PATH=C:\jdk1.6.0_15\bin;%PATH%
set JAVA_HOME=C:\jdk1.6.0_15

Alternatively, you could also right-click on My Computer, select Properties, then Advanced, then Environment Variables. Then, you would update the PATH value and press the OK button.
On Linux, if the SDK is installed in /usr/local/jdk1.6.0_15 and you use the C shell, you would put the following code into your .cshrc file.

setenv PATH /usr/local/jdk1.6.0_15/bin:$PATH
setenv JAVA_HOME /usr/local/jdk1.6.0_15
Alternatively, if you use an Integrated Development Environment (IDE) Eclipse, then it will know automatically where you have installed your Java.

Installing the Eclipse ADT Bundle

The Eclipse ADT Bundle provides everything you need to start developing apps, including the Android SDK tools and a version of the Eclipse IDE with built-in ADT (Android Developer Tools) to streamline your Android app development.

If you didn't download the Eclipse ADT bundle, go http://developer.android.com/sdk/index.html.

To set up the ADT Bundle:

1.       Unpack the ZIP file (named adt-bundle-<os_platform>.zip) and save it to an appropriate location, such as a "Development" directory in your home directory.
2.       Open the adt-bundle-<os_platform>/eclipse/ directory and launch Eclipse.
Caution: Do not move any of the files or directories from the adt-bundle-<os_platform> directory. If you move the eclipse/ or sdk/ directory, ADT will not be able to locate the SDK and you'll need to manually update the ADT preferences.

Eclipse with ADT is now ready and loaded with the Android developer tools, but there are still a couple packages you should add to make your Android SDK complete.

Adding SDK Packages

By default, the Android SDK does not include everything you need to start developing. The SDK separates tools, platforms, and other components into packages you can download as needed using the Android SDK Manager. So before you can start, there are a few packages you should add to your Android SDK. Click here to download Android SDK http://developer.android.com/tools/help/sdk-manager.html 
To start adding packages, launch the Android SDK Manager in one of the following ways:
·         In Eclipse or Android Studio, click SDK Manager  in the toolbar.

·         If you're not using Eclipse or Android Studio:
      • Windows: Double-click the SDK Manager.exe file at the root of the Android SDK directory.
      • Mac/Linux: Open a terminal and navigate to the tools/ directory in the Android SDK, then execute android sdk.

When you open the SDK Manager for the first time, several packages will be selected by default. Leave these selected, but be sure you have everything you need to get started by following these steps:

Once you launched SDK manager, it’s time to install other required packages. By default it will list down total 7 packages to be installed, but I will suggest de-selecting Documentation for Android SDK and Samples for SDK packages to reduce installation time. Next click Install 7 Packages button to proceed, which will display following dialogue box:


If you agree to install all the packages, select Accept All radio button and proceed by clicking Install button. Now let SDK manager do its work and you go, pick up a cup of coffee and wait until all the packages are installed. It may take some time depending on your internet connection. Once all the packages are installed, you can close SDK manager using top-right cross button.

Setup Android Development Tools (ADT) Plugin

This step will help you in setting Android Development Tool plugin for Eclipse. Let's start with launching Eclipse and then, choose Help > Software Updates > Install New Software. This will display the following dialogue box.


Now use Add button to add ADT Plugin as name and https://dl-ssl.google.com/android/eclipse/ as the location. Then click OK to add this location, as soon as you will click OK button to add this location, Eclipse starts searching for the plug-in available the given location and finally lists down the found plugins.


Now select all the listed plug-ins using Select All button and click Next button which will guide you ahead to install Android Development Tools and other required plugins.

Create Android Virtual Device

To test your Android applications you will need a virtual Android device. So before we start writing our code, let us create an Android virtual device. Launch Android AVD Manager using Eclipse menu options Window > AVD Manager> which will launch Android AVD Manager. Use New button to create a new Android Virtual Device and enter the following information, before clicking Create AVD button.


If your AVD is created successfully it means your environment is ready for Android application development. If you like, you can close this window using top-right cross button. Better you re-start your machine and once you are done with this last step, you are ready to proceed for your first Android example but before that we will see few more important concepts related to Android Application Development.


Wednesday, 3 December 2014

Android Development Tools

Android SDK:

The Android SDK (software development kit) is a set of development tools used to develop applications for Android platform. 

The Android SDK includes the following:
  • Required libraries
  • Debugger
  • An emulator
  • Relevant documentation for the Android application program interfaces (APIs)
  • Sample source code
  • Tutorials for the Android OS

Every time Google releases a new version of Android, a corresponding SDK is also released. To be able to write programs with the latest features, developers must download and install each version’s SDK for the particular phone. 


Android debug bridge (adb):

Android Debug Bridge (adb) is a versatile command line tool that lets you communicate with an emulator instance or connected Android-powered device.
What ADB do's:
Phone rooting: This is the basic and most common function which in fact is compulsory for Android developers willing to root Nexus or any other Android device.
App side loading: If you want to install an application that’s either not available on Google Play in your location or was removed from the store (like Flappy Bird), then ADB comes handy again. The adb install command will install an APK file onto your Android device, on the condition that you have enabled installation of applications from unknown sources in settings.
Files Push and Pull between a PC and an Android device: Adb push and adb pull, let you easily transfer files between your PC and Android device. Again, this is more helpful when you’re working with rooted devices, since you can achieve the same end using Windows File Explorer
Even more handy commands:  A lot of functions like flashing ROMs to your phone require you to boot into recovery mode. Normally, this requires you to hold down a particular set of buttons on your phone for a certain length of time, which is obnoxious. With ADB, you can install a ROM stored on the computer (helpful if running low on external sd memory). This even gives the command to flash a recovery image which has been topic for those with an unlocked boot loader that have been receiving the unlocked boot loader error message on reboot.


Dalvik Virtual Machine (DVM):

A virtual machine optimized for mobile devices that was designed and written by Dan Bornstein and other Google engineers. Dalvik is a part of the software stack that makes up the Android platform.

According to Google's Android documentation, the Dalvik VM is an interpreter-only virtual machine that executes files in the Dalvik Executable (.dex) format, a format that is optimized for efficient storage and memory-mappable execution. The virtual machine is register-based, and it can run classes compiled by a Java language compiler that have been transformed into its native format.


Android RunTime (ART):

Android Runtime (ART) is an application runtime environment used by the Android mobile operating system. ART replaces Dalvik, which is the process virtual machine originally used by Android, and performs transformation of the application's bytecode into native instructions that are later executed by the device's runtime environment.


DDMS:

DDMS stands for Dalvik debug monitor server, that provide many services on the device. The service could include message formation,call spoofing , capturing screenshot , exploring internal threads and file systems e.t.c.

Tuesday, 2 December 2014

Android Architecture


The above figure shows the diagram of Android Architecture. The Android OS can be referred to as a software stack of different layers, where each layer is a group of sveral  program components. Together it includes operating system, middleware and important applications. Each layer in the architecture provides different services to the layer just above it. We will examine the features of each layer in detail.

Linux Kernel

The basic layer is the Linux kernel.


The whole Android OS is built on top of the Linux 2.6 Kernel with some further architectural changes made by Google.  It is this Linux that interacts with the hardware and contains all the essential hardware drivers. Drivers are programs that control and communicate with the hardware. For example, consider the Bluetooth function. All devices has a Bluetooth hardware in it. Therefore the kernel must include a Bluetooth driver to communicate with the Bluetooth hardware.  The Linux kernel also  acts as an abstraction layer between the hardware and other software layers. Android uses the Linux for all its core functionality such as Memory management, process management, networking, security settings etc. As the Android is built on a most popular and proven foundation, it made the porting of Android to variety of hardware, a relatively painless task.

Libraries

The next layer is the Android’s native libraries.


It is this layer that enables the device to handle different types of data. These libraries are written in c or c++ language and are specific for a particular hardware.
Some of the important native libraries include the following:

Surface Manager: 

It is used for compositing window manager with off-screen buffering. Off-screen buffering means you cant directly draw into the screen, but your drawings go to the off-screen buffer. There it is combined with other drawings and form the final screen the user will see. This off screen buffer is the reason behind the transparency of windows.


Media framework: 

Media framework provides different media codecs allowing the recording and playback of different media formats.

SQLite: 

SQLite is the database engine used in android for data storage purposes

WebKit:
It is the browser engine used to display HTML content

OpenGL:
Used to render 2D or 3D graphics content to the screen

Android Runtime

Android Runtime consists of Dalvik Virtual machine and Core Java libraries.


Dalvik Virtual Machine

It is a type of JVM used in android devices to run apps and is optimized for low processing power and low memory environments. Unlike the JVM, the Dalvik Virtual Machine doesn’t run .class files, instead it runs .dex files. .dex files are built from .class file at the time of compilation and provides hifger efficiency in low resource environments. The Dalvik VM allows multiple instance of Virtual machine to be created simultaneously providing security, isolation, memory management and threading support. It is developed by Dan Bornstein of Google.

Core Java Libraries

These are different from Java SE and Java ME libraries. However these libraries provides most of the functionalities defined in the Java SE libraries.


Application Framework


These are the blocks that our applications directly interacts with. These programs manage the basic functions of phone like resource management, voice call management etc. As a developer, you just consider these are some basic tools with which we are building our applications.
Important blocks of Application framework are:

Activity Manager
Manages the activity life cycle of applications

Content Providers:
 Manage the data sharing between applications

Telephony Manager: 
Manages all voice calls. We use telephony manager if we want to access voice calls in our application.

Location Manager: 
Location management, using GPS or cell tower

Resource Manager: 
Manage the various types of resources we use in our Application


Applications

Applications are the top layer in the Android architecture and this is where our applications are gonna fit.


 Several standard applications comes pre-installed with every device, such as:
    • SMS client app
    • Dialer
    • Web browser
    • Contact manager

< Prev What is Android?