Why You Need to Read Our Android Tutorial?
Javtpoint.com develops Android Tutorial which allows you to solve each and every question. Al We made it in easy manner with full of examples so that you do not need to go anywhere. We ensure you that if you will use our Android tutorial then you will get an appropriate answer easily.
What is Android?
Android is an open source and Linux-based Operating System for cell phones, for example, cell phones and tablet machines. Android was produced by the Open Handset Alliance, headed by Google, and different organizations.
Android offers a bound together approach to application improvement for cell phones which implies designers require create for Android, and their applications ought to have the capacity to run on distinctive gadgets fueled by Android.
Features of Android
- Beautiful UI: Android OS basic screen provides a beautiful and intuitive user interface.
- Connectivity: GSM/EDGE, IDEN, CDMA, EV-DO, UMTS, Bluetooth, Wi-Fi, LTE, NFC and WiMAX.
- Storage: SQLite, a lightweight relational database, is used for data storage purposes.
- Media support :H.263, H.264, MPEG-4 SP, AMR, AMR-WB, AAC, HE-AAC, AAC 5.1, MP3, MIDI, Ogg Vorbis, WAV, JPEG, PNG, GIF, and BMP
- Messaging: SMS and MMS
- Web browser: Based on the open-source WebKit layout engine, coupled with Chrome's V8 JavaScript engine supporting HTML5 and CSS3.
- Multi-touch: Android has native support for multi-touch which was initially made available in handsets such as the HTC Hero.
- Multi-tasking: User can jump from one task to another and same time various application can run simultaneously.
- Resizable widgets: Widgets are resizable, so users can expand them to show more content or shrink them to save space
- Multi-Language:Supports single direction and bi-directional text.
- GCM:Google Cloud Messaging (GCM) is a service that lets developers send short message data to their users on Android devices, without needing a proprietary sync solution.
- Wi-Fi Direct: A technology that lets apps discover and pair directly, over a high-bandwidth peer-to-peer connection.
- Android Beam: A popular NFC-based technology that lets users instantly share, just by touching two NFC-enabled phones together.
Step 1 - Setup Java Development Kit (JDK)
You can download the latest version of Java JDK from Oracle's Java site: Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively.
set PATH=C:\jdk1.6.0_15\bin;%PATH%
set JAVA_HOME=C:\jdk1.6.0_15
On Linux, if the SDK is installed in /usr/local/jdk1.6.0_15 and you use the C shell, you would put the following code into your .cshrc file.
setenv PATH /usr/local/jdk1.6.0_15/bin:$PATH
setenv JAVA_HOME /usr/local/jdk1.6.0_15
Step 2 - Setup Android SDK
You can download the latest version of Android SDK from Android official website: Android SDK Downloads. If you are installing SDK on Windows machine, then you will find a installer_rXX-windows.exe, so just download and run this exe which will launch Android SDK Tool Setup wizard to guide you through out of the installation, so just follow the instructions carefully. Finally you will haveAndroid SDK Tools installed on your machine.
If you are installing SDK either on Mac OS or Linux, check the instructions provided along with the downloaded android-sdk_rXX-macosx.zip file for Mac OS and android-sdk_rXX-linux.tgz file for Linux. This tutorial will consider that you are going to setup your environment on Windows machine having Windows 7 operating system.
So let's launch Android SDK Manager using the option All Programs > Android SDK Tools > SDK Manager, this will give you following window:
Once you launched SDK manager, its time to install other required packages. By default it will list down total 7 packages to be installed, but I will suggest to de-select Documentation for Android SDK andSamples for SDK packages to reduce installation time. Next click Install 7 Packages button to proceed, which will display following dialogue box:
If you agree to install all the packages, select Accept All radio button and proceed by clicking Install button. Now let SDK manager do its work and you go, pick up a cup of coffee and wait until all the packages are installed. It may take some time depending on your internet connection. Once all the packages are installed, you can close SDK manager using top-right cross button.
Step 3 - Setup Eclipse IDE
To install Eclipse IDE, download the latest Eclipse binaries from https://www.eclipse.org/downloads/. Once you downloaded the installation, unpack the binary distribution into a convenient location. For example in C:\eclipse on windows, or /usr/local/eclipse on Linux and finally set PATH variable appropriately. Eclipse can be started by executing the following commands on windows machine, or you can simply double click on eclipse.exe
%C:\eclipse\eclipse.exe
Eclipse can be started by executing the following commands on Linux machine:
$/usr/local/eclipse/eclipse
After a successful startup, if everything is fine then it should display following result:
Step 4 - Setup Android Development Tools (ADT) Plug-in
This step will help you in setting Android Development Tool plugin for Eclipse. Let's start with launching Eclipse and then, choose Help > Software Updates > Install New Software. This will display the following dialogue box
Now use Add button to add ADT Plugin as name and https://dl-ssl.google.com/android/eclipse/ as the location. Then click OK to add this location, as soon as you will click OK button to add this location, Eclipse starts searching for the plug-in available the given location and finally lists down the found plugins.
Now select all the listed plug-ins using Select All button and click Next button which will guide you ahead to install Android Development Tools and other required plugins.
Step 5 - Create Android Virtual Device
To test your Android applications you will need a virtual Android device. So before we start writing our code, let us create an Android virtual device. Launch Android AVD Manager using Eclipse menu optionsWindow > AVD Manager> which will launch Android AVD Manager. Use New button to create a new Android Virtual Device and enter the following information, before clicking Create AVD button.
If your AVD is created successfully it means your environment is ready for Android application development. If you like, you can close this window using top-right cross button. Better you re-start your machine and once you are done with this last step, you are ready to proceed for your first Android example but before that we will see few more important concepts related to Android Application Development.
Android Architecture
Linux kernel
At the bottom of the layers is Linux - Linux 2.6 with approximately 115 patches. This provides basic system functionality like process management, memory management, device management like camera, keypad, display etc. Also, the kernel handles all the things that Linux is really good at such as networking and a vast array of device drivers, which take the pain out of interfacing to peripheral hardware.
Libraries
On top of Linux kernel there is a set of libraries including open-source Web browser engine WebKit, well known library libc, SQLite database which is a useful repository for storage and sharing of application data, libraries to play and record audio and video, SSL libraries responsible for Internet security etc.
Android Runtime
This is the third section of the architecture and available on the second layer from the bottom. This section provides a key component called Dalvik Virtual Machine which is a kind of Java Virtual Machine specially designed and optimized for Android.
The Dalvik VM makes use of Linux core features like memory management and multi-threading, which is intrinsic in the Java language. The Dalvik VM enables every Android application to run in its own process, with its own instance of the Dalvik virtual machine.
The Android runtime also provides a set of core libraries which enable Android application developers to write Android applications using standard Java programming language.
Application Framework
The Application Framework layer provides many higher-level services to applications in the form of Java classes. Application developers are allowed to make use of these services in their applications.
Applications
Application components are the essential building blocks of an Android application. These components are loosely coupled by the application manifest file AndroidManifest.xml that describes each component of the application and how they interact.
Components |
Description |
Activities |
They dictate the UI and handle the user interaction to the smartphone screen |
Services |
They handle background processing associated with an application. |
Broadcast Receivers |
They handle communication between Android OS and applications. |
Content Providers |
They handle data and database management issues. |
Activities
An activity represents a single screen with a user interface. For example, an email application might have one activity that shows a list of new emails, another activity to compose an email, and another activity for reading emails. If an application has more than one activity, then one of them should be marked as the activity that is presented when the application is launched.
An activity is implemented as a subclass of Activity class as follows:
public class MainActivity extends Activity {}
Services
A service is a component that runs in the background to perform long-running operations. For example, a service might play music in the background while the user is in a different application, or it might fetch data over the network without blocking user interaction with an activity.
A service is implemented as a subclass of Service class as follows:
public class MyService extends Service {}
Broadcast Receivers
Broadcast Receivers simply respond to broadcast messages from other applications or from the system. For example, applications can also initiate broadcasts to let other applications know that some data has been downloaded to the device and is available for them to use, so this is broadcast receiver who will intercept this communication and will initiate appropriate action.
A broadcast receiver is implemented as a subclass of BroadcastReceiver class and each message is broadcasted as an Intent object.
public class MyReceiver extends BroadcastReceiver {}
A content provider component supplies data from one application to others on request. Such requests are handled by the methods of the ContentResolver class. The data may be stored in the file system, the database or somewhere else entirely.
A content provider is implemented as a subclass of ContentProvider class and must implement a standard set of APIs that enable other applications to perform transactions.
public class MyContentProvider extends ContentProvider {}
Additional Components
Components |
Description |
Fragments |
Represents a behavior or a portion of user interface in an Activity. |
Views |
UI elements that are drawn onscreen including buttons, lists forms etc. |
Layouts |
View hierarchies that control screen format and appearance of the views. |
Intents |
Messages wiring components together. |
Resources |
External elements, such as strings, constants and drawables pictures. |
Manifest |
Configurations file for the application. |
Android Layout Types
S.N. |
Layout & Description |
1 |
Linear Layout |
2 |
Relative Layout |
3 |
Table Layout |
4 |
Absolute Layout |
5 |
Frame Layout |
6 |
List View |
7 |
Grid View |
Layout Attributes
Attribute |
Description |
android:id |
This is the ID which uniquely identifies the view. |
android:layout_width |
This is the width of the layout. |
android:layout_height |
This is the height of the layout |
android:layout_marginTop |
This is the extra space on the top side of the layout. |
android:layout_marginBottom |
This is the extra space on the bottom side of the layout. |
android:layout_marginLeft |
This is the extra space on the left side of the layout. |
android:layout_marginRight |
This is the extra space on the right side of the layout. |
android:layout_gravity |
This specifies how child Views are positioned. |
android:layout_weight |
This specifies how much of the extra space in the layout should be allocated to the View. |
android:layout_x |
This specifies the x-coordinate of the layout. |
android:layout_y |
This specifies the y-coordinate of the layout. |
android:layout_width |
This is the width of the layout. |
android:layout_width |
This is the width of the layout. |
android:paddingLeft |
This is the left padding filled for the layout. |
android:paddingRight |
This is the right padding filled for the layout. |
android:paddingTop |
This is the top padding filled for the layout. |
android:paddingBottom |
This is the bottom padding filled for the layout. |
Here width and height are the dimension of the layout/view which can be specified in terms of dp (Density-independent Pixels), sp ( Scale-independent Pixels), pt ( Points which is 1/72 of an inch), px( Pixels), mm ( Millimeters) and finally in (inches).
You can specify width and height with exact measurements but more often, you will use one of these constants to set the width or height:
· android:layout_width=wrap_content tells your view to size itself to the dimensions required by its content.
· android:layout_width=fill_parent tells your view to become as big as its parent view.
Gravity attribute plays important role in positioning the view object and it can take one or more (separated by '|') of the following constant values.
View Identification
A view object may have a unique ID assigned to it which will identify the View uniquely within the tree. The syntax for an ID, inside an XML tag is:
android:id="@+id/my_button"
Following is a brief description of @ and + signs:
· The at-symbol (@) at the beginning of the string indicates that the XML parser should parse and expand the rest of the ID string and identify it as an ID resource.
· The plus-symbol (+) means that this is a new resource name that must be created and added to our resources. To create an instance of the view object and capture it from the layout, use the following:
Button myButton = (Button) findViewById(R.id.my_button);
Android UI Controls
S.N. |
UI Control & Description |
1 |
Text View |
2 |
Edit Text |
3 |
Auto Complete Text View |
4 |
Button |
5 |
Image Button |
6 |
Checkbox |
7 |
Toggle Button |
8 |
Radio Button |
9 |
Radio Group |
10 |
Progress Bar |
11 |
Spinner |
12 |
Time Picker |
13 |
Date Picker |
Create UI Controls
As explained in previous chapter, a view object may have a unique ID assigned to it which will identify the View uniquely within the tree. The syntax for an ID, inside an XML tag is:
android:id="@+id/text_id"
To create a UI Control/View/Widget you will have to define a view/widget in the layout file and assign it a unique ID as follows:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView android:id="@+id/text_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I am a TextView" />
</LinearLayout>
Then finally create an instance of the Control object and capture it from the layout, use the following:
TextView myText = (TextView) findViewById(R.id.text_id);
Android Event Handling
Event Listeners & Event Handlers
Event Handler |
Event Listener & Description |
onClick() |
OnClickListener() |
onLongClick() |
OnLongClickListener() |
onFocusChange() |
OnFocusChangeListener() |
onKey() |
OnFocusChangeListener() |
onTouch() |
OnTouchListener() |
onMenuItemClick() |
OnMenuItemClickListener() |
Event Listeners Registration:
Event Registration is the process by which an Event Handler gets registered with an Event Listener so that the handler is called when the Event Listener fires the event. Though there are several tricky ways to register your event listener for any event, but I'm going to list down only top 3 ways, out of which you can use any of them based on the situation.
· Using an Anonymous Inner Class
· Activity class implements the Listener interface.
· Using Layout file activity_main.xml to specify event handler directly.
Below section will provide you detailed examples on all the three scenarios
Defining Styles
A style is defined in an XML resource that is separate from the XML that specifies the layout. This XML file resides under res/values/ directory of your project and will have <resources> as the root node which is mandatory for the style file. The name of the XML file is arbitrary, but it must use the .xml extension.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="CustomFontStyle">
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:capitalize">characters</item>
<item name="android:typeface">monospace</item>
<item name="android:textSize">12pt</item>
<item name="android:textColor">#00FF00</item>/>
</style>
</resources>
Using Styles
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView android:id="@+id/text_id"
style="@style/CustomFontStyle"
android:text="@string/hello_world" />
</LinearLayout>
Style Inheritance
Android supports style Inheritance in very much similar way as cascading style sheet in web design. You can use this to inherit properties from an existing style and then define only the properties that you want to change or add.
Its simple, to create a new style LargeFont that inherits the CustomFontStyle style defined above, but make the font size big, you can author the new style like this:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="CustomFontStyle.LargeFont">
<item name="android:textSize">20ps</item>
</style>
</resources>
You can reference this new style as @style/CustomFontStyle.LargeFont in your XML Layout file. You can continue inheriting like this as many times as you'd like, by chaining names with periods. For example, you can extend FontStyle.LargeFont to be Red, with:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="CustomFontStyle.LargeFont.Red">
<item name="android:textColor">#FF0000</item>/>
</style>
</resources>
This technique for inheritance by chaining together names only works for styles defined by your own resources. You can't inherit Android built-in styles this way. To reference an Android built-in style, such as TextAppearance, you must use the parent attribute as shown below:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="CustomFontStyle" parent="@android:style/TextAppearance">
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:capitalize">characters</item>
<item name="android:typeface">monospace</item>
<item name="android:textSize">12pt</item>
<item name="android:textColor">#00FF00</item>/>
</style>
</resources>
Android Themes
Hope you understood the concept of Style, so now let's try to understand what is a Theme. A theme is nothing but an Android style applied to an entire Activity or application, rather than an individual View.
Thus, when a style is applied as a theme, every View in the Activity or application will apply each style property that it supports. For example, you can apply the same CustomFontStyle style as a theme for an Activity and then all text inside that Activity will have green monospace font.
To set a theme for all the activities of your application, open the AndroidManifest.xml file and edit the<application> tag to include the android:theme attribute with the style name. For example
<application android:theme="@style/CustomFontStyle">
But if you want a theme applied to just one Activity in your application, then add the android:theme attribute to the <activity> tag only. For example:
<activity android:theme="@style/CustomFontStyle">
There are number of default themes defined by Android which you can use directly or inherit them using parent attribute as follows:
<style name="CustomTheme" parent="android:Theme.Light">
...
</style>
Creating a Simple Custom Component
The simplest way to create your custom component is to extend an existing widget class or subclass with your own class if you want to extend the functionality of existing widget like Button, TextView, EditText, ListView, CheckBox etc. otherwise you can do everything yourself by starting with theandroid.view.View class.
At its simplest form you will have to write your constructors corresponding to all the constructors of the base class. For example if you are going to extend TextView to create a DateView then following three constructors will be created for DateView class:
public class DateView extends TextView {
public DateView(Context context) {
super(context);
//--- Additional custom code --
}
public DateView(Context context, AttributeSet attrs) {
super(context, attrs);
//--- Additional custom code --
}
public DateView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
//--- Additional custom code --
}
}
Because you have created DateView as child of TextView so it will have access on all the attributes, methods and events related to TextView and you will be able to use them without any further implementation. You will implement additional custom functionality inside your own code as explained in the given examples below.
If you have requirement for implementing custom drawing/sizing for your custom widgets then you need to override onMeasure(int widthMeasureSpec, int heightMeasureSpec) and onDraw(Canvas canvas) methods. If you are not going to resize or change the shape of your built-in component then you do not need either of these methods in your custom component.
The onMeasure() method coordinate with the layout manager to report the widget's width and height, and you need to call setMeasuredDimension(int width, int height) from inside this method to report the dimensions.
You can then execute your custom drawing inside the onDraw(Canvas canvas) method, where android.graphis.Canvas is pretty similar to its counterpart in Swing, and has methods such as drawRect(), drawLine(), drawString(), drawBitmap() etc. which you can use to draw your component.
INSTANTIATE USING CODE INSIDE ACTIVITY CLASS
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DateView dateView = new DateView(this);
setContentView(dateView);
}
INSTANTIATE USING LAYOUT XML FILE
Traditionally you use Layout XML file to instantiate your built-in widgets, same concept will apply on your custom widgets as well so you will be able to instantiate your custom component using Layout XML file as explained below. Here com.example.dateviewdemo is the package where you have put all the code related to DateView class and DateView is Java class name where you have put complete logic of your custom component.
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<com.example.dateviewdemo.DateView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#fff"
android:textSize="40sp"
android:background="#000"
/>
</RelativeLayout>
Custom Component with Custom Attributes
We have seen how we can extend functionality of built-in widgets but in both the examples given above we saw that extended component can make use of all the default attributes of its parent class. But consider a situation when you want to create your own attribute from scratch. Below is a simple procedure to create and use new attributes for Android Custom components. Consider we want to introduce three attributes and will use them as shown below:
<com.example.dateviewdemo.DateView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#fff"
android:textSize="40sp"
custom:delimiter="-"
custom:fancyText="true"
/>
STEP 1
The first step to enable us to use our custom attributes is to define them in a new xml file underres/values/ and call it attrs.xml. Let's have a look on an example attrs.xml file:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="DateView">
<attr name="delimiter" format="string"/>
<attr name="fancyText" format="boolean"/>
</declare-styleable>
</resources>
STEP 2
Your second step will be to read these attributes from Layout XML file and set them for the component. This logic will go in the constructors that get passed an AttributeSet, since that is what contains the XML attributes. To read the values in the XML, you need to first create a TypedArray from theAttributeSet, then use that to read and set the values as shown in the below example code:
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.DateView);
final int N = a.getIndexCount();
for (int i = 0; i < N; ++i)
{
int attr = a.getIndex(i);
switch (attr)
{
case R.styleable.DateView_delimiter:
String delimiter = a.getString(attr);
//...do something with delimiter...
break;
case R.styleable.DateView_fancyText:
boolean fancyText = a.getBoolean(attr, false);
//...do something with fancyText...
break;
}
}
a.recycle();
STEP 3
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
xmlns:custom="https://schemas.android.com/apk/res/com.example.dateviewdemo"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<com.example.dateviewdemo.DateView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#fff"
android:textSize="40sp"
custom:delimiter="-"
custom:fancyText="true"
/>
</RelativeLayout>
The important part isxmlns:custom="https://schemas.android.com/apk/res/com.example.dateviewdemo". Note thathttps://schemas.android.com/apk/res/ will remain as is, but last part will be set to your package name and also that you can use anything after xmlns:, in this example I used custom, but you could use any name you like.
<o:p></o:p>