You are on page 1of 77

WEEK-1: DAY-1: INTRODUCTION TO ANDROID

Android is a Linux-based Operating System that gives us a world-class platform for creating apps and games for android users. Android is an Open-Handset Alliance Google along with other 34 companies led android to help improve open standards for mobile phones. The companies included mobile phone manufacturers, application developers, mobile network operators and processor makers. This business alliance was called as Open-Handset Alliance. Android was initially founded by Andy Rubin, Rich Miner and Chris White in October 2003. Android uses Java API(Application Programmable Interface) Java API specifies how some software components should interact with each other. An API can be used to ease the work of programming the GUI components. Most often an API is a library that is a collection of classes, enumeration and interfaces. Moreover, Android uses the Dalvik virtual machine with just-in-time compilation to run Dalvik byte code, which is usually translated from Java byte code. Source Code Byte Code Dalvik Code

Versions of Android - Android versions have been developed under a codename and released according to alphabetical order: Cupcake(1.5) Donut(1.6) Eclair(2.0-2.1) Froyo(2.2-2.2.3) Gingerbread(2.3-2.3.7)

Honeycomb(3.0-3.2.6) Ice cream Sandwich(4.0-4.0.4) Jelly Bean(4.1-4.3) Kitkat(4.4+)

Android is an open-source operating system, i.e., any user can get the source code and use it to make any new application. User can also edit the existing applications by making use of this source code. It is widely used Operating System for touch screen phones, tablets, washing machines, watches, etc.

DAY-2:
Tools for Android: Phone

INSTALLATION STEPS

Eclipse(http://www.eclipse.org/downloads/) Android Plug-in (ADT) Android SDK(http://developer.android.com/sdk/index.html)

Installation of Android SDK: Once installed open the SDK Manager. Install the desired packages or APIs. Create an Android Virtual Device (AVD).

SDK Manager:

AVD:

DAY-3:
ADT Plug-in 1: In Eclipse, go to Help -> Install New Software Click Add in top right Enter: Name: ADT Plug-in Location: https://dl-ssl.google.com/android/eclipse/ Click OK, then select Developer Tools, click Next Click Next and then Finish Afterwards, restart Eclipse Specify SDK location (next 3 slides)

ADT Plug-in 2:

ADT Plug-in 3:

ADT Plug-in 4:

DAY-4:
Interfaces:

JAVA REVIEW

An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface. An interface is not a class. Writing an interface is similar to writing a class, but they are two different concepts. A class describes the attributes and behaviors of an object. An interface contains behaviors that a class implements. Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class. An interface is similar to a class in the following ways: An interface can contain any number of methods. An interface is written in a file with a .java extension, with the name of the interface matching the name of the file. The byte code of an interface appears in a .class file Interfaces appear in packages, and their corresponding byte code file must be in a directory structure that matches the package name. However, an interface is different from a class in several ways, including: You cannot instantiate an interface. An interface does not contain any constructors. All of the methods in an interface are abstract. An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final. An interface is not extended by a class; it is implemented by a class. An interface can extend multiple interfaces. Declaring Interfaces - The interface keyword is used to declare an interface. Here is a simple example to declare an interface: Example: /* File Name : NameOf Interface.java */ import java. lang.*;

//Any number of import statements public interface NameOfInterface { // Any number of final, static fields // Any number of abstract method declarations } Interfaces have the following properties: An interface is implicitly abstract. You do not need to use the abstract keyword when declaring an interface. Each method in an interface is also implicitly abstract, so the abstract keyword is not needed. Methods in an interface are implicitly public.

DAY-5: Abstraction: Abstraction is a process of hiding the implementation details and showing only functionality to the user. Another way, it shows only important things to the user and hides the internal details for example sending an sms, you just type the text and send the message. You dont know the internal processing about the message delivery. Abstraction lets us focus on what the object does instead of how it does it.

Abstract Class: A class that is declared as abstract is known as abstract class. Its needs to be extended and its method to be implemented. Syntax: abstract class<class_name>{}

Abstract Method: A method that is declared as abstract and does not have implementation is known as abstract method. Syntax: abstract return_type <method_name>(); Example: abstract class Bike { abstract void run(); } class Honda extends Bike {

//no braces{}

void run(){System.out.println(running safely);} } public static void main(String args[]){ Bike obj=new Honda(); obj.run(); } Output: running safely In this example, Bike is the abstract class that contains only one abstract method run. Its implementation is provided by the Honda class.

DAY-6:
Abstract Classes versus Interfaces: Unlike interfaces, abstract classes can contain fields that are not static and final, and they can contain implemented methods. Such abstract classes are similar to interfaces, except that they provide a partial implementation, leaving it to subclasses to complete the implementation. If an abstract class contains only abstract method declarations, it should be declared as an interface instead. Multiple interfaces can be implemented by classes anywhere in the class hierarchy, whether or not they are related to one another in any way. By comparison, abstract classes are most commonly subclassed to share pieces of implementation. A single abstract class is subclassed by similar classes that have a lot in common (the implemented parts of the abstract class), but also have some differences (the abstract methods).

Thread: A thread is a single sequential flow of control within a program. In programming, sometimes you need to do some tasks together (simultaneously) , for example copying a file and showing the progress, or playing a music while showing some pictures as a slideshow, or a listener handles cancel event for aborting a file copy operation. If a program needs to run (do) more than one task (thread) at a time, that kind of a program is called a concurrent (multi-thread) program. There is a class in java named Thread. It has several methods, amongst of them one is public void run. To make our class as thread type we have to override run method in our class. There are two ways by which we can get a thread object: by extending thread class by implementing runnable interface

DAY-7:

WEEK-2: CREATING A NEW PROJECT

Need the items circled. The click finish.

DAY-8:

PROJECT COMPONENTS

Once you complete the New Project Wizard, ADT creates the following folders and files in your new project: src/- Includes your stub Activity Java file. All other Java files for your application go here. <Android Version>/ - (e.g., Android 1.5/) Includes the android.jar file that your application will build against. gen/ - This contains the Java files generated by ADT, such as your R.java file and interfaces created from AIDL files. assets/ - This is empty. You can use it to store raw asset files. res/ - A folder for your application resources, such as drawable files, layout files, string values, etc. AndroidManifest.xml - The Android Manifest for your project. default.properties - This file contains project settings, such as the build target. XML: Extensible Markup Language (XML) is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. It is defined in the XML 1.0 Specification produced by the W3C, and several other related specifications, all gratis open standards. The design goals of XML emphasize simplicity, generality, and usability over the Internet. It is a textual data format with strong support via Unicode for the languages of the world. Although the design of XML focuses on documents, it is widely used for the representation of arbitrary data structures, for example in web services. XML is an application profile of SGML (ISO 8879). Versions: There are two current versions of XML. The first (XML 1.0) was initially defined in 1998. It has undergone minor revisions since then, without being given a new version number, and is currently in its fifth edition, as published on November 26, 2008. It is widely implemented and still recommended for general use.

The second (XML 1.1) was initially published on February 4, 2004, the same day as XML 1.0 Third Edition, and is currently in its second edition, as published on August 16, 2006. It contains features (some contentious) that are intended to make XML easier to use in certain cases. The main changes are to enable the use of lineending characters used on EBCDIC platforms, and the use of scripts and characters absent from Unicode 3.2. XML 1.1 is not very widely implemented and is recommended for use only by those who need its unique features.

DAY-9:

ANDROID PROGRAMMING COMPONENTS

Activity Service Content Provider Broadcast Receiver

Activity: An Activity is an application component that provides a screen with which users can interact in order to do something, such as dial the phone, take a photo, send an email, or view a map. Each activity is given a window in which to draw its user interface. The window typically fills the screen, but may be smaller than the screen and float on top of other windows. It represents the presentation layer of an Android application, e.g. a screen which the user sees. An Android application can have several activities and it can be switched between them during runtime of the application. Activity States: The Android OS uses a priority queue to assist in managing activities running on the device. Based on the state a particular Android activity is in, it will be assigned a certain priority within the OS. This priority system helps Android identify activities that are no longer in use, allowing the OS to reclaim memory and resources. The following diagram illustrates the states an activity can go through, during its lifetime: These states can be broken into 3 main groups as follows: Active or Running - Activities are considered active or running if they are in the foreground, also known as the top of the activity stack. This is considered the highest priority activity in the Android Activity stack, and as such will only be killed by the OS in extreme situations, such as if the activity tries to use more memory than is available on the device as this could cause the UI to become unresponsive.

Paused - When the device goes to sleep, or an activity is still visible but partially hidden by a new, non-full-sized or transparent activity, the activity is considered paused. Paused activities are still alive, that is, they maintain all state and member information, and remain attached to the window manager. This is considered to be the second highest priority activity in the Android Activity stack and, as such, will only be killed by the OS if killing this activity will satisfy the resource requirements needed to keep the Active/Running Activity stable and responsive. Stopped - Activities that are completely obscured by another activity are considered stopped or in the background. Stopped activities still try to retain their state and member information for as long as possible, but stopped activities are considered to be the lowest priority of the three states and, as such, the OS will kill activities in this state first to satisfy the resource requirements of higher priority activities.

DAY-10:

ACTIVITY LIFE CYCLE

OnCreate(): Called when the activity is first created. This is where you should do all of your normal static set up: create views, bind data to lists, etc. This method also provides you with a Bundle containing the activity's previously frozen state, if there was one. Always followed by onStart(). onRestart() : Called after your activity has been stopped, prior to it being started again. Always followed by onStart() onStart() : Called when the activity is becoming visible to the user. Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden. onResume() : Called when the activity will start interacting with the user. At this point your activity is at the top of the activity stack, with user input going to it. Always followed by onPause(). onPause (): Called as part of the activity lifecycle when an activity is going into the background, but has not (yet) been killed. The counterpart to onResume(). When activity B is launched in front of activity A, this callback will be invoked on A. B will not be created until A's onPause() returns, so be sure to not do anything lengthy here. onStop(): Called when you are no longer visible to the user. You will next receive either onRestart(), onDestroy(), or nothing, depending on later user activity. Note that this method may never be called, in low memory situations where the system does not have enough memory to keep your activity's process running after its onPause() method is called. onDestroy() : The final call you receive before your activity is destroyed. This can happen either because the activity is finishing (someone called finish() on it, or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing() method.

DAY-11:

BASIC LIFE CYCLE

There are three key loops you may be interested in monitoring within your activity: The entire lifetime of an activity happens between the first call to onCreate(Bundle) through to a single final call to onDestroy(). An activity will do all setup of "global" state in onCreate(), and release all remaining resources in onDestroy(). For example, if it has a thread running in the background to download data from the network, it may create that thread in onCreate() and then stop the thread in onDestroy(). The visible lifetime of an activity happens between a call to onStart() until a corresponding call to onStop(). During this time the user can see the activity onscreen, though it may not be in the foreground and interacting with the user. Between these two methods you can maintain resources that are needed to show the activity to the user. For example, you can register a BroadcastReceiver in onStart() to monitor for changes that impact your UI, and unregister it in onStop() when the user no longer sees what you are displaying. The onStart() and onStop() methods can be called multiple times, as the activity becomes visible and hidden to the user.

The foreground lifetime of an activity happens between a call to onResume() until a corresponding call to onPause(). During this time the activity is in front of all other activities and interacting with the user. An activity can frequently go between the resumed and paused states -- for example when the device goes to sleep, when an activity result is delivered, when a new intent is delivered -- so the code in these methods should be fairly lightweight. The entire lifecycle of an activity is defined by the following Activity methods. All of these are hooks that we can override to do appropriate work when the activity changes state. All activities will implement onCreate(Bundle) to do their initial setup; many will also implement onPause() to commit changes to data and otherwise prepare to stop interacting with the user.

DAY-12: Service:

SERVICE

A Service is an application component that can perform long-running operations in the background and does not provide a user interface. Another application component can start a service and it will continue to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform interprocess communication (IPC). For example, a service might handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background. A service can essentially take two forms: Started - A service is "started" when an application component (such as an activity) starts it by calling startService(). Once started, a service can run in the background indefinitely, even if the component that started it is destroyed. Usually, a started service performs a single operation and does not return a result to the caller. For example, it might download or upload a file over the network. When the operation is done, the service should stop itself. Bound - A service is "bound" when an application component binds to it by calling bindService(). A bound service offers a client-server interface that allows components to interact with the service, send requests, get results, and even do so across processes with interprocess communication (IPC). A bound service runs only as long as another application component is bound to it. Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed.

Run in the background Can continue even if Activity that started it dies Should be used if something needs to be done while the user is not interacting with application Otherwise, a thread is probably more applicable Should create a new thread in the service to do work in, since the service runs in the main thread Can be bound to an application

In which case will terminate when all applications bound to it unbind Allows multiple applications to communicate with it via a common interface Needs to be declared in manifest file Like Activities, has a structured life cycle

DAY-13:

WEEK-3: SERVICE LIFE CYCLE

onStartCommand(): The system calls this method when another component, such as an activity, requests that the service be started, by calling startService(). Once this method executes, the service is started and can run in the background indefinitely. If you implement this, it is your responsibility to stop the service when its work is done, by calling stopSelf() or stopService(). (If you only want to provide binding, you don't need to implement this method.) onBind(): The system calls this method when another component wants to bind with the service (such as to perform RPC), by calling bindService(). In your implementation of this method, you must provide an interface that clients use to communicate with the service, by returning an IBinder. You must always implement this method, but if you don't want to allow binding, then you should return null. onCreate(): The system calls this method when the service is first created, to perform one-time setup procedures (before it calls either onStartCommand() or onBind()). If the service is already running, this method is not called. onDestroy(): The system calls this method when the service is no longer used and is being destroyed. Your service should implement this to clean up any resources such as threads, registered listeners, receivers, etc. This is the last call the service receives. The service lifecycle - The diagram above shows the lifecycle when the service is created with startService() and the diagram on the right shows the lifecycle when the service is created with bindService(). By implementing these methods, you can monitor two nested loops of the service's lifecycle: The entire lifetime of a service happens between the time onCreate() is called and the time onDestroy() returns. Like an activity, a service does its initial setup in onCreate() and releases all remaining resources in onDestroy(). For example, a music playback service could create the thread where the music will be played in onCreate(), then stop the thread in onDestroy(). The onCreate() and onDestroy() methods are called for all services, whether they're created by startService() or bindService(). The active lifetime of a service begins with a call to either onStartCommand() or onBind(). Each method is handed the Intent that was passed to either startService() or bindService(), respectively.

If the service is started, the active lifetime ends the same time that the entire lifetime ends (the service is still active even after onStartCommand() returns). If the service is bound, the active lifetime ends when onUnbind() returns.

DAY-14:

CONTENT PROVIDER

Content Provider: Content providers manage access to a structured set of data. They encapsulate the data, and provide mechanisms for defining data security. Content providers are the standard interface that connects data in one process with code running in another process. When you want to access data in a content provider, you use theContentResolver object in your application's Context to communicate with the provider as a client. The ContentResolverobject 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. This topic describes the basics of the following: How content providers work. The API you use retrieve data from a content provider. The API you use to insert, update, or delete data in a content provider. Other API features that facilitate working with providers. A content provider manages access to a central repository of data. You implement a provider as one or more classes in an Android application, along with elements in the manifest file. One of your classes implements a subclass ContentProvider, which is the interface between your provider and other applications. Although content providers are meant to make data available to other applications, you may of course have activities in your application that allow the user to query and modify the data managed by your provider.

DAY-15:

BROADCAST RECEIVER

Broadcast Receiver: public abstract class BroadcastReceiver extends Object java.lang.Object android.content.BroadcastReceiver Base class for code that will receive intents sent by sendBroadcast(). If you don't need to send broadcasts across applications, consider using this class with LocalBroadcastManager instead of the more general facilities described below. This will give you a much more efficient implementation (no cross-process communication needed) and allow you to avoid thinking about any security issues related to other applications being able to receive or send your broadcasts. You can either dynamically register an instance of this class with Context.registerReceiver() or statically publish an implementation through the <receiver> tag in your AndroidManifest.xml. There are two major classes of broadcasts that can be received: Normal broadcasts (sent with Context.sendBroadcast) are completely asynchronous. All receivers of the broadcast are run in an undefined order, often at the same time. This is more efficient, but means that receivers cannot use the result or abort APIs included here. Ordered broadcasts (sent with Context.sendOrderedBroadcast) are delivered to one receiver at a time. As each receiver executes in turn, it can propagate a result to the next receiver, or it can completely abort the broadcast so that it won't be passed to other receivers. The order receivers run in can be controlled with the android:priority attribute of the matching intent-filter; receivers with the same priority will be run in an arbitrary order.

There are following two important steps to make BroadcastReceiver works for the system broadcasted intents: Creating the Broadcast Receiver. Registering Broadcast Receiver There is one additional steps in case you are going to implement your custom intents then you will have to create and broadcast those intents. Creating the Broadcast Receiver: A broadcast receiver is implemented as a subclass of BroadcastReceiver class and overriding the onReceive() method where each message is received as a Intent object parameter. public class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context,"Intent Detected.",Toast.LENGTH_LONG).show(); } } Registering Broadcast Receiver: An application listens for specific broadcast intents by registering a broadcast receiver inAndroidManifest.xml file. Consider we are going to register MyReceiver for system generated event ACTION_BOOT_COMPLETED which is fired by the system once the Android system has completed the boot process. <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <receiver android:name="MyReceiver"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED"> </action> </intent-filter> </receiver> </application>

DAY-16:

DALVIK VIRTUAL MACHINE

DVM: One of the key elements of Android is the Dalvik virtual machine. Rather than use a traditional Java virtual machine (VM) such as Java ME (Java Mobile Edition), Android uses its own custom VM designed to ensure that multiple instances run efficiently on a single device. The Dalvik VM uses the devices underlying Linux kernel to handle low -level functionality including security, threading, and process and memory management. Its also possible to write C/C++ applications that run directly on the underlying Linux OS. While you can do this, in most cases theres no reason you should need to. All Android hardware and system service access is managed using Dalvik as a middle tier. By using a VM to host application execution, developers have an abstraction layer that ensures they never have to worry about a particular hardware implementation. The Dalvik VM executes Dalvik executable files, a format optimized to ensure minimal memory footprint. The .dex executables are created by transforming Java language compiled classes using the tools supplied within the SDK. Being optimized for low memory requirements, Dalvik has some specific characteristics that differentiate it from other standard VMs: The VM was slimmed down to use less space. The constant pool has been modified to use only 32-bit indices to simplify the interpreter. Standard Java bytecode executes 8-bit stack instructions. Local variables must be copied to or from the operand stack by separate instructions. Dalvik instead uses its own 16-bit instruction set that works directly on local variables. The local variable is commonly picked by a 4-bit 'virtual register' field. This lowers Dalvik's instruction count and raises its interpreter speed. Moreover, according to Google, the design of Dalvik permits a device to run multiple instances of the VM efficiently.

DAY-17:

ANDROID ARCHITECTURE

Android Architecture Diagram:

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 several 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 Androids 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 offscreen buffering. Off-screen buffering means you cannot 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 codes 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.

DAY-18: 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 doesnt run .class files, instead it runs .dex files. .dex files are built from .class file at the time of compilation and provides higher 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 going to fit. Several standard applications comes pre-installed with every device, such as: SMS client app Dialer Web browser

Contact manager As a developer we are able to write an app which replace any existing system app. That is, we are not limited in accessing any particular feature. We are practically limitless and can whatever you want to do with the android (as long as the users of our app permits it). Thus Android is opening endless opportunities to the developer.

DAY-19:

WEEK-4: DESIGNING AN APPLICATION

Design Your Apps User Interface Using Basic Widgets: User interface has become more and more important as mobile applications become more and more advanced. Android as a platform provides a great GUI toolkit for Android developers use to design intuitive interfaces. Many app developers try to make new, unprecedented, innovative interfaces, but more often than not, the best method for making an app easy to use is to stick with familiar frameworks. This usually means that its best to stick with standard interface elements from widely-used toolkits. Like all good GUI toolkits, Android also provides some basic widgets like buttons, labels, etc., which any Android developer can use to create the UI for his application. Here is an overview of the most common Android interface elements. Labels (TextView): One of the most basic widgets provided by Android is the TextView(label), which is used to display a small amount of text on screen. TextView in general is used to display contextual information to the user or to name other elements on the screen. TextView can be added to your apps interface using two different methods : Adding TextView through layout.xml Adding TextView through code. Adding Labels through Layout.xml: One of the ways to add a TextView is through the layout.xml file. In layout.xml, you can add a TextView by simply adding the <TextView> tag. The code to add a TextView is as follows: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/info" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello"

/> </LinearLayout> In the TextView node above, you can add different properties (e.g:- android:text) as properties of the XML Tag.

DAY-20:

ADDING A LABEL

Adding Labels through Code: Adding TextView through XML is an easy way to add a TextView to the interface, but sometimes it might be necessary to add the TextView programmatically. The following is the code to add a TextView using more standard programming techniques. public class TextViewDemo extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); View linearLayout = findViewById(R.id.info); TextView ProgramaticallyTV = new TextView(this); ProgramaticallyTV.setText("Text View Added Programatically"); ((LinearLayout) linearLayout).addView(ProgramaticallyTV); } } In this, we get the layout using the function findViewById and then create a new Instance of TextView. Then, we set the text of the TextView using the function setText, and finally, we add the TextView to the layout using the addView function.

Now, if we run the application by adding these two TextView it will appear as follows:

DAY-21:

ADDING A TEXT

EditText: EditText is a basic widget in the Android toolkit to let users enter text for different processing. The EditText can also be added via the XML and even through code. Adding EditText through Layout.xml: To add EditText through XML, you need to add the tag <EditText> into your layout.xml file. The code for it is as follows: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/info" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="UserName" /> <EditText android:id="@+id/username" android:layout_width="fill_parent" android:layout_height="wrap_content"/> </LinearLayout>

The EditText widgets has many properties, like android:text, which can be used to set it Text or android:password to make the EditText a password field. If we run the application now, the screen will be seen as follows:

Adding the EditText via Code: The EditText can be added via code if the user wants to add an EditText on the fly or based on some condition. The following is the code that adds an EditText for password and then converts it to a password EditText by using the method setTransformationMethod. public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); View linearLayout = TextView tvPassword = new TextView(this); tvPassword.setText("PassWord"); ((LinearLayout) linearLayout).addView(tvPassword);

EditText etPassword = new EditText(this); etPassword.setTransformationMethod(new PasswordTransformationMethod()); ((LinearLayout) linearLayout).addView(etPassword); }

Above, we create an instance of EditText, and then to make the EditText as password, we use the setTransformationMethod. If we run the application now, the screen will look as follows:

DAY-22:

ADDING A BUTTON

Buttons: Buttons are another very basic and very handy widget provided by the Android Toolkit. We can add buttons to our UI and then respond to the clicks on each button. A button can also be added through the XML layout or through code, just like a TextView. Adding A Button Through Layout.xml: To add a button through the layout.xml file, you need to specify the <button> tag within layout.xml. Like a TextView, we can specify other properties of the button as attributes to that XML tag, e.g. android:text. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/mainlayout" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <Button android:id="@+id/xmlbutton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Button Added via xml" android:onClick="xmlButtonClick" /> </LinearLayout>

The button also has a property called as android:onClick, which allows us to specify the click handler (the function to be called when button is clicked). To handle the button click via code, we will need to create a method as follows:

public void xmlButtonClick(View v) {

Toast.makeText(getApplicationContext(), "Button Added VIA XML Clicked", Toast.LENGTH_SHORT).show(); }

This method just displays a toast on screen as soon as the button is clicked.

DAY-23:

ADDING A BUTTON

Adding the Button Through Code: We can also add a button through code and attach the click handler to handle when the button is clicked. The following is the code to add the button and handle its click. public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); View linearLayout = Button buyButton = new Button(this); buyButton.setText("Button Added Programatically"); buyButton.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { Toast.makeText(getApplicationContext(), "Button Added Prgramatically Clicked", Toast.LENGTH_SHORT).show(); } }); ((LinearLayout) linearLayout).addView(buyButton); } In this example, we get the layout using the findViewById function, and then we create a new instance of the button. We add the text to the button using the setText method on the button, and then we set a clickhandler using the setOnClickListener to display a toast when the button is clicked.

When we run the program and click on the button, the Toast will appear as follows:

DAY-24:

ADDING AN IMAGE

Images: The ImageView widget provided by Android is used to display images on the android screen. To use it, we need to add the image in the res/drawable folder. Like the other widgets, the ImageView can be added through the layout.xml file or through code. Adding ImageView Through Layout.xml: To add ImageView through layout.xml we will need to add the <ImageView> tag in the layout.xml file. The code to add the ImageView is as follows: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/info" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <ImageView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/flower1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:adjustViewBounds="true" android:src="@drawable/flower1" /> </LinearLayout> In the layout.xml file, we can use the attribute android:src to specify the name of the image which is to be displayed. In this example, I have used flower1 which is kept at the location res/drawable/flower1.jpg.

If we run the program now, the screen will look like the following:

DAY-25:

WEEK-5: DESIGNING AN APPLICATION - IMAGE

Adding ImageView Through Code: Sometimes, it might be handy to add an ImageView through code. For example, we might want to display an image only if a certain programming condition is fulfilled. The following is the code to add an ImageView through code: public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); View linearLayout = findViewById(R.id.info); ImageView Flower2Image = new ImageView(this); Flower2Image.setImageResource(R.drawable.flower2); ((LinearLayout) linearLayout).addView(Flower2Image); }

In this example, we first find the layout using the function findViewById. Then, we create a new ImageView instance. Then, we set the image on the new ImageView instance using the function setImageResource, and finally, we pass the ID for the image to be displayed.

Lastly, we add the ImageView instance to the layout using the addView function. If we run the program now, the following will be the output:

DAY-26:

ADDING A CHECKBOX

Checkbox: User interfaces generally consists of different options that the user can either select or deselect. Checkboxes are really useful for creating such options. Androids UI toolkit also provides us with a Checkbox widget, which can help us create options for user to select or deselect. Like the other widgets, the Checkbox can be added through the layout.xml or through code. Adding CheckBox Through Layout.xml: To add CheckBox through layout.xml file, we will need to add the <CheckBox> tag within layout.xml. The code to add the CheckBox is as follows: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/info" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/develop" /> <CheckBox xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/windows" android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="true" android:text="Windows" /> <CheckBox xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/linux" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Linux" />

<CheckBox xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/mac" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Mac" /> </LinearLayout>

If we run the application now, it will be seen as below: The user will be able to select or deselect the different options on the screen.

DAY-27:

ADDING A CHECKBOX

Adding CheckBox Through Code: Sometimes, we might want to add checkboxes only under specific conditions.For such cases, Checkboxes can be added through code. The following is the code that will dynamically add one TextView and two more CheckBox to the previous screen. public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); View linearLayout =TextView tvAdditionalQuestions = new TextView(this); tvAdditionalQuestions.setText("Some Addtional Questions..."); ((LinearLayout) linearLayout).addView(tvAdditionalQuestions); CheckBox cbMobileDevelopment = new CheckBox(this); cbMobileDevelopment.setText("I love Mobile Development"); findViewById(R.id.info); ((LinearLayout) linearLayout).addView(cbMobileDevelopment); CheckBox cbLoveAndroid = new CheckBox(this); cbLoveAndroid.setText("I love Android"); ((LinearLayout) linearLayout).addView(cbLoveAndroid); }

Here, we create an instance of the checkbox and set the text for it using the setText method. If we run the application now, the screen will be as follows:

DAY-28:

ADDING A RADIOBUTTON

Radio Button: Radio buttons are similar to checkboxes in that they also enable users to select options. The one major difference is that from a group of radio buttons, only one can be selected at a time. To make a radio button part of one group we have to add it to a RadioGroup. Adding Radio Button Through Layout.xml: To add the tadio buttons through the XML file, we have to first create a <RadioGroup> tag and then add <RadioButton> tags within it. The following is the code to add three radio buttons via XML: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/info" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Which is your favourite platorm for Android development" /> <RadioGroup xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <RadioButton android:id="@+id/windows" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Windows" /> <RadioButton android:id="@+id/linux" android:layout_width="wrap_content" android:layout_height="wrap_content"

android:text="Linux" /> <RadioButton android:id="@+id/mac" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Mac" /> </RadioGroup> </LinearLayout>

Here, we add the radio button tags for the options we want to display to the user. If we run the program now, the screen will appear as follows:

DAY-29:

ADDING A RADIOBUTTON

Adding Radio Button Through Code: Like the other widgets, even the Radio button can be added through code. Just like we did in the XML file, first we will need to create a radio group. Then, we will create instances of the radio button and then finally, well add these instances to the radio group. Once this is done, we can add the radio group to the layout. The following is the code to add two radio buttons: public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); View linearLayout = TextView tvAdditionalQuestions = new TextView(this); tvAdditionalQuestions.setText("Would You Like to Switch your development Enviroment..."); ((LinearLayout) linearLayout).addView(tvAdditionalQuestions); RadioGroup rgAddtionalQuestion = new RadioGroup(this); rgAddtionalQuestion.setOrientation(RadioGroup.VERTICAL); RadioButton rbYes = new RadioButton(this); rbYes.setText("Yes"); rgAddtionalQuestion.addView(rbYes); RadioButton rbNo = new RadioButton(this); rbNo.setText("No"); rgAddtionalQuestion.addView(rbNo); ((LinearLayout) linearLayout).addView(rgAddtionalQuestion); }

If we run the application now, the screen will be as follows:

DAY-30:

EMULATOR IN ANDROID

Emulator: The Android SDK includes a virtual mobile device emulator that runs on our computer. The emulator lets us prototype, develop and test Android applications without using a physical device. The Android emulator mimics all of the hardware and software features of a typical mobile device, except that it cannot place actual phone calls. It provides a variety of navigation and control keys, which we can "press" using our mouse or keyboard to generate events for our application. It also provides a screen in which our application is displayed, together with any other active Android applications.

To let us model and test our application more easily, the emulator utilizes Android Virtual Device (AVD) configurations. AVDs let us define certain hardware aspects of our emulated phone and allow us to create many configurations to test many Android platforms and hardware permutations. Once our application is running on the emulator, it can use the services of the Android platform to invoke other applications, access the network, play audio and video, store and retrieve data, notify the user, and render graphical transitions and themes. The emulator also includes a variety of debug capabilities, such as a console from which we can log kernel output, simulate application interrupts (such as arriving SMS messages or phone calls), and simulate latency effects and dropouts on the data network.

Overview: The Android emulator is an application that provides a virtual mobile device on which we can run our Android applications. It runs a full Android system stack, down to the kernel level, that includes a set of preinstalled applications (such as the dialer) that we can access from our applications. We can choose what version of the Android system we want to run in the emulator by configuring AVD, and we can also customize the mobile device skin and key mappings. When launching the emulator and at runtime, we can use a variety of commands and options to control its behavior. The Android system images available through the Android SDK Manager contain code for the Android Linux kernel, the native libraries, the Dalvik VM, and the various Android packages (such as the Android framework and preinstalled applications). The emulator provides dynamic binary translation of device machine code to the OS and processor architecture of our development machine. The Android emulator supports many hardware features likely to be found on mobile devices, including: An ARMv5 CPU and the corresponding memory-management unit (MMU). A 16-bit LCD display. One or more keyboards (a Qwerty-based keyboard and associated Dpad/Phone buttons). A sound chip with output and input capabilities.

Flash memory partitions (emulated through disk image files on the development machine). A GSM modem, including a simulated SIM Card. A camera, using a webcam connected to our development computer. Sensors like an accelerometer, using data from a USB-connected Android device.

DAY-31:

WEEK-6: LAYOUTS IN ANDROID

Layouts: A layout defines the visual structure for a user interface, such as the UI for an activity or app widget. We can declare a layout in two ways: Declare UI elements in XML: Android provides a straightforward XML vocabulary that corresponds to the View classes and subclasses, such as those for widgets and layouts. Instantiate layout elements at runtime: Our application can create View and ViewGroup objects (and manipulate their properties) programmatically. The Android framework gives us the flexibility to use either or both of these methods for declaring and managing your application's UI. For example, we can declare our application's default layouts in XML, including the screen elements that will appear in them and their properties. We can then add code in our application that would modify the state of the screen objects, including those declared in XML, at run time. The ADT Plugin for Eclipse offers a layout preview of your XML with the XML file opened, select the Layout tab. We should also try the Hierarchy Viewer tool, for debugging layouts it reveals layout property values, draws wireframes with padding/margin indicators, and full rendered views while we debug on the emulator or device. The layout opt tool lets us quickly analyze our layouts and hierarchies for inefficiencies or other problems. The advantage to declaring our UI in XML is that it enables us to better separate the presentation of our application from the code that controls its behavior. Our UI descriptions are external to our application code, which means that we can modify or adapt it without having to modify our source code and recompile. For example, we can create XML layouts for different screen orientations, different device

screen sizes, and different languages. Additionally, declaring the layout in XML makes it easier to visualize the structure of our UI, so it's easier to debug problems. There are different types of layouts which we will work on while creating our applications. In Eclipse, we are provided with six layouts: Grid Layout Table Layout Linear Layout (Horizontal) Linear Layout (Vertical) Relative Layout Frame Layout

DAY-32:

CONTENTS OF AN APLLIACTION

The contents of an application are as follows: AndoirdManifest.xml R.java Activity_main.xml AndroidManifest.xml: Every application must have an AndroidManifest.xml file (with precisely that name) in its root directory. The manifest presents essential information about the application to the Android system, information the system must have before it can run any of the application's code. Among other things, the manifest does the following: It names the Java package for the application. The package name serves as a unique identifier for the application. It describes the components of the application the activities, services, broadcast receivers, and content providers that the application is composed of. It names the classes that implement each of the components and publishes their capabilities (for example, which Intent messages they can handle). These declarations let the Android system know what the components are and under what conditions they can be launched. It determines which processes will host application components. It declares which permissions the application must have in order to access protected parts of the API and interact with other applications. It also declares the permissions that others are required to have in order to interact with the application's components. It lists the Instrumentation classes that provide profiling and other information as the application is running. These declarations are present in the manifest only while the application is being developed and tested; they're removed before the application is published. It declares the minimum level of the Android API that the application requires. It lists the libraries that the application must be linked against.

Structure of AndroidManifest.xml: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.app4" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="10" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.app4.MainActivity" 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>

DAY-33: R.java: This is an auto-generated file. It stores constants of the resources in the activity. It acts as an interface between the resources and the java file.

Structure of R.java: /* AUTO-GENERATED FILE. DO NOT MODIFY. */ package com.app4; public final class R { public static final class attr { } public static final class dimen { public static final int activity_horizontal_margin=0x7f040000; public static final int activity_vertical_margin=0x7f040001; } public static final class drawable { public static final int ic_launcher=0x7f020000; } public static final class id { public static final int action_settings=0x7f080002; public static final int button1=0x7f080000; public static final int textView1=0x7f080001; } public static final class layout { public static final int activity_main=0x7f030000; } public static final class menu { public static final int main=0x7f070000; } public static final class string { public static final int Hello_String=0x7f050003;

public static final int action_settings=0x7f050001; public static final int app_name=0x7f050000; public static final int hello_world=0x7f050002; } public static final class style { public static final int AppBaseTheme=0x7f060000; public static final int AppTheme=0x7f060001; } }

DAY-34: Activity_Main.xml: This file tells us about the User Interface of the application, i.e., how our application is going to look after completion. Whatever form widgets we use in our application automatically be described here in this file.

Structure of Activity_Main.xml:

DAY-35:

APK FILE

APK File: Application Package File (APK) is the file format used to distribute and install application software and middleware onto Google's Android operating system; very similar to an MSI package in Windows or a Deb package in Debian-based operating systems like Ubuntu. To make an APK file, a program for Android is first compiled, and then all of its parts are packaged into one file. An APK file contains all of that program's code (such as.dex files), resources, assets, certificates, and manifest file. As is the case with many file formats, APK files can have any name needed, provided that the file name ends in ".apk". Each time we upload an APK using the Google Play Developer Console, we have the option to add one or two expansion files to the APK. Each file can be up to 2GB and it can be any format we choose, but it is recommended that we use a compressed file to conserve bandwidth during the download. Conceptually, each expansion file plays a different role: The main expansion file is the primary expansion file for additional resources required by our application. The patch expansion file is optional and intended for small updates to the main expansion file. While we can use the two expansion files any way we wish, it is recommended that the main expansion file deliver the primary assets and should rarely if ever updated; the patch expansion file should be smaller and serve as a patch carrier, getting updated with each major release or as necessary. However, even if our application update requires only a new patch expansion file, we still must upload a new APK with an updated version Code in the manifest.

File name format: Each expansion file we upload can be any format we choose (ZIP, PDF, MP4, etc.). We can also use the JOBB tool to encapsulate and encrypt a set of resource files and subsequent patches for that set. Regardless of the file type, Google Play

considers them opaque binary blobs and renames the files using the following scheme: [main|patch].<expansion-version>.<package-name>.obb

There are three components to this scheme: main or patch Specifies whether the file is the main or patch expansion file. There can be only one main file and one patch file for each APK. <expansion-version> This is an integer that matches the version code of the APK with which the expansion is first associated (it matches the application's android:versionCode value). "First" is emphasized because although the Developer Console allows us to re-use an uploaded expansion file with a new APK, the expansion file's name does not changeit retains the version applied to it when we first uploaded the file. <package-name> Your application's Java-style package name.

DAY-36:

IMPLEMENTATION OF APK FILE

Implementation Of APK File: Firstly, in the main menu, there is no application named, Hindi-Sher-O-Shayari, as we can see in the image below.

Then we choose to install this application by transferring the .apk file from our project to the mobile phone.

It asks for our confirmation to install the application.

If we choose to install, the .apk file gets installed in our phone.

Now, we can see the installed application in the main menu of our phone and we can simply use it just like another applications.

You might also like