WHAT IS ANDROID?
Google + OHA (Open Handset Alliance)
The first truly open and comprehensive platform for mobile devices, all of the software to run a mobile
phone but without the proprietary obstacles that have hindered mobile innovation.
Linux OS kernel
Java programming
Open source libraries: SQLite, WebKit, OpenGL
ANDROID SDK FEATURE
GSM, EDGE, and 3G networks, WiFi, Bluetooth
API Support for Bluetoothe, WiFi Ad hoc mode
Libraries
Media, SQLite, WebKit, SSL
Hardware control:
Accelerometer, compass, microphone, camera, GPS
touch screen, power
Location-based service, map (Google API) & Facebook ,gmail and Twitter Support(Api's)
TOOLS
The Android Emulator
Implementation of the Android virtual machine
Test and debug your android applications.
Dalvik Debug Monitoring Service (DDMS)
Monitor and Control the Dalvik virtual machines
Logcat (see logged msgs)
Android Debug Bridge (ADB)
Manage the state of an emulator instance or Android-powered device
Copy files, install compiled application packages, and run shell commands.
Traceview
Graphical analysis tool for viewing the trace logs from your Android application
Debug your application and profile its performance
MkSDCard
Creates an SDCard disk image
Tools that are found in android Sdk are:
Sdk Tools----Platform Independent tools
Platform-tools
The tools are classified into two groups: SDK tools and platform tools. SDK tools are platform independent and are required no matter which Android platform you are developing on. Platform tools are customized to support the features of the latest Android platform.
SDK Tools is a downloadable component for the Android SDK. It includes the complete set of development and debugging tools for the Android SDK like emulator, sdcard, sqlite and apk builder etc.. Where as Platform-tools are used to support the features for the current android platform including adb which is acting like a bridge to communicate with emulator or device.
Android Sdk Tools
Android SDK Manager (android sdk
)
AVD Manager (android avd
) the emulator (emulator
)
Dalvik Debug Monitor Server (ddms
)
SqliteManager
Apk Builder
Platform-tools
Aidl, aapt
, dexdump
, and dx are generally called by android ADT or android build tool
Android Debug Bridge (ADB)
The Android Debug Bridge (ADB) is a client-server program used in Android application development. The Android Debug-Bridge is part of the Android SDK and is made up of three components: a client, a daemon, and a server. It is used to manage either an emulator instance or an actual Android device.
ADB ia android Platform tool that lets u communicate with emulator or actual device.
BY Android.developer:
Android Debug Bridge (adb) is a versatile command line tool that lets you communicate with an emulator instance or connected Android-powered device. It is a part of android Sdk.It is a client-server program that includes three components:
A client, which runs on your development machine. You can invoke a client from a shell by issuing an adb command. Other Android tools such as the ADT plugin and DDMS also create adb clients.
A server, which runs as a background process on your development machine. The server manages communication between the client and the adb daemon running on an emulator or device.
A daemon, which runs as a background process on each emulator or device instance.
NOTE
:
You can find the
adb
tool in
<sdk>/platform-tools/
.
DDMS
The Dalvik Debug Monitor Service (DDMS) is a debugging utility that is integrated into Eclipse through the DDMS perspective. The DDMS perspective provides a number of useful features for interacting with emulators and handsets
The features of DDMS are roughly divided into five functional areas:
Task management
File management
Emulator interaction
Logging
Screen captures(Device -->sceen capture icon)
Thread and heap information on the device
Devices
Navigator
Emulator Control
Allocation Tracker—Tracking memory allocation to each virtual machine
AVD MANAGER
The AVD Manager provides a graphical user interface in which you can create and manage Android Virtual Devices (AVDs), which are required by the Android Emulator.
You can launch the AVD Manager in one of the following ways:
In Eclipse: select Window > AVD Manager, or click the AVD Manager icon in the Eclipse toolbar.
In other IDEs: Navigate to your SDK's tools/
directory and execute android avd
.
ADT(Android Developer Tool)
ADT (Android Developer Tools) is a plugin for Eclipse that provides a suite of tools that are integrated with the Eclipse IDE
*************************************************************************************************
Thu 14 Mar 2013 10:41:13 AM IST
Loaders in Android
Introduced in Android 3.0, loaders make it easy to asynchronously load data in an activity or fragment.
Main Characteristics of Loaders
Provides Asychronous Loading of Data.
Available to evry activity or fragment.
Monitor source of data and deliver new results when content changes.
Automatically reconnect to last loaders cursor after a configuration change so no need to query them again.
Loader Api---Consist of classes & Interfaces for implementing loaders in Android
●
LoaderManager—Associated with Activity/Fragment for Managing one or more Loader Instance commonly used with cursorloader class.
●
LoaderManager.Loadercallbacks—Callbacks for a client to interact with loader as:
oncreateLoader()--
Instantiate and return a new Loader for the given ID.
onLoadfinished()-
Called when a previously created loader has finished its load.
onLoaderReset()—called when previous loader is reset so that making its old data unavailable.
●
Loader—This is the base class for loader which is used for asynchronously loading data
●
AsyncTaskLoader--Abstract loader that provides an AsyncTask
to do the work
●
CursorLoader--A subclass of AsyncTaskLoader
that queries the ContentResolver
and returns a Cursor. This class implements the Loader
protocol in a standard way for querying cursors, building on AsyncTaskLoader
to perform the cursor query on a background thread so that it does not block the application's UI. Using this loader is the best way to asynchronously load data from a ContentProvider, instead of performing a managed query through the fragment or activity's APIs.
A CursorLoader is used
to load data backed by a ContentProvider.
Starting a Loader
getLoaderManager().initLoader(0, null, this);
A cursorloader gets that data from your data source and loads it into a cursor then manages the cursor. A cursor is basically an in memory data storage construct.
An adapter takes the data from the cursor (or array or list) and puts into your display layout to be viewed.
Importance of Loader
Loader importance is that before them we need to requerry again and agin but after using loader with cursor we dont have to requerry again anda agin for data after configuration changes or acticity stated comes from stop state.
***Basically speaking loaders are used to avoid requerrying
CursorLoader auto updates, so no need to requery the cursor
NOTE:
Earlier we were using Activity.managedQuery or Activity.startManagingCursor which needs requeery on configuration changes. As it is not been able to update databse automatically so this problem has been sort out by Loaders in Android.
Asynchoronous Loading of Data
Loading data into its own thread(Separate thread from main thread) not in the main thread of the application so to avoid interruptation in loading data and reducing burden on CPU.
Means loading of data without affecting other parts of the program/Application.
CURSOR
A database cursor is an object used to pinpoint records in a database.
When a database file is opened, the cursor points to the first record in the file, and using various commands the cursor can move to any location within the file.
A cursor is used to perform database operations on a set of data.
Cursors are database objects used to traverse the results of an SQL query. They point to a certain location within a recordset and allow the operator to move forward (and sometimes backward, depending upon the cursor type) through the results one record at a time. Cursors are often criticized for their high overhead.
cursors in data base are generally pointers which points to one row at a time.
It returns a pointer which is directed to a recoed set in Database.
Friday, March 15 2013
APK File Format
Stands for Android Application Package kit
Each Android application is compiled and packaged in a single file that includes all of the application's code (.dex files), resources, assets, and manifest file.
Android programs are compiled into .dex (Dalvik Executable) files, which are in turn zipped into a single
.apk file on the device. .dex files can be created by automatically translating compiled applications written in
the Java programming language.
The APK file is compressed the AndroidManifest.xml file, application code (.dex files), resource files, and
other files. A project is compiled into a single .apk file.
.DEX Files
Compiled Android application code file.
Android programs are compiled into .dex (Dalvik Executable) files, which are in turn zipped into a single .apk file on the device. .dex files can be created by automatically translating compiled applications written in the Java programming language.
dex is a binary code
How to develop Dalvik files in Android
Programs are commonly written in Java and compiled to bytecode. They are then converted from Java Virtual Machine-compatible .class files to Dalvik-compatible .dex (Dalvik Executable) files before installation on a device. The compact Dalvik Executable format is designed to be suitable for systems that are constrained in terms of memory andprocessor speed.
Java Code------by Jvm-------->Byte code(.class files)------DEX Compiler----->.dex-----Zipped--->.apk------then executed by DVM
Note: Apk files are executed by DVM only
Difference between DVM and JVM
DVM is register baseed Architecture.
Designed to run on low Memory
Uses it own byte code(Optimised bytecode for mobile devices)
Runs only .dex(Dalvik executable files)
Needs low memory and low Power
Mainly for mobile
JVM is stack based Architecture
Uses java Byte code
Runs .class files having JIT
Needs more memory and more power as compare to DVM
Computers and laptops
API Level in Android
"API Level is an integer value that uniquely identifies the framework API revision offered by a version of the Android platform."
Basically defines the various updated revisions of a particular version.
It consist of following:
A core set of packages and classes
A set of XML elements and attributes for declaring a manifest file
A set of XML elements and attributes for declaring and accessing resources
A set of Intents
A set of permissions that applications can request, as well as permission enforcements included in the system
Thur 07 Mar 2013 08:10:17 PM IST
LINUX
• free and open source software
• The defining component of Linux is the Linux kernel, an operating system kernel.
• leading operating system on servers and other big iron systems such as mainframe computers,embedded systems and supercomputers
• Main OS for fast operating systems.
• Android system is build on Linux Kernel
• Popular Linux are: Ubuntu and Linux Mint
About Linux Architecture
http://vedyadhara.ignou.ac.in/wiki/images/5/5f/OSEI-044_Block-3_Unit-1.pdf
Main Components of Linux Architecture
1.Hard Ware ---inner most
2.Kernel --After 1.
3.Shell --After 2.
4.(Compilers, Tools , utilities, App programming etc) --Last in Linux Architecture
Shell- It is the command Interpreter which reads users command one by one which user types in Linux Terminal.
Kernel--Kernel is the innermost component of Linux Architecture. It makes direct contact with the Hardware & performs following functions as:
• creation and deletion of processes
• synchronization of processes
• inter process communication.
• schedule the memory management
• I/O management of the processor.
The kernel is a program that constitutes the central core of a computer operating system. It has complete control over everything that occurs in the system.
The kernel is responsible for memory management, process and task management, and disk management.
Kernel is the first part of operating system to load into memory during booting and remain till session closes.
When a computer crashes, it actually means the kernel has crashed.
Kernel act as abstraction layer between hardware and rest of the software stack.
Contents of a kernel
Scheduler
Interrupt Handler
Supervisor
Memory Manager
Categories of Kernels
Monolithic kernels--performs core functions and device drivers
Micro kernels-- provides only minimal services, such as defining memory address spaces, inter-process communication (IPC) and Process management.
Hybrid Kernels--Similar to Micro kernels except provides additional code in kernel Space for high performance.
Exokernels--Still a Experimental approach.
Difference between Monolithic and microlithic kernels
Mono as name suggest everything in a single huge unit called monolithic.It contains all services and management in a Kernel Space.
Microlithic only small portion of basic services are kept in kernel space & other put in users space called servers.
Thu 07 Mar 2013 02:20:35 PM IST
Android Linux Architecture
Android is a software platform for mobile devices which runs on Linux Operating System and developed by Google.
O.S.--Linux Kernel Version 2.6
Emulator--Mac,Windows , Linux
Hardware Support
• Gsm Telephony
• Blue-tooth ,3G,Wifi
• Camera,GPS,Compass & Accelerometer
For Linux Diagram go to ---http://www.android-app-market.com/android-architecture.html
Main Layers of Android Architecture Diagram are:
i)Applications
• Home
• Contacts
• Phones
• Browser
• Your app
ii)Applications Framework
• Activity manager
• Window Manager
• Content provider
• View System
• Package Manager
• Telephony Manager
• Resource Manager
• Location Manager
• Notification Manager
iii)Libraries
• Surface Manager
• Media framework
• Sq-lite
• OpenGls
• Free Type
• Web Kit
• SGL
• SSL
• libc
Android Run-time
• Core Libraries
• Dalvik Virtual Machine
iv)Linux Kernel
• Display Driver
• Camera Driver
• Flash Memory Driver
• Binder(IPC) Driver
• Keypad Driver
• Wifi driver
• Audio drivers
• Power Management
Applications
It is the top layer in android Architecture and it is the place where our Applications are going to fit. For Ex...
Sms client App
Dialer
Web Browser etc..
Applications Framework
Here we have block of programs to which our applications directly Interact.
This part manages the basic part of phone as resource management, voice call management etc. Example:
Activity Manager,Content Providers,Telephony Manager,Location Manager,Resource Manager
Libraries
It helps device in handling different types of data. These libraries are written in c or c++ language and are specific for a particular hardware.
Example:
Surface Manager
Media framework Sq-lite,OpenGls,Free Type,Web Kit,SGL,SSL,libc.
Android Run time
It consist of following as:
Dalvik Virtual Machine
Core Java Libraries
DVM(Dalvik Virtual Machine)
DVM is similar to JVM but it needs low memory and consumes low Power hence exclusively made for mobile ,It runs .dex files instead of .class files, where as JVM can run on any environment(that is global) but exclusively made for android(i.e. Linux OS)
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.
It consist of classes which are used by many portions of Jdk.
They include functionality which is close to the VM and is not explicitly included in other areas.
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 Blue tooth function. All devices has a Blue tooth hardware in it. Therefore the kernel must include a Blue tooth driver to communicate with the Blue tooth 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.
*****************************
Difference between SE , EE , ME library
JavaSE = Standard Edition. This is the core Java programming platform. It contains all of the libraries and APIs that any Java programmer should learn (java.lang, java.io, java.math, java.net, java. util, etc...).
JavaEE = Enterprise Edition. From wikipedia: "The Java platform (Enterprise Edition) differs from the Java Standard Edition Platform (Java SE) in that it adds libraries which provide functionality to deploy fault-tolerant, distributed, multi-tier Java software, based largely on modular components running on an application server."Basically for a large scale , distributed system.
JavaME = Micro Edition. This is the platform for developing applications for mobile devices and embedded systems such as set-top boxes.
javaME provides a subset of the functionality of JavaSE, but also introduces libraries specific to mobile devices.
Monday, March 11 2013
dkarora@modexindia.com
CONTENT PROVIDER
Content Providers are used when you want to share your data across applications.
When we want to share data between different applications then we have to use content Provider becoz sqlite does not share data with other application>it can only share data with its own application.
Content Provider act as a bridge between applications to share data between them. It does not matters which type of database we are using.
Basically content Providers are only used when we want to share data between applications otherwise we generally dont use them.
The ContentResolver/ContentProvider mechanism is used to allow applications to share information across applications. Although it could be used to share data inside a single application, it is probably overkill
Content Providers are the Android platforms way of sharing information betweeen multiple applications through its ContentResolver interface. Each application has access to the SQLite database to maintain their information and this cannot be shared with another application.
Example of Content Provider--ContentProvider in AbhishekWorkspace
Common example of Content Provider in Android is Users Dictionary which stores the spellings of non-standard words that the user wants to keep.
The ContentResolver job is to dispatch your commands to a ContentProvider, based on the uri you provide
A ContentResolver can talk to any content provider; it cooperates with the provider to manage any interprocess communication that's involved.
This class provides applications access to the content model.
The ContentResolver object communicates with the provider object, an instance of a class that implements ContentProvider. The provider object receives data requests from clients, performs the requested action, and returns the results.
getContentResolver()----Return a ContentResolver instance for your application's package.
Working Content Provider
Content Provider share date between various application through its content Resolver Interface which communicates with provider of application through getcontentResolver() method which returns contentResolver instance of our application
Difference between Content Provider & Content Resolver
ContentResolver allows your application to communicate with other
applications' ContentProviders.
ContentValues is a container for name-value pairs that are used to
insert or modify a row in a ContentProvider.
Accessing Data from content provider
An application accesses the data from a content provider with a ContentResolver client object. This object has methods that call identically-named methods in the provider object, an instance of one of the concrete subclasses of ContentProvider. The ContentResolver methods provide the basic "CRUD" (create, retrieve, update, and delete) functions of persistent storage.
ContentResolver object automatically handles IPC handling between Applications which owns Provider.
To access a provider, your application usually has to request specific permissions in its manifest file.
Example of Providers in Android: Calender Provider & Contacts Provider
// Get content provider and cursor
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(Settings.System.CONTENT_URI, null, null, null, null);
// Queries the user dictionary and returns results
mCursor = getContentResolver().query(
UserDictionary.Words.CONTENT_URI, // The content URI of the words table
mProjection, // The columns to return for each row
mSelectionClause // Selection criteria
mSelectionArgs, // Selection criteria
mSortOrder); // The sort order for the returned rows
Query format which is used: query(Uri,projection,selection,selectionArgs,sortOrder)
Uri FROM table_name Uri maps to the table in the provider named table_name.
projection col,col,col,... projection is an array of columns that should be included for each row retrieved.
selection WHERE col = value selection specifies the criteria for selecting rows.
selectionArgs (No exact equivalent. Selection arguments replace ? placeholders in the selection clause.)
sortOrder ORDER BY col,col,... sortOrder specifies the order in which rows appear in the returned Cursor.
**********************************************************************************************************
Content provider is an essential component in Android applications. The main use of content provider is to share data between applications. In Android all application resources like files, database etc. are private to the application, so content provider is the solution to share data between applications.
**********************************************************************************************************************************
Why does Android System need Content Providers?
The need for Content Providers arises because the database created in one application is not visible to a second application.
It is simple to create and store database in different applications using SQLite, however the problem is this, a database in Android is private to the application that creates it. There is no common storage area in Android that every application can access. Therefore, for different applications to use a database, Android system needs an interface that allows such inter-application and inter-process data exchange. This is where content provider comes to play.
Do I really need a Content Provider?
1) You do not need to develop your own provider if you want a private database for a particular application (this database would not be accessible to applications other than the one that created it).
2) You however need a Custom provider to provide custom search suggestions in your own application system.
3) You would also need a Content Provider to copy and paste complex data from your application to other applications.
What are the operations supported by a Content Provider?
Content providers support the following basic operations:
1) Querying: Queries the Content Provider for all the objects, based on the specified URI.
2) Delete: Deletes the specified objects from the database of a Content Provider.
3) Update: Makes updates to the objects in the database.
4) Insert: Inserts new object to the database.
URI
Android uses URI strings as the basis for requesting data in a content provider (such as to retrieve a list of contacts) and for requesting actions in an Intent (such as opening a Web page in a browser). The URI scheme and format is specialized according to the type of use, and an application can handle specific URI schemes and strings in any way it wants. Some URI schemes are reserved by system components. For example, requests for data from a content provider must use the content://. In an Intent, a URI using an http:// scheme will be handled by the browser.
Andriod Developers - Cite This Source - This Definition
Browse Related Terms: Action, Content Provider, Content URI, Query String, URIs
Uniform Resource Identifier (URI)
● A URI is a string of characters that identifies a resource ●
Uniform – means that different types of resource identifiers can be used in the same context even when their access mechanisms are different
● Resource – means anything that has an identity (e.g., a document, an image, a service)
● Identifier – means that it is a reference to a resource that with an identity (e.g., a sequence of characters with specific syntactic restrictions)http://www.youtube.com/vkedco http://www.vkedco.blogspot.com
A Uri is an address that points to something of significance. In the case of ContentProviders, the Uri is usually used to determine which table to use. So event_uri points to the events table and the reminder_uri points to the reminders table. There is really no "default value" for uris.
In the previous lines of code, the full URI for the "words" table is:
content://user_dictionary/words
where the user_dictionary string is the provider's authority, and words string is the table's path. The string content:// (the scheme) is always present, and identifies this as a content URI.
Today: Wednesday, March 13 2013
Marshalling
In computer science, Marshalling (sometimes spelled marshaling with a single l) is the process of transforming the memory representation of an object to a data format suitable for storage or transmission, and it is typically used when data must be moved between different parts of a computer program or from one program to another or from one application or process to another application or Process.
Marshalling is similar to serialization and is used to communicate to remote objects with an object, in this case a serialized object. It simplifies complex communication, using custom/complex objects to communicate instead of primitives. The opposite, or reverse, of marshalling is called unmarshalling (or demarshalling, similar to de-serialization).
UnMarshalling
It reverse of marshaling or u can say that it is de-serialization.
In Android AIDL(Android Interface Definition Language) act as alternative to marshalling
Stub in Android
It is class that implements Remote Interface in way u can use it as if it were a local class.
Basically its main function is to handle marshalling and unmarshalling & sending/receiving to/from the remote service.
It is used with AIDL in Android.
AIDL(Android Interface Definition Language)
On Android, one process cannot normally access the memory of another process. So to talk, they need to decompose their objects into primitives that the operating system can understand, and marshall the objects across that boundary for you. The code to do that marshalling is tedious to write, so Android handles it for you with AIDL.
In Android a process normally cannot access memory of another process hence 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
Steps in creating Android Aidl
• First of all we need to create interface that will be a Aidl file which will be created in inside Project_name/src/Packatge_name.
• After this it is necessary to compile this interface by running the project as after this a same java file will be created by same name by which .aidl file is created.
• This .java file will be created inside Project_name/gen/Packatge_name where our R file is found.
• After this we will create a service class that is we will implement a remote service for this we'll return the IBinder from onBind() method in our service class. And here we will implement our method which is made in interface i.e we will define this method here.
• After this we will expose our service remotely in our MainActivity and will made out connection here by implementing ServiceConnection and other callback methods.
Example -----Projectaidl
6/03/2013
Topics:
Api,packages,threads,kernel,android Achitecture,Linux,Package,Library
Process and Threads
Process is a series of actions or steps taken to achieve an end.
Processes have their own memory where as Thread share memory.
Processes are slow in comparison to Threads as Process require separate memory hence creating load for CPU.
Process
Each process provides the resources needed to execute a program. A process has a virtual address space, executable code, open handles to system objects, a security context, a unique process identifier, environment variables, a priority class, minimum and maximum working set sizes, and at least one thread of execution. Each process is started with a single thread, often called the primary thread, but can create additional threads from any of its threads.
An executing instance of a program is called a process.
Thread
A thread is the entity within a process that can be scheduled for execution. All threads of a process share its virtual address space and system resources. In addition, each thread maintains exception handlers, a scheduling priority, thread local storage, a unique thread identifier, and a set of structures the system will use to save the thread context until it is scheduled. The thread context includes the thread's set of machine registers, the kernel stack, a thread environment block, and a user stack in the address space of the thread's process.
It is termed as a ‘lightweight process’, since it is similar to a real process but executes within the context of a process and shares the same resources allotted to the process by the kernel
A process may also be made up of multiple threads of execution that execute instructions concurrently.
The major difference between threads and processes is:
Threads share the address space of the process that created it; processes have their own address space.
Threads have direct access to the data segment of its process; processes have their own copy of the data segment of the parent process.
Threads can directly communicate with other threads of its process; processes must use inter process communication to communicate with sibling processes.
Threads have almost no overhead; processes have considerable overhead.
New threads are easily created; new processes require duplication of the parent process.
Threads can exercise considerable control over threads of the same process; processes can only exercise control over child processes.
Changes to the main thread (cancellation, priority change, etc.) may affect the behavior of the other threads of the process; changes to the parent process does not affect child processes.
A process has a self-contained execution environment. A process generally has a complete, private set of basic run-time resources; in particular, each process has its own memory space.
Definition for a uneducated person
Sequence of interdependent and linked procedures which, at every stage, consume one or more resources (employee time, energy, machines, money) to convert inputs (data, material, parts, etc.) into outputs. These outputs then serve as inputs for the next stage until a known goal or end result is reached.
Task
Jobs
Events
Task --It may be a single process or collection of multiple process in a computable node.
Job--It is collection of Tasks.
Process lifecycle hierarchy
Foreground process-----Most Important !
Visible process !
Service process !
Background process !
Empty process----Least Important V
UI Thread is referred as ==main thread
Example of Thread
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
Bitmap b = loadImageFromNetwork("http://example.com/image.png");
mImageView.setImageBitmap(b);
}
}).start();
}
MultiThreading
Threads, of course, allow for multi-threading. A common example of the advantage of multithreading is the fact that you can have a word processor that prints a document using a background thread, but at the same time another thread is running that accepts user input, so that you can type up a new document.
OpenGls In Android
OpenGL + OpenGL ES(Open GL for Embedded Systems)
Basically it is a library for developing high quality performance 2D and 3D applications in android.
Android includes support for high performance 2D and 3D graphics with the Open Graphics Library (OpenGL), specifically, the OpenGL ES API. OpenGL is a cross-platform graphics API that specifies a standard software interface for 3D graphics processing hardware. OpenGL ES is a flavor of the OpenGL specification intended for embedded devices.
The OpenGL ES 1.0 and 1.1 API specifications have been supported since Android 1.0. Beginning with Android 2.2 (API Level 8), the framework supports the OpenGL ES 2.0 API specification.
Android Support OpenGL through Android Framework API and Native Developement Kit(NDK).
Two main Classes in android which help us in implementation of openGLs in Android are:
GLSurfaceView—view class that helps in designing graphics and drawings in android.
GLSurfaceView.Render—Interface that defines methods required for drawing graphixcs in android.
Methods required for GLSurface Interface:
onSurfaceCreated,onDrawfrane(),onSurfaceChanged()
Requirements for using openGL in our Application are:
Declaration in manifest file for using OpenGl:
<uses-feature android:glEsVersion="0x00020000" android:required="true" />
R file in android
There are two types of R file in android as:
R.java
R.class
R.java is an auto generated file when you build an android application.
It contains unique identifiers (normally 32bit numbers) for elements in each category (drawable, string, layout, color, etc.) of resources (elements under directory res) available in your android application.
The main purpose of R.java file is quick accessibility of resources in the project. If any resource has deleted or added to the project, R.java file will be updated automatically, this can be done by ADT plugin in Eclipse.
When your application is compiled, aapt
generates the R
class, which contains resource IDs for all the resources in your res/
directory.
You will find R.java inside-->General--Package-->R.java
You will find R.class inside --->android---android.jar--android--R.class
Android aapt
Stands for android assset packaging tool.This tool is a part aandroid sdk and help us to create ,view and update zip compatibale archives(zip,rar,apk).it also compiles resources into binary assets.
NFC
Near Field Communication(NFC) is a set of short-range wireless technologies, typically requiring a distance of 4cm or less to initiate a connection. NFC allows you to share small payloads of data between an NFC tag and an Android-powered device, or between two Android-powered devices.
NDFC
NDEF (NFC Data Exchange Format) is a light-weight binary format, used to encapsulate typed data. It is specified by the NFC Forum, for transmission and storage with NFC, however it is transport agnostic.
NDEF defines messages and records. An NDEF Record contains typed data, such as MIME-type media, a URI, or a custom application payload. An NDEF Message is a container for one or more NDEF Records.
When an Android device receives an NDEF Message (for example by reading an NFC tag) it processes it through a dispatch mechanism to determine an activity to launch. The type of the first record in the message has special importance for message dispatch, so design this record carefully.
BroadCastReciever
It is an Android Component that responds to system wide broadcast announcements.
Many broadcast originate from system such as Broadcast announcing battery is low, screen turned off or picture captured or data downloaded.
Broadcast receivers generally dont create a user interface but creates a status bar notification to alert user when broadcast event occurs.
A broadcast receiver is implemented as a subclass of BroadcastReceiver and each broadcast is delivered as an Intent object.
Basically system will send some info which our app will receive and displays using the concept/use of BroadcastReceiver class in android.This Information would be helpful for various purposes example plugin before battery goes down.
It will provide a notification that will displays message regarding system information.
It is technique by which Android informs you about system events, offers the possibility for some nice apps as well as for user-friendly additions to existing apps.
Example saved as BroadcastInAndroid in AbhishekWorkspace
ANR
ANR (Application Not Responding) is not exactly an error.It is shown when your application is very sluggish and takes a lot of time to respond making the user wait.
The user won't appreciate if your application makes him wait for a long time so the android framework gives the user an option of closing your applicaiton.
Android will display the ANR dialog for a particular application when it detects one of the following conditions:
“Its action performed by android when our application due to certain reasons is not responding.”
Basically android will provide a option to close the application to the user.
How to avoid ANR status?
Android allows the system to protect the applications that are not responsive for a period of time by displaying a status called as ANR (Application not responding). Methods should use the main thread for work, as it takes long time for the main thread to complete the task. The work should be divided and another thread named as child thread be used for executing more tasks, as it takes less time. Main thread should provide a handler for child threads to post back upon completion.
We should make child threads to divide the tasks of main thread and avoid ANR
Attributes of ANR Dialog
wait
close Application
What dialog boxes are supported in android?Android supports 4 dialog boxes:
AlertDialog: An alert dialog box supports 0 to 3 buttons and a list of selectable elements, including check boxes and radio buttons. Among the other dialog boxes, the most suggested dialog box is the alert dialog box.
ProgressDialog: This dialog box displays a progress wheel or a progress bar. It is an extension of AlertDialog and supports adding buttons.
-
-
How the nine-patch Image different from a regular bitmap? Alternatively, what is the difference between nine-patch Image vs regular Bitmap Image?
It is one of a resizable bitmap resource which is being used as backgrounds or other images on the device. The NinePatch class allows drawing a bitm ap in nine sections. The four corners are unscaled; the middle of the image is scaled in both axes, the four edges are scaled into one axis.
What are the different Storage Methods in android?
Android provides many options for storage of persistent data. It provides the solution according to your need. The storages which have been provided in Android are as follows:-
Shared Preferences: Store private primitive data in key-value pairsInternal Storage: Store private data on the device memory.External Storage: Store public data on the shared external storage.SQLite Databases: Store structured data in a private database.Network Connection: Store data on the web with your own network server.
Context Provider---For sharing data between other applications.
Shared Prefence in Android
Shared preference class help us to save and retrieve persistent key value pair of primitive data types such as booleans,floats,ints,long,and strings.This data will persist across user sessions (even if your application is killed).
Methods to access object of shared preference are:
Example saved as sharedPrefenceAndroid in AbhishekWorkspace
EXCEPTION
An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.
An exception is a problem that arises during the execution of a program. An exception can occur for many different reasons, including the following:
A user has entered invalid data.
A file that needs to be opened cannot be found.
A network connection has been lost in the middle of communications, or the JVM has run out of memory.
Types of Exception :
Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation.(Cannot be ignored).
Occurs at compile time.
Unchecked or Runtime exceptions: A runtime exception is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compliation.
Errors: These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.
Handling Exceptions
i)Using try and catch block\
ii)Using throw and throws
The throws/throw Keywords:
If a method does not handle a checked exception, the method must declare it using the throwskeyword. The throws keyword appears at the end of a method's signature.
You can throw an exception, either a newly instantiated one or an exception that you just caught, by using the throw keyword. Try to understand the different in throws and throw keywords.
The following method declares that it throws a RemoteException:
import java.io.*;
public class className
{
public void deposit(double amount) throws RemoteException
{
// Method implementation
throw new RemoteException();
}
//Remainder of class definition
}
A method can declare that it throws more than one exception, in which case the exceptions are declared in a list separated by commas. For example, the following method declares that it throws a RemoteException and an InsufficientFundsException:
import java.io.*;
public class className
{
public void withdraw(double amount) throws RemoteException,
InsufficientFundsException
{
// Method implementation
}
//Remainder of class definition
}
The finally Keyword
The finally keyword is used to create a block of code that follows a try block. A finally block of code always executes, whether or not an exception has occurred.
Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code.
A finally block appears at the end of the catch blocks and has the following syntax:
try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}finally
{
//The finally block always executes.
}
Android Supports Following Exceptions as:
1. InflateException : This exception is thrown When an error conditions are occurred.
2. Surface.OutOfResourceException: This exception is thrown When a surface is not created or resized.
3. SurfaceHolder.BadSurfaceTypeException: This exception is thrown from the lockCanvas() method, when invoked on a Surface whose is SURFACE_TYPE_PUSH_BUFFERS
4. WindowManager.BadTokenException: This exception is thrown at the time of trying to add view an invalid WindowManager.LayoutParamstoken.
Plus
Android supports all java exceptions as:
Context
It is handle to the system.
It's like a handle to the environment your application is currently running in.
or
Its a reference to the current part or object of our application and It provides access to local files, databases, class loaders associated to the environment and services including system level services etc.
or
The Context class is an “Interface to global information about an application environment.”
Example ---getApplicationcontext();
Context object extends android.content.context
Bundle ~ a Bundle is a collection of data. When an Activity starts (via onCreate), the Android OS (or you!) can pass off some extra data to this activity via this bundle. Do you know what a HashMap is? A bundle is a glorified hashmap in that supports multiple different types.
OnCreate Bundle ~ This bundle comes from Android. Honestly, don't worry about it too much. If you want to start one activity from another, you use an intent (do you know this yet?). As such, you can "bundle" data into the intent (using the setExtra
methods). This data from the intent will be included in this onCreate bundle, and you can access it through there.
Context ~ your running application and anything associated with it. When you run your application, everything associated with your application is referenced by this context. All of you activities, views, resources, EVERYTHING is associated with the context. Think of it as the word defines: It is the context of your application. Every application has a unique context.
View ~ A view is anything that can be drawn on screen.
Containers in Java
A class that is used to contain other java objects. They contain methods for adding and removing objects, as well as ways to iterate through them. They tend to differ mostly by how the objects are referenced (by key or no), by how fast their various methods execute, and by how much memory the container uses.
Examples include:
java.util.Vector
java.util.Hashtable
java.util.HashSet
Difference between View and ViewGroup in Android
View—Button(A single view also called widget)
ViewGroup—RadioButton which contains Various buttons inside it
Different Types of Layouts in Android
LinearLayout—one after another
Relative Layout---one in respect to other
Tab Layout—in form Tables similar to HTML table
FrameLayout—concept of frames auto adjustment according to screen size
Absolute layout—In which we can specify relative x and y positions in pixels(Basically not recommended,since it is difficult to maintain)
HTC Device on which i have worked on
HTC Explorer 310e
version --- 2.3.5
Fragments
Android runs on variety of devices, from phones with small screen sizes, to tablets and large-screen TV sets. Fragments in a nutshell represent a smaller part of a user interface that could take a whole screen, or be part of a larger UI. By creating and using fragments, your app can adapt to a variety of devices and screen sizes
- A fragment is a class implementing a portion of an activity.
A fragment represents a particular operation or interface running within a larger activity.
Fragments enable more modular activity design, making it easier to adapt an application to different screen orientations and multiple screen sizes.
Fragments must be embedded in activities; they cannot run independent of activities.
- Most fragments define their own layout of views that live within the activity’s view hierarchy. A fragment has its own lifecycle, closely related to the lifecycle of its host activity.
- A fragment can be a static part of an activity, instantiated automatically during the activity’s creation.
Or, you can create, add, and remove fragments dynamically in an activity at run-time.
Fragments were added to the Android API in Honeycomb, API 11.
The primary classes related to fragments are:
- android.app.Fragment
- The base class for all fragment definitions
- android.app.FragmentManager
- The class for interacting with fragment objects inside an activity
- android.app.FragmentTransaction
- The class for performing an atomic set of fragment operations
Example saved in my AbhishekWorkspace as SimpleFragment and SimpleLayout.
Note: For creating a simple fragment your class should extend base class Fragment or any subclass of it and it should call method public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState){}.
This method will return a view that will display your fragment layout.
And one thing more for running Fragments we need atleast Honeycom (3.0) version of android or we have to increase Api level of below versions.
Another example of Fragments is AndroidFragment in AbhishekWorkspace
Fragments Primary uses in Android.
For more modular and flexible UI that can adapt to different devices such as tablets and phones
Reusability of view with functionality for a repetied view.
Can be invisible worker pieces of code
The main disadvantage is (some) added complexity. You can generally achieve the same thing with (custom) views in a non-standard and less robust way.
Fragment Activity Cycle
Fragment is added----Fragment State
onAttach()
onCreate()
onCreateView()
onActivityCreated()
onStart()
onResume()
fragment is now Active--- Fragment Mid State
onPause()
onStop()
onDestroyView()
onDestroy()
onDetach()
Fragment is Destroyred---Fragment last State
Dynamic Adding Fragments in Android
We can add fragments dynamically in android using FragmentManager class & FragmentTransaction Class from a already created fragment as:
Here shown on a button click
public
void
onClick(View v) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
HelloFragment hello =
new
HelloFragment();
fragmentTransaction.add(R.id.fragment_container, hello,
"HELLO"
);
fragmentTransaction.commit();
}
};
Example saved in AbhishekWorkspace as DynamicFragment
INTENT
An Intent is exactly what it describes. It's an "intention" to do an action.
Intent are the asychronous messages. It is a facility for late run-time binding between components in the same or different applications.
It has differerent action for different components.
It defines an operation to be performed.
Basically an Intent object is a bundle of Information .It contains information of interest to the component which recieves it plus information of interest for android system.Principaly it consist of following:
-
- Component name—Optional part. packagename+class name
Action
Data
Category
Extras
Flags
Intents or Intent messaging is the Android’s way to pass messages/information to various components of Android. An Intent object contains information that the target component can act upon. Through Intents, your apps can trigger Activities, Services and Broadcast Receivers. The most common use of intents in any application is to directly launch an Activity or Service to perform action on the data being passed with the Intent object.
A sample use of Intent is shown in the following example.
1. To launch an Activity
Intent intent = new Intent(context, TagetActivity.class);
startActivity(intent);
2. To launch a Service
Intent intent = new Intent(context, TargetService.class);
startService(intent);
3. To pass some data within your intents you need pass them within the Intent object like this.
intent.put(key, value);
Attributes of Intent
Component Name
The name of the component that should handle the intent.
It optional.
If it is set, the Intent object is delivered to an instance of the designated class. If it is not set, Android uses other information in the Intent object to locate a suitable target.
ACTION
It is a string name that define an action to be performed.
Or in the case of broadcast intents, the action that took place and is being reported.
Example: ACTION_CALL,ACTION_EDIT, ACTION_BATTERY_LOW, ACTION_SCREEN_ON etc
DATA
This field defines the data field that is to be acted upon.
For ACTION_CAll uri will be tel
For ACTION_EDIT uri will be uri
For ACTION_VIEW uri will be http
- CATEGORY
- A string containing additional information about the kind of component that should handle the intent.Ex.
CATEGORY_BROWSABLE
CATEGORY_GADGET
CATEGORY_LAUNCHER
EXTRA
Key-value pairs for additional information that should be delivered to the component handling the intent.
For example, an ACTION_TIMEZONE_CHANGED
intent has a "time-zone
" extra that identifies the new time zone, and ACTION_HEADSET_PLUG
has a "state
" extra indicating whether the headset is now plugged in or unplugged.
FLAGS
Flags are used for various purposes example for defining the prefence or position of activity after it had been launched.
TYPES OF INTENTS IN ANDROID
Explicit Intent
Target component name is explicitly define in Explicit Intent .
explicit intents are typically used for application-internal messages
Since in case of Explicit Intent we give name of Component expilicty so android system does not have to search for the component to handle Intent.
Implicit Intent
Does not name a target components
Implicit intents are typically used to activate components in other applications
In case of Implicit Intent since no Component have been mentioned so Android system have to search for relevant and suitable component by matching the contents of Intent object with Intent filter(structure that are associated with components that can recieve the intents).Filters advertise the capabilities of a component and delimit the intents it can handle
Example of Implicit Intent
Button viewContacts = (Button)findViewById(R.id.ViewContacts);
viewContacts.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent contacts = new Intent();
contacts.setAction(android.content.Intent.ACTION_VIEW);---providing information about action
contacts.setData(People.CONTENT_URI);----------providing information about data
startActivity(contacts);
}
});
NOTE:
If a component does not have any intent filters, it can receive only explicit intents. A component with filters can receive both explicit and implicit intents.
Only three aspects of an Intent object are consulted when the object is tested against an intent filter:
action
data (both URI and data type)
category
The extras and flags play no part in resolving which component receives an intent.
Intent Filters
Intent filters describe the capability of component that which type of intents they can a handle.They inform the system about the implicit intent they can handle.Thet advertise the properties of components to handle intents.
A intent filter has following fields which were match against Intent object.
Action---
<intent-filter . . . >
<action android:name="com.example.project.SHOW_CURRENT" />
<action android:name="com.example.project.SHOW_RECENT" />
<action android:name="com.example.project.SHOW_PENDING" />
. . .
</intent-filter>
To pass this test, the action specified in the Intent object must match one of the actions listed in the filter.
Data
<intent-filter . . . >
<data android:mimeType="video/mpeg" android:scheme="http" . . . />
<data android:mimeType="audio/mpeg" android:scheme="http" . . . />
. . .
</intent-filter>
Category
An <intent-filter>
element also lists categories as subelements. For example:
<intent-filter . . . >
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
. . .
</intent-filter>
STICKY INTENT
A normal broadcast Intent is not available anymore after it was send and processed by the system. If you use the sendStickyBroadcast(Intent) method, the Intent is sticky, meaning the Intent you are sending stays around after the broadcast is complete and is available to other components.
Intent
intent =
new
Intent
(
"some.custom.action"
);
intent.putExtra(
"some_boolean"
,
true
);
sendStickyBroadcast(intent);
Example :--ACTION_BATTERY_CHANGED
VECTOR CLASS
Vector is defined in java.util.Vector class and it implements a dynamic array. It's working is similar to ArrayList but it is little a bit different from it
Vector class is in java.util package of java. Vector is dynamic array which can grow automatically according to the required need. Vector does not require any fix dimension like String array and int array. Vector contains many useful methods. To add element in Vector, we can use add() method of vector class. To add elements at fix position, we have to use add(index, object) method.
To get value from Vector, Vector provides get() method and Vector size() method. Size() method returns total number of elements in Vector.
Arraylist are also similar to vectors but are unsycronised and fast where as vectors are synchonised and can be of great help in multi threading.
Vectors can hold only Objects and not primitive types. If u want to store primitive data type in vector than put it inside an object.
The Vector
class is an example of what is called a container
. Other container
classes are Stack
(for implementing last-in, first-out sequence) and Hashtable
(for an associative array).
Create vector
Vector v = new Vector();
Add element
v.add(s);
Characteristics of Vector
Implements Dynamic Array
Automatically increses size according to requirements
Synchronised
can hold objects only
Implements various Methods to be inplemented.
Difference between Vector and ArrayList
Vectors are synchronised where as ArrayList are not Syncronised.
ArrayList
- ArrayList is an implementation of List, backed by an array. All optional operations including adding, removing, and replacing elements are supported.
All elements are permitted, including null.
- ArrayList are similar to vectors but are not Synchronised.
- They can Increaseor decrease their size according to the Requirement.
- ArrayList is like a dynamic array or a variable-length array.
Example--- ArrayList al = new ArrayList(); //creating a ArrayList
al.add("a"); //to add an element
if ArrayList reaches max capacity then a new ArrayList object will be with
new capacity=(current capacity*3/2)+1
Difference between Array and ArrayList
- ArrayListy is Dynamic where as Array are of fixed length/size.
- Array is Homogeneous where as Array List are Hetrogeneous.
- ArrayList contains Objects where as array cannot.
Adapter
An Adapter object acts as a bridge between an AdapterView
(ListView,GridView etc)
and the underlying data for that view. The Adapter provides access to the data items. The Adapter is also responsible for making a View
for each item in the data set.
An adapter is used to bind data to a view.
Example of Liast Adapter in AbhishekWorkspace saved as SimpleAdapterEx
Syntax for ArrayAdapter in Android
ArrayList
<
MyClass
> myList =
new
ArrayList
<
MyClass
>();
ListView
listView = (
ListView
) findViewById(R.id.list);
ArrayAdapter
<
MyClass
> adapter =
new
ArrayAdapter
<
MyClass
>(
this
, R.layout.row,
to, myList.);
listView.setAdapter(adapter);
Main types of Adapter
ArrayAdapter
used in case of when we are getting data from any array source
CursorAdapter
used in case when we are retrieving data from Database(Sqlite etc)
SimpleCursorAdapter
LIstAdapter
used we want to fill list through an Adapter
BaseAdaper
SpinnerAdapter
BaseAdapter
is an abstract base class for the Adaptor interface to simplify implementing adapters. You could implement your own, but the framework provides some pretty flexible adapters already. Some popular adapters are:
binds an array of data to a view
override getView()
to inflate, populate, and return a custom view for the given index in the array. The getView()
method includes an opportunity reuse views via the convertView
parameter.
binds data from a cursor (like a database cursor) to a view
abstract so you don't use it directly, use a subclass or derive your own
implement the abstract method newView()
to inflate, populate, and return the desired view for the current cursor position and implement the abstract method bindView
to populate an existing view that is being reused..
a concrete implementation of CursorAdapter
it can take a row layout and a mapping of cursor columns to row layout widgets
supports text and images, but can customize using setViewText
and setViewImage
can support other types and can customize bindings through a hook: clients implement theSimpleCursorAdapter.ViewBinder
interface with a setViewValue()
method to inflate, populate, and return the desired view for a given row (current cursor state) and data "column". This method can define just the "special" views and bindings, but still defer to SimpleCursorAdapter's standard behavior for the "normal" bindings.