Android Tutorial – Learn Android From Scratch!
Android Tutorial – Learn Android From Scratch!
In this article, we discuss the basics behind Android app development, including architecture, application anatomy, and a quick "Hello, World"app.
Join the DZone community and get the full member experience.
Join For FreeA common dilemma faced by many developers is whether to go with Android or IOS? Well, all I can say is, “it all depends on CHOICES!” To me, Android is the best bet. Why? Android today has managed to hold 88% of the global market, whereas competitors like Apple’s IOS and Windows are way behind.
In this tutorial, I will take you through an introduction to Android app development, so you can get started building your own.
You may also like: Code Gems for Android Developers.
Why Android?
Android is the most successful and powerful mobile operating system in the market today. Before jumping into the tutorial, let’s understand why Android is a good choice to develop applications with.
- Open source.
- Customizable operating system.
- Reduce the cost of development and overall complexity.
- Larger community and developer reach.
- Inter-app integration.
- Higher success ratio.
- Rich development environment – a variety of apps can be developed.
Low-cost smartphones in emerging markets and strong demand for premium smartphones continued to be the driving factors,” said Anshul Gupta, research director at Gartner.
This is surely Google’s magic. Now, let’s see how Android has evolved.
Evolution of Android
Google has launched several different versions of Android. The name of these versions is in alphabetical order, such as Cupcake, Donut, Eclair, Froyo, Gingerbread, and so on. Now, the interesting fact to be noticed in these versions is the name of the operating system, which is named after desserts. Isn’t that great? Hence, the latest version i.e 7.0 is named after Nougat, which is said to be the sweetest release to date.
Let us see different versions that have come across till now. The initial versions of Android (1.0 and 1.1) were not given any specific names. They were the initial versions that became the base for the upcoming android versions with mind-boggling innovations.
Android Architecture
Android OS is a software stack of different layers, in which each layer is a group of some program components. It includes your operating system, middleware, and important applications. Each layer in the architecture provides different services to the layer just above it.
The f8ollowing are the different layers in the Android stack:
- Linux Kernel Layer – Linux kernel is the bottom-most layer in the architecture of Android. It never really interacts with the users and developers, but it is at the heart of the whole system. Its importance stems from the fact that it provides functions in the Android system, such as hardware abstraction, memory management programs, security settings, power management software, other hardware drivers, network stack, etc.
- Libraries – The next layer in the Android architecture includes libraries. Libraries carry a set of instructions to guide the device to handle different types of data. For example, the playback and recording of various audio and video formats are guided by the Media Framework Library.
- Runtime – The third section of the architecture is runtime, which provides a key component called Dalvik Virtual Machine (DVM). Dalvik is open source software, and Java Virtual Machine is specially designed and optimized for Android.
- Application Framework – Our applications directly interact with these blocks of Android architecture. These programs manage the basic functions of phones like resource management, voice call management, etc. It provides many higher-level services to applications in the form of Java classes. Some important blocks of the Application Framework are activity management, content providers, resource manager, notification manager, view system, etc.
- Applications Layer – The applications are at the topmost layer of the Android stack. All the applications will be installed in this layer, such as address books, games, etc.
Features
As we all know, Android has plenty of features. Some of the major features are listed below:
- UserInterface — The Android operating system provides a UI that is associated with the activity and presented to the user.
- Messaging — It supports messaging services (SMS, MMS).
- Web Browser — It is based on the open source WebKit layout engine, which is coupled with Chrome’s V8 JavaScript engine that supports HTML5 and CSS3.
- Connectivity — It has various connections such as Bluetooth, Wi-Fi, GSM/EDGE, CDMA, etc.
- Storage — A light relational database, SQL (SQLite), is used for storage purposes.
- Multi-touch — Android has native support for the multi-touch features.
- Multi-tasking — Android supports multitasking where the user can perform multiple tasks simultaneously.
- Multi-Language — It supports a single direction and bidirectional text features.
- Wi-Fi Direct —Android supports a feature that lets apps discover and pair directly over a high-bandwidth peer-to-peer connection.
- Android Beam —This feature is used to share instantly just by touching two NFC enabled phones together.
Apart from these, Android is used in various fields. If you open your play store, there are several categories where Android can be used. Some of them are mentioned below:
By now, you know some of the basics behind Android. Let's move forward in our Android tutorial blog and understand the core building blocks of Android!
Core Buildings Blocks
There are five main components that are considered to be the core building blocks within an Android application:
- Activity.
- Services.
- Broadcast Receivers.
- Content Providers.
- Manifest.
Let’s understand them in detail.
Activity
An Activity is the screen representation of any application in Android.
It serves as an entry point for the user’s interaction. Each activity has a layout file where you can place your UI. An application can have different activities. For example, the Facebook start page where you enter your email/phone and password to login acts as an activity.
Below are the two methods, which almost all subclasses of Activity will implement:
onCreate(Bundle)
: It is a method where your initialization is done. Under this, you will call setContentView(int)
with a layout resource that defines your UI. Also, you can retrieve the widgets in that UI by using findViewById(Int)
. These are required to interact programmatically.
onPause()
: It is a method which deals with the user whenever it leaves the activity. So, any changes made by the user should be committed, which is done by the ContentProvider
that holds data. An activity is implemented as a subclass of the Activity
class as follows:
public class MainActivity extends Activity {
}
Now, let’s move ahead and understand the activity life cycle.
Activity Life Cycle
As the user navigates between different screens or apps, it goes through different stages in their lifecycle. So, an activity lifecycle consists of seven different methods of the android.app.Activity
class.
You must be aware that a program starts from a main()
function in different programming languages. Similarly, Android initiates the program within an activity with a call to the onCreate()
callback method. There is a sequence of callback methods that starts up an activity and then tears down that activity in different methods shown in the above Activity life cycle diagram:
Let’s understand these methods:
-
onCreate()
: In this state, the activity is created. -
onStart()
: This callback method is called when the activity becomes visible to the user. -
onResume()
: The activity is in the foreground, and the user can interact with it. -
onPause()
: Activity is partially obscured by another activity. Another activity that’s in the foreground is semi-transparent. -
onStop()
: The activity is completely hidden and not visible to the user. -
onDestroy()
: Activity is destroyed and removed from memory.
Services
A service in Android is a background process that is used to perform long-running operations. Let’s say a service of type location is active in the background while the user is in different applications. So it does not disturb the user interaction with an activity. Now, services are classified into two types, namely:
- Local: This service is accessed from within the application.
- Remote: This service is accessed remotely from other applications running on the same device.
It is implemented as a subclass of Service
as follows :
public class MyService extends Service {
}
Broadcast Receiver
A Broadcast Receiver is a mechanism that allows a host application to listen for System-level events. A Broadcast Receiver is used by the application whenever they need to perform the execution based on System events — like listening for incoming calls, SMS, etc. Broadcast Receivers help in responding to broadcast messages from other applications or from the system. They are used to handle communication between the Android operating system and applications.
They are implemented as a subclass of BroadcastReceiver
class, and each message is broadcaster as an Intent
object.
public class Myreceiver extends BroadcastReceiver{
public void onReceive(context,intent){}
}
Content Provider
Content Providers manage access to a structured set of data. It is the standard interface that connects data in one process with code running in other processes. They encapsulate data and provide mechanisms for defining data security. Content Providers are used to share data between different applications.
They are implemented as a subclass of ContentProvider
class and must implement as a standard set of APIs that enable other applications to perform transactions.
public class MyContentprovider extends ContentProvider {
public void onCreate(){}
}
Finally, let’s move on to our last building block in Android (i.e. Manifest).
Manifest
The manifest file plays an integral role, as it provides essential information about your app to the Android system. The system must have this information before it can run any of the app’s code. Manifest files performs various tasks such as:
- Naming the Java package for the app, as the package name serves as a unique identifier for the application.
- Protecting the application by declaring permissions in order to access protected parts of the API and interact with other applications.
- Declaring the minimum level of the Android API and listing the libraries that are linked with the application.
- Listing instrumentation classes. These classes provide profiling and other information as the application runs, but this information is removed as soon the application is published. It remains only until the application is in development mode.
Structure of a manifest file: The structure of a manifest file consists of various elements, such as action, activity, activity-alias, and many more. Refer to the below screenshot, which shows the general structure of the manifest file.
Moving ahead, let’s understand the anatomy of an android application.
Android Application Anatomy
App: It describes the fundamental characteristics of the app and defines each of its components.
Java: This contains the .java source files for your project. By default, it includes an MainActivity.java source file. Under this, you create all the activities that have .java extensions and all the code behind the application. MainActivity.java is the actual file that gets converted to a dalvik executable and runs your app.
Res: It is a directory for files that define your app’s user interface. You can add TextView, button, etc. to build the GUI and use its various attributes, such as android:layout_width
, android:layout_height
, etc, which are used to set its width and height.
Gradle scripts: This is an auto-generated file that contains compileSdkVersion
, buildToolsVersion
, applicationId
, minSdkVersion
,targetSdkVersion
, versionCode
, and versionName
.
Now that you understand all the components in an Android app, let’s implement them!
Installation
First, let me excite you by telling that you can start developing Android applications on any operating system. It can be Microsoft Windows XP or a later version, Mac OS, or Linux.
Now, to start off with implementation, we need to install the following software:
- JDK – Java Development Kit.
- Android Studio.
Let’s get started by installing JDK in the system. To download it, you can follow the below steps:
- Go to the link: http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html.
- You can download the JDK, as per your system’s requirement.
Once its there in your system, you can go ahead and follow the below process to download and install Android Studio on your system.
- Go to the link: https://developer.android.com/studio/index.html.
- Download the latest version of Android Studio (2.3.3).
You can refer to the following screenshot to get a better understanding:
Let us move forward and do some hands-on coding where we will create a basic Android application. So, let’s begin coding!
My First Application
Let’s create a very basic Android application. First of all, we need to create a new project in Android Studio. To create a new project click on Start a new Android Studio Project.
After that, you can configure your project by giving Application name > Company domain > Package Location > click Next.
Then, you have to select the form factors your app will run on. Select Phoneand Tablet. Then, select the minimum SDK as API:9 Android 2.3 (Gingerbread).
Now that the target device is set, we can add an activity to Mobile.
For starters, let’s select Empty Activity and click Next.
Once you click on Next, you can customize your activity. In the “Customize the Activity” window, fill up the activity name and Layout name and click Finish.
Your project and activity have been created!
Let’s create an app that prints “Welcome to Edureka Android Tutorial”. For this, MainActivity.java file is the actual application file that will be executed first. So let’s have a look at the default code generated by the application for printing ‘Hello World’.
package com.example.aayushi.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
We’ve seen that the activities have a .java file extension. Let’s see the layout of the same activity. The activity_main.xml file is located in the res/layout folder. This file is referenced by your app when you build your UI. By default, "Hello World"
printed related to the default layout. You can change the android:text=” Welcome to Edureka Android Tutorial”
and size of the text in your layout file as written in the following code.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.aayushi.myapplication.MainActivity">
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Welcome to Edureka Android Tutorial" android:textSize="22dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
You are all done with the code. let’s run the app now!
For executing the code, you can directly Run ‘app’ or press ‘Shift+F10.’ Once you run it, it will ask you to select a deployment target. You can either connect your Android device through USB or create a virtual device. To create one virtual device, you can click Create New virtual device and choose the device according to your needs. Refer to the screenshot below:
Click Next and your virtual device is ready!
I have opted for Nexus_6 as my Android Emulator. Android Studio installs the app on your emulator, and if everything is fine with your set-up and application, the following screen will be displayed.
Congratulations! Your first Android app is ready!
This is the end of the Android tutorial blog. I hope you guys are clear about each and every aspect that I have discussed above. Stay tuned for other blogs and good luck with your Android Development career.
Published at DZone with permission of Aayushi Johari, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}
{{ parent.urlSource.name }}