192-2-SY-BSC-CS-SSEM-IV-Android-developer-fundamentals-INNER-PAGES-munotes

Page 1


1 1 INTRODUCTION TO ANDROID STRUCTURE Unit Structure : 1.0 Learning Objective 1.1 Introduction 1.2 Why Android 1.2.1 Features of Android 1.2.2 Steps to Install Android Studio 1.2.3 Creating A Project in Android 1.2.4 Creating AVD in Android Studio 1.3 Android Run Time(ART) 1.3.1 Dalvik Virtual Machine(DVM) 1.4 Android Studio 1.5 Introduction to Gradle 1.5.1 Fundamentals of Gradle 1.5.1.1 The code editor 1.5.1.2 The design editor 1.6 Basic Building Blocks 1.6.1 Activity and View 1.6.2 Intent 1.6.3 Service 1.6.4 Android Virtual Device (AVD) 1.6.5 Android Activities and Its life Cycle 1.6.6 Android Services 1.6.7 Broadcast Receiver and Content Provider 1.7 UI Components 1.7.1 TextView 1.7.2 Notification 1.8 Components for Communication 1.8.1 Intent Filters 1.9 Android API Level 1.10 Summary 1.11 Keywords 1.12 Learning Activity 1.13 Unit End Questions 1.14 References munotes.in

Page 2


2 Android Development Fundamental 1.0 LEARNING OBJECTIVES • By studying this unit students are be able to install the android studio and able to create the android application in Android Studio. • Also Students are able to run the applications using Android Virtual Device(AVD) . • At the end of this unit students can make simple mobile applications. 1.1 INTRODUCTION • Android is a mobile operating system developed by Google. It is used by several smart phones and tablets. • The Android operating system (OS) is based on the Linux kernel. • Unlike Apple's IOS, Android is open source, meaning developers can modify and customize the OS for each phone. An install of Android Studio includes: • Android SDK the latest version of the Android SDK • Android SDK tools and platform tools for debugging and testing your apps A system image for the Android emulator lets you create and test your apps on different virtual devices • Downloading and Installing Android Studio • Android Studio is available from Android’s developer site at • If you do not already have it installed, you will need to install the Java Development Kit (JDK8), which you can download from 1.2 WHY ANDROID Zero/negligible development cost • The development tools like Android SDK, JDK, and Eclipse IDE etc. are free to download for the android mobile application development. Also Google charge a small fee $25, to distribute your mobile app on the Android Market. Open Source • The Android OS is an open-source platform based on the Linux kernel and multiple open-source libraries. In this way developers are free to contribute or extend the platform as necessary for building mobile apps which run on Android devices. developer.android.com/ sdk/ www.oracle.com munotes.in

Page 3


3
Introduction to Android
Structure Multi-Platform Support • In market, there are a wide range of hardware devices powered by the Android OS, including many different phones and tablet. Even development of android mobile apps can occur on Windows, Mac OS or Linux. Multi-Carrier Support • Worldwide a large number of telecom carriers like Airtel, Vodafone, Idea Cellular, AT&T Mobility, BSNL etc. are supporting Android-powered phones. Open Distribution Model • Android Market place (Google Play store) has very few restrictions on the content or functionality of an android app. So the developer can distribute theirs app through the Google Play store and as well other distribution channels like Amazon’s app store. 1.2.1 FEATURES OF ANDROID There are numerous features of android. Some of them are listed below: Feature Description Connectivity Android supports multiple connectivity
technologies including 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 Android supports various type of audio/video/still
media formats like: H.263, H.264, MPEG -4 SP,
AMR, AMR -WB, AAC, HE-AAC, AAC 5.1,
MP3, MIDI, Ogg Vorbis, WAV, JPEG, PNG, GIF,
BMP and WebP Web browser The web browser available in Android is based on
the open -source Blink (previously WebKit) layout
engine, coupled with Chrome's V8 JavaScript
engine supporting HTML5 and CSS3 Messaging SMS and MMS are available forms of messaging,
it also include threaded text messaging and
Android Cloud To Device Messaging (C2DM) and
now support the enhanced version of C2DM,
Android Google Cloud Messaging (GCM) is also a
part of Android Push Messaging services Multi -tasking Multitasking of applications, with unique handling
of memory allocation, is available, using this user
can jump from one task to another and at the same
time various application can run simultaneously munotes.in

Page 4


4 Android Development Fundamental Feature Description Resizable widg ets Widgets are re -sizable, so users can expand them
to show more content or shrink them to save space Multi -touch Android has native support for multi -touch which
was initially made available in handsets such as the
HTC Hero Wi-Fi A technology that lets apps discover and pair
directly, over a high -bandwidth peer -to-peer
connection. Screen capture Android supports capturing a screenshot by
pressing the power and home -screen buttons at the
same time. This features supports after Android 4.0 Multi -Language Android supports multiple languages, also
supports single direction and bi -directional text The Android Studio • Android Studio provides a unified environment where you can build apps for Android phones, tablets, Android Wear, Android TV, and Android Auto. Structured code modules allow you to divide your project into units of functionality that you can independently build, test, and debug 1.4 STEPS TO INSTALL ANDROID STUDIO Step – 1: Head over to bellow link to get the Android Studio executable or zip file . https://developer.android.com/studio/#downloads Step – 2: Click on the download android studio button . Click on the “I have read and agree with the above terms and conditions” checkbox followed by the download button.
munotes.in

Page 5


5
Introduction to Android
Structure
Click on save file button in the appeared prompt box and the file will start downloading. Step – 3: After the downloading has finished, open the file from downloads and run it . It will prompt the following dialogue box

munotes.in

Page 6


6 Android Development Fundamental Click on next. In the next prompt it’ll ask for a path for installation. Choose a path and hit next. Step – 4: It will start the installation, and once it is completed, it will be like the image shown below
Click on next

munotes.in

Page 7


7
Introduction to Android
Structure Step – 5 : Once “Finish” is clicked, it will ask whether the previous settings needs to be imported [if android studio had been installed earlier], or not. It is better to choose the ‘Don’t import Settings option’ .
Step – 6 : This will start the Android Studio.
Meanwhile it will be finding the available SDK components . Step – 7: After it has found the SDK components, it will redirect to the Welcome dialog box .
munotes.in

Page 8


8 Android Development Fundamental
Click on next .
Choose Standard and click on Next. Now choose the theme, whether Light theme or the Dark one . The light one is called the IntelliJ theme whereas the dark theme is called Darcula . Choose as required.
munotes.in

Page 9


9
Introduction to Android
Structure
Click on the Next button Step – 8 : Now it is time to download the SDK components.
Click on Finish .

munotes.in

Page 10


10 Android Development Fundamental It has started downloading the components
The Android Studio has been successfully configured. Now it’s time to launch and build app. To create your new Android project, follow these steps: • Install the latest version of Android Studio. • In the Welcome to Android Studio window, click Start a new Android Studio project.


munotes.in

Page 11


11
Introduction to Android
Structure 1.2.3 Creating A Project in Android • If you have a project already opened, select File > New > New Project. • In the Choose your project window, select Empty Activity and click Next. • In the Configure your project window, complete the following: 1. Enter "My First App" in the Name field. 2. Enter "com.example.myfirstapp" in the Package name field. 3. If you'd like to place the project in a different folder, change its Save location. 4. Select either Java or Kotlin from the Language drop-down menu. • Select the checkbox next to Use androidx.* artifacts. • Leave the other options as they are. • Click Finish.
• After some processing time, the Android Studio main window appears. 1.2.4 Creating AVD in Android Studio 1. After the project is created, there are 2 files, MainActivity.java and activity_main.xml
To Open Project Window
select View > Tool Windows > Project To Open MainActivity.java file
app > java > PackageName > MainActivity.java To Open Layout
activity_main.xml file
app > res > layout > activity_main.xml munotes.in

Page 12


12 Android Development Fundamental 2. Go to activity_main.xml and select Design View 3. In Design View, change the layout to LinearLayout(Vertical) select Add TextView, and change the text to “Hello World!” 4. Click on Run and select the AVD already created(if not created, first create the AVD) 5. Output screen should show “Hello World” To create a new AVD: 1. Open the AVD Manager by clicking Tools > AVD Manager. 2. Click Create Virtual Device, at the bottom of the AVD Manager dialog.... 3. Select a hardware profile, and then click Next. 4. Select the system image for a particular API level, and then click Next. 5. Change AVD properties as needed, and then click Finish.


munotes.in

Page 13


13
Introduction to Android
Structure



munotes.in

Page 14


14 Android Development Fundamental 1.3 ANDROID RUNTIME (ART) • Dalvik Virtual Machine or DVM is a Register-Based virtual machine that was designed and written by Dan Bornstein. • Dalvik is a discontinued process virtual machine (VM) in the Android OS that executes applications written for Android.
1.4 THE ANDROID STUDIO • Android Studio provides the SDK and the emulator system image from the latest platform. • However, you may want to test your apps on earlier versions of Android. • You can get components for each platform using the Android SDK Manager. • In Android Studio, select Tools → Android → SDK Manager. • Under the Quick Start section, • select Configure → SDK Manager.) • The SDK Manager is shown in Figure .
munotes.in

Page 15


15
Introduction to Android
Structure
1.5 INTRODUCTION TO GRADLE • In Android Studio, Gradle is used for building our android application projects, hence playing the role of a build system. • Gradle is a build system, which is responsible for code compilation, testing, deployment and conversion of the code into . dex files and hence running the app on the device. • As Android Studio comes with Gradle system pre-installed, there is no need to install additional runtime softwares to build our project. • Whenever you click on Run button in android studio, a gradle task automatically triggers and starts building the project and after gradle completes its task, app starts running in AVD or in the connected device. • A build system like Gradle is not a compiler, linker etc, but it controls and supervises the operation of compilation, linking of files, running test cases, and eventually bundling the code into an apk file for your Android Application. There are two build.gradle files for every android studio project of which, one is for application and other is for project level(module level) build files. build.gradle (project level) The Top level (module) build.gradle file is project level build file, which defines build configurations at project level. This file applies configurations to all the modules in android application project. munotes.in

Page 16


16 Android Development Fundamental build.gradle (application level) The Application level build.gradle file is located in each module of the android project. This file includes your package name as applicationID, version name(apk version), version code, minimum and target sdk for a specific application module. When you are including external libraries(not the jar files) then you need to mention it in the app level gradle file to include them in your project as dependencies of the application.
1.5.1 FUNDAMENTALS OF GRADLE • An Android app is really just a bunch of valid files in a particular folder structure, and Android Studio sets all of this up for you when you create a new app. • The easiest way of looking at this folder structure is with the explorer in the leftmost column of Android Studio.
munotes.in

Page 17


17
Introduction to Android
Structure
The folder structure
includes different
types of files
If you browse through
the folder structure,
you’ll see that the
wizard has created
various types of files
and folders for you:
Java and XML
source files
These are the activity
and layout files the
wizard created for
you.
Resource files
These include default
image files for icons,
styles your app might
use, and any common
String values your
app might want to
look up.
Android libraries
In the wizard, you
specified the
minimum SDK
version you want your
app to be compatible
with. Android Studio
makes sure it includes
the relevant Android
libraries for this
version.
Configuration files
The configuration
files tell Android
what’s actually in the
app and how it should
run.

munotes.in

Page 18


18 Android Development Fundamental • Android Studio projects use the gradle build system to compile and deploy your apps. Gradle projects have a standard layout. Here are some of the key files and folders you’ll be working with:
1.5.1.1 The code editor Most files get displayed in the code editor. The code editor is just like a text editor, but with extra features such as color coding and code checking.

munotes.in

Page 19


19
Introduction to Android
Structure 1.5.1.2 The Design Editor • If you’re editing a layout, you have an extra option. Rather than edit the XML, you can use the design editor. • The design editor allows you to drag GUI components onto your layout, and arrange them how you want. • The code editor and design editor give different views of the same file, so you can switch back and forth between the two.
activity_main.xml xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
android:paddingBottom="16dp"
tools:context=".MainActivi ty">
munotes.in

Page 20


20 Android Development Fundamental
1.6 BASIC BUILDING BLOCKS • An android component is simply a piece of code that has a well defined life cycle e.g. Activity, Receiver, Service etc. • The core building blocks or fundamental components of android are activities, views, intents, services, content providers, fragments and AndroidManifest.xml.
munotes.in

Page 21


21
Introduction to Android
Structure 1.6.1 Activity and View • An activity is a class that represents a single screen. It is like a Frame in AWT. • A view is the UI element such as button, label, text field etc. Anything that you see is a view. 1.6.2 Intent • Intent is used to invoke components. It is mainly used to: Start the service Launch an activity Display a web page Display a list of contacts Broadcast a message Dial a phone call etc. 1. Intent intent= new Intent(Intent.ACTION_VIEW);
2. intent.setData(Uri.parse("http://www.javatpoint.com"));
3. startActivity(intent); 1.4 SERVICE • Service is a background process that can run for a long time. • There are two types of services local and remote. • Local service is accessed from within the application whereas remote service is accessed remotely from other applications running on the same device. Content Provider • Content Providers are used to share data between the applications. Fragment • Fragments are like parts of activity. An activity can display one or more fragments on the screen at the same time. AndroidManifest.xml • It contains informations about activities, content providers, permissions etc. It is like the web.xml file in Java EE. munotes.in

Page 22


22 Android Development Fundamental 1.6.4 Android Virtual Device (AVD) • It is used to test the android application without the need for mobile or tablet etc. It can be created in different configurations to emulate different types of real devices. • The Android emulator allows you to run your app on an Android virtual device (AVD). The AVD behaves just like a physical Android device. • You can set up numerous AVDs, each emulating a different type of device. Compile, package, deploy and run
• The Java source files get compiled to bytecode. • An Android application package, or APK file, gets created. • The APK file includes the compiled Java files, along with any libraries and resources needed by your app. • Assuming there’s not one already running, the emulator gets launched with the AVD. • Once the emulator has been launched and the AVD is active, the APK file is uploaded to the AVD and installed. • The AVD starts the main activity associated with the app. • Your app gets displayed on the AVD screen, and it’s all ready for you to test out. activity_main.xml has two elements Here’s the code from activity_main.xml that Android Studio generated for us.
munotes.in

Page 23


23
Introduction to Android
Structure The code contains two elements. • The first element is the element. This element tells Android to display items on the layout in relative positions. You can use , for instance, to center items in the middle of the layout, align them to the bottom of the screen on your Android device, or position them relative to other items. • The second element is the element. This element is used to display text to the user. It’s nested within the , and in our case it’s being used to display the sample text “Hello world!”. Strings.xml • strings.xml is the default resource file used to hold name/value pairs of strings so that they can be referenced throughout your app. • Android Studio created a string resource file for us called strings.xml, so let’s see if it contains a hello_world resource. Use the explorer to find it in the app/src/main/res/values folder, and open it by double-clicking on it. • Here’s what our code in the strings.xml file looks like:

My First App
Hello world!
Settings
• strings.xml includes a string with a name of hello_world, and a value of “Hello world!”. • As you can see, there’s a line of code that looks just like what we are looking for. It describes a string resource with a name of hello_ world, and a value of “Hello world!”: Hello world! • There are two things that allow Android to recognize strings.xml as being a string resource file: • The file is held in the folder app/src/main/res/values. • XML files held in this folder contain simple values, such as strings and colors. • The file has a element, which contains one or more elements. munotes.in

Page 24


24 Android Development Fundamental Activities • An activity provides the window in which the app draws its UI. This window typically fills the screen, but may be smaller than the screen and float on top of other windows. ... Typically, one activity in an app is specified as the main activity, which is the first screen to appear when the user launches the app. • Android Activity Lifecycle is controlled by 7 methods of android.app.Activity class. The android Activity is the subclass of ContextThemeWrapper class. • An activity is the single screen in android. It is like window or frame of Java. • By the help of activity, you can place all your UI components or widgets in a single screen. • The 7 lifecycle method of Activity describes how activity will behave at different states. Method Description onCreate called when activity is first creat ed. onStart called when activity is becoming visible to the user. onResume called when activity will start interacting with the
user. onPause called when activity is not visible to the user. onStop called when activity is no longer visible to the user. onRestart called after your activity is stopped, prior to start. onDestroy called before the activity is destroyed. munotes.in

Page 25


25
Introduction to Android
Structure

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="example.javatpoint.com.activitylifecycle.MainActivit
y">
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

munotes.in

Page 26


26 Android Development Fundamental import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("lifecycle","onCreate invoked");
}
@Override
protected void onStart() {
super .onStart();
Log.d("lifecycle","onStart invoked");
}
@Override
protected void onResume() {
super .onResume();
Log.d("lifecycle","onResume invoked");
}
@Override
protected void onPause() {
super .onPause();
Log.d("lifecycle","onPause invoked");
}
@Override
protected void onStop() {
super .onStop();
Log.d("lifecycle","onStop invoked");
}
@Override
protected void onRestart() {
super .onRestart();
Log.d("lifecycle","onRestart invoked");
}
@Override
protected void onDestroy() {
super .onDestroy();
Log.d("lifecycle","onDestroy invoked");
}
} munotes.in

Page 27


27
Introduction to Android
Structure 1.6.6 Android Services • A service is a component that runs in the background to perform long-running operations without needing to interact with the user and it works even if application is destroyed. • A service can essentially take two states − Sr.No. State & Description 1 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. 2 Bound
A service is bound when an application component binds
to it by calling bindService() . A bound service offe rs 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).

munotes.in

Page 28


28 Android Development Fundamental 1.6.7 Broadcast Receiver and Content Provider • Broadcast receiver is an Android component which allows you to send or receive Android system or application events. All the registered application are notified by the Android runtime once event happens. • It works similar to the publish subscribe design pattern and used for asynchronous inter-process communication. • For example, applications can register for various system events like boot complete or battery low, and Android system sends broadcast when specific event occur. Any application can also create its own custom broadcasts. Register Broadcast • There are two ways to register broadcast receiver- • Manifest-declared (Statically) : By this receiver can be registered via the AndroidManifest.xml file. • Context-registered (Dynamically) : By this register a receiver dynamically via the Context.registerReceiver() method.
Create a new instance of the LocalBroadcastManager
LocalBroadcastManager localBroadcastManager =
LocalBroadcastManager.getInstance(context); Content Provider • A content provider component supplies data from one application to others on request. Such requests are handled by the methods of the ContentResolver class.
munotes.in

Page 29


29
Introduction to Android
Structure • A content provider can use different ways to store its data and the data can be stored in a database, in files, or even over a network.
Sometimes it is required to share data across applications. This is where content providers become very useful. public class My Application extends ContentProvider { } 1.7 UI COMPONENTS • Android UI Controls are those components of Android that are used to design the UI in a more interactive way. • It helps us to develop an application that makes user interaction better with the view components. • Android provides us a huge range of UI controls of many types such as buttons, • text views, etc. • A View is an object that draws something on the screen that the user can interact with and a ViewGroup is an object that holds other View (and ViewGroup) objects in order to define the layout of the user interface.

munotes.in

Page 30


30 Android Development Fundamental 1.7.1 TextView • TextView is a UI Component that displays the text to the user on their Display Screen. • We can create it in two ways: • XML file: • For this, we declare it in the layout tag as follows: "http://schemas.android.com/apk/res/android"
//attributes to describe it
/>
Activity file: In this, we declare it using the setText() method as follows: setContentView(R.layout.activity_main);
LinearLayout linearlayout_name =
(LinearLayout)findViewById(R.id.LinearLayout);
TextView textview_name = new TextView(this);
textveiw_name.setText(“Hello I am Text View”);
linearLayout.addView(textView); Sr.No. UI Control & Description 1 TextView
This control is used to display text to the user. 2 EditText
EditText is a predefined subclass of Tex tView that includes rich
editing capabilities. 3 AutoCompleteTextView
The AutoCompleteTextView is a view that is similar to
EditText, except that it shows a list of completion suggestions
automatically while the user is typing. 4 Button
A push -button that can be pressed, or clicked, by the user to
perform an action. 5 ImageButton
An ImageButton is an AbsoluteLayout which enables you to
specify the exact location of its children. This shows a button
with an image (instead of text) that can be pressed or clicked by
the user. munotes.in

Page 31


31
Introduction to Android
Structure Sr.No. UI Control & Description 6 CheckBox
An on/off switch that can be toggled by the user. You should use
check box when presenting users with a gr oup of selectable
options that are not mutually exclusive. 7 ToggleButton
An on/off button with a light indicator. 8 RadioButton
The RadioButton has two states: either checked or unchecked. 9 RadioGroup
A RadioGroup is used to group together one or more
RadioButtons. 10 ProgressBar
The ProgressBar view provides visual feedback about some
ongoing tasks, such as when you are performing a task in the
background. 11 Spinner
A drop -down list that allows users to select one value from a set. 12 TimePicker
The TimePicker view enables users to select a time of the day,
in either 24 -hour mode or AM/PM mode. 13 DatePicker
The DatePicker view enables users to select a date of the day. 1.7.2 Notification • A notification is a message you can display to the user outside of your application's normal UI. • When you tell the system to issue a notification, it first appears as an icon in the notification area. • To see the details of the notification, the user opens the notification drawer. Both the notification area and the notification drawer are system-controlled areas that the user can view at any time • Android Toast class provides a handy way to show users alerts but problem is that these alerts are not persistent which means alert flashes on the screen for a few seconds and then disappears munotes.in

Page 32


32 Android Development Fundamental
1.8 COMPONENTS FOR COMMUNICATION –INTENTS • An intent is to perform an action on the screen. It is mostly used to start activity, send broadcast receiver,start services and send message between two activities. • There are two intents available in android as Implicit Intents and Explicit Intents. • An Intent is a messaging object you can use to request an action from another app component. Although intents facilitate communication between components in several ways, there are three fundamental use cases: Starting an activity • An Activity represents a single screen in an app. You can start a new instance of an Activity by passing an Intent to startActivity(). The Intent describes the activity to start and carries any necessary data. • If you want to receive a result from the activity when it finishes, call startActivityForResult(). Your activity receives the result as a separate Intent object in your activity's onActivityResult() callback. For more information, see the Activities guide.
munotes.in

Page 33


33
Introduction to Android
Structure Starting a service • A Service is a component that performs operations in the background without a user interface. With Android 5.0 (API level 21) and later, you can start a service with JobScheduler. For more information about JobScheduler, see its API-reference documentation. • For versions earlier than Android 5.0 (API level 21), you can start a service by using methods of the Service class. You can start a service to perform a one-time operation (such as downloading a file) by passing an Intent to startService(). The Intent describes the service to start and carries any necessary data. • If the service is designed with a client-server interface, you can bind to the service from another component by passing an Intent to bindService(). For more information, see the Services guide. Delivering a broadcast • A broadcast is a message that any app can receive. The system delivers various broadcasts for system events, such as when the system boots up or the device starts charging. You can deliver a broadcast to other apps by passing an Intent to sendBroadcast() or sendOrderedBroadcast(). Intent types • There are two types of intents: • Explicit intents specify which application will satisfy the intent, by supplying either the target app's package name or a fully-qualified component class name. • You will typically use an explicit intent to start a component in your own app, because you know the class name of the activity or service you want to start. • For example, you might start a new activity within your app in response to a user action, or start a service to download a file in the background. • Implicit intents do not name a specific component, but instead declare a general action to perform, which allows a component from another app to handle it. • For example, if you want to show the user a location on a map, you can use an implicit intent to request that another capable app show a specified location on a map. Implicit Intent Syntax Intent intent=new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://www.javatpoint.com"));
startActivity(intent); munotes.in

Page 34


34 Android Development Fundamental Explicit Intent Syntax: Intent i = new Intent(getApplicationContext(), ActivityTwo.class);
startActivity(i); 1.8.1 Intent Filters • You have seen how an Intent has been used to call an another activity. • Android OS uses filters to pinpoint the set of Activities, Services, and Broadcast receivers that can handle the Intent with help of specified set of action, categories, data scheme associated with an Intent. You will use element in the manifest file to list down actions, categories and data types associated with any activity, service, or broadcast receiver. • Following is an example of a part of AndroidManifest.xml file to specify an activity com.example.My Application.CustomActivity which can be invoked by either of the two mentioned actions, one category, and one data − android:label="@string/app_name">









1.9 ANDROID VERSIONS, NAME, AND API LEVEL • The development of the Android operating system was started in 2003 by Android, Inc. Later on, it was purchased by Google in 2005. The beta version of Android OS was released on November 5, 2007, while the software development kit (SDK) was released on November 12, 2007. • The first Android mobile was publicly released with Android 1.0 of the T-Mobile G1 (aka HTC Dream) in October 2008. munotes.in

Page 35


35
Introduction to Android
Structure Code name Version
numbers API
level Release date No codename 1.0 1 September 23, 2008 No codename 1.1 2 February 9, 2009 Cupcake 1.5 3 April 27, 2009 Donut 1.6 4 September 15, 2009 Eclair 2.0 - 2.1 5 - 7 October 26, 2009 Froyo 2.2 - 2.2.3 8 May 20, 2010 Gingerbread 2.3 - 2.3.7 9 - 10 December 6, 2010 Honeycomb 3.0 - 3.2.6 11 - 13 February 22, 2011 Ice Cream Sandwich 4.0 - 4.0.4 14 - 15 October 18, 2011 Jelly Bean 4.1 - 4.3.1 16 - 18 July 9, 2012 KitKat 4.4 - 4.4.4 19 - 20 October 31, 2013 Lollipop 5.0 - 5.1.1 21- 22 November 12, 2014 Marshmallow 6.0 - 6.0.1 23 October 5, 2015 Nougat 7.0 24 August 22, 2016 Nougat 7.1.0 - 7.1.2 25 October 4, 2016 Oreo 8.0 26 August 21, 2017 Oreo 8.1 27 December 5, 2017 Pie 9.0 28 August 6, 2018 Android 10 10.0 29 September 3, 2019 Android 11 11 30 September 8, 2020 1.10 SUMMARY • This unit has provided a brief overview of Android, and highlighted some of its capabilities. • If you have followed the sections on downloading the tools and the Android SDK, you should now have a working system — one that is capable of developing more interesting Android applications other than the Hello World application. • In the next unit, you will learn about the concepts of activities and intents, and the very important roles they play in Android 1.11 KEYWORD • SDK : Software development kit use to deploy android application. • AVD : Android Virtual Device creates virtual environment for android application. • Android Studio : is used to develop android application. • Kernel : Kernel is linux based in android. • Intent : It is used to connect activities. munotes.in

Page 36


36 Android Development Fundamental 1.12 LEARNING ACTIVITY 1. Define TextView? ____________________________________________________________ ____________________________________________________________ ____________________________________________________________ ____________________________________________________________ 2. Define Layout? ____________________________________________________________ ____________________________________________________________ ____________________________________________________________ ____________________________________________________________ 1.13 UNIT END QUESTIONS A. Descriptive Questions Short Answer 1. What is an AVD? 2. What is the difference between the android:versionCode and android:versionName attributes in the AndroidManifest.xml file? 3. What is the use of the strings.xml file? 4. What is Activity ? Draw and Explain Activity Life Cycle? Long Answer 1. Write down the steps to download and install android studio. 2. Explain any TWO UI components? 3. What is intent? Why it is used? 4. Explain the concept of notifications in Android. B. Multiple Choice Questions 1) How many sizes are supported by Android? a) Android supported all sizes b) Android does not support all sizes c) Android supports small,normal, large and extra-large sizes d) Size is undefined in android munotes.in

Page 37


37
Introduction to Android
Structure 2) How many broadcast receivers are available in android? a) sendIntent() b) onRecieve() c) implicitBroadcast() d) sendBroadcast(),sendOrderBroadcast(),and sendStickyBroadcast(). 3) What is LastKnownLocation in android? a) To find the last location of a phone b) To find known location of a phone c) To find the last known location of a phone. d) To find the last known location of user 4) How to find the JSON element length in android JSON? a) count() b) sum() c) add() d) length() 5) What is off-line synchronization in android? a) Synchronization with internet b) Background synchronization c) Synchronization without internet d) Foreground synchronization Answers 1-c, 2-d, 3-c. 4-d, 5-c 1.14 REFERENCES References book 1) “Professional Android 4 Application Development” by Reto Meier 2) “Programming Android Java Programming for the New Generation of Mobile Devices” by Zigurd Mennieks 3) “Android Cookbook” by Ian F Darwin 4) “Android Programming: The Big Nerd Ranch Guide” by Bill Phillips and Chris Stewart Textbook references 1) “Professional Android 4 Application Development” by Reto Meier munotes.in

Page 38


38 Android Development Fundamental 2) “Programming Android Java Programming for the New Generation of Mobile Devices” by Zigurd Mennieks 3) “Android Cookbook” by Ian F Darwin 4) “Android Programming: The Big Nerd Ranch Guide” by Bill Phillips and Chris Stewart Website Introduction to Android: http://developer.android.com/guide/index.html. Android API: http://developer.android.com/reference/packages.html Java 6 API: http://docs.oracle.com/javase/6/docs/api/ Android Fundamentals: http://developer.android.com/guide/components/fundamentals.html  munotes.in

Page 39

39 2 USER INPUT CONTROLS Unit Structure : 2.0 Objectives 2.1 User Input Controls 2.2 Menus 2.3 Screen Navigation 2.4 RecyclerView 2.5 Drawables 2.6 Themes and Styles 2.7 Material Design 2.8 Providing Resources for Adaptive Layouts 2.9 Summary 2.10 Exercise 2.11 Reference 2.0 OBJECTIVES After going through this chapter you will be able to 1. Know the various user controls that can be used while app development 2. Know various types of menus and drawables in Android 3. Know the difference between themes and styles 4. Know how adaptive layout work while using screen 2.1 USER INPUT CONTROLS Designing Android UI An Android Operating System (OS) interacts with users through different devices. It also communicates via an intermediary called the User Interface (UI). Through the user interface, the end user is able to see and interact with it. UI is used to navigate and utilize various components of Android OS on an Android application. They are represented to the user in the following different forms:  Graphical User Interface (GUI) allows users to interact with visual representations on digital devices or smartphones.  Voice-controlled interfaces help users to interact via voice commands such as Alexa. munotes.in

Page 40


40 Android Development Fundamental  Gesture-based interface lets users interact with the interface through body motions. Sometimes, the implementation of a weakly designed UI results in facing difficulties while interacting with the Android OS. So, the UI layout needs to be professional with effective navigation designed for users. Android UI design Android UI design includes the use of prebuilt Android UI components, such as UI controls, to create an efficient GUI for our applications. A UI screen of an Android App consists of four parts, which are as follows:  Status bar  App bar  Content area  Bottom navigation bar The Android UI components comprise different types of layouts and special interfaces such as menus, notifications, and dialogs. Android UI Controls Various types of UI controls are available in android to implement the user interface for any android application. TextView: It displays the text to the user on the display screen. It entered text can be edited. Although text editing is allowed, the basic class does not allow editing. EditText: It allows users to enter some text. It also contains certain features through which confidential data can be kept hidden. Button: It allows users to perform some action as soon as some events such as user click, double click takes place. ImageButton: ImageButton is the same as a button but it carries an image on it to perform an action. In this, we need to give the source of the image so that the system can load it. ToggleButton: It displays ON/OFF state of a button with a light indicator. RadioButton: It has two states, checked or unchecked. Users can select only one radiobutton at a time from a group. RadioGroup: A group of Radio buttons that are of similar type where only one of all the radiobuttons can be chosen. CheckBox: It has two states, checked or unchecked. Users can select multiple checkboxes at a time. ProgressBar: It shows the progress of certain action that is proceeding like copying a file from one location to other or downloading a file. munotes.in

Page 41


41
User Input Controls Two modes of progressbar:  Determinate Mode: The progress is shown in terms of percentage of action completed and estimated time to complete the action is also shown.  Indeterminate Mode: It does not show process completion time on screen and therefore it goes continuously. Spinner: It is a dropdown menu and used to select a particular choice from a list of given options. When the down arrow is clicked, a list of values are displayed on screen and it allows us a faster selection of any choice from those options. TimePicker: It helps us to select a time of the day in 12 hrs or 24 hrs format. It gives a virtual Clock or a watch to select it. DatePicker: In gives a virtual calendar or dropdown to select the day or date and a time. SeekBar: It is considered as an extension of a Progress bar. SeekBar has a draggable pointer to drag on the left or right which helps to set the progress or to choose a particular range of values. RatingBar: It is considered as an extended version of a seekbar. It allows us to give a rating by touching it. A user can rate on a scale of 5 with a difference of 0.5 and rating is done in stars. AlertDialog: It is a dialogbox that gives alert or warning to the users. Once it appears on the screen, the user needs to choose an option shown on the screen. For example, when you enter the wrong password for email id or memory full message or wrong name identified for opening a file or folder. Switch: A switch holds either an ON or OFF state. ON means Yes and OFF means No. A user can alter its state multiple times. AutoCompleteTextView: It is an extension of EditText where the user is given with a few suggestions of some values/texts and any value can be selected by the user while filling AutoCompleteTextView.

munotes.in

Page 42


42 Android Development Fundamental 2.2 MENU In android, Menu is an essential component of the User Interface that helps us in providing common functionalities around the application. Menu enhances rich user interaction experience throughout the application. To create and use a menu it needs to be define in a separate XML file and use the same in the android application. Also menu APIs can be used to represent user actions and several other options during android application activities. Types of Menus Android provides three types of Menus to define a set of options and actions in the android applications. Android Options Menu : It is a primary collection of menu items and is useful for actions used for searching in application. The options menu is usually present on the action bar where you can see several options listed in the options menu from which you can make a selection.
Android Context Menu: It is a floating menu that appears only when the user long press over an element. Context menu is useful for components that affect the selected content or context frame. It is floating menu that means its position is not fixed and usually appears just beside the element you click for a long time on an element.

munotes.in

Page 43


43
User Input Controls Android Popup Menu : A Popup menu is a list of items displayed vertically and is used to provide actions on the screen specific to related content. It presents the view that invokes the menu. Popup Menu always appears over the view and covers your view.
Menu designing in XML In android studio, Menu needs to be defined in standard XML format. This XML menu resource can be loaded as a menu object in any activity or fragment used in android application.  Right click on the res folder to create menu directory.  Navigate to New and select Android Resource Directory.  Give the name to resource directory as menu  Select Resource type as menu  One directory will be created under the res folder.  Right click on menu folder  Navigate to New and select menu resource file  Give the name to resource file as menu_example.  One menu_example.xml file will be created under menu folder.

munotes.in

Page 44


44 Android Development Fundamental android:title="@string/tea" Description

- This root element helps to define Menu in an XML file that contains multiple elements. - It contains nested elements to create a submenu and helps in creating a single item in the menu. - It is optional and invisible. It is used for elements to categorize the menu items so that they can share properties like active state, and visibility. 2.3 SCREEN NAVIGATION In Android, any activity represents a single screen. But the most of the applications have multiple activities to represent various screens, for example, one activity presents a list of the application settings, and other might displays the application status. The up navigation allows any application to move to one level up i.e. to the previous activity. To implement it, we need to first find out which activity is the appropriate parent for every activity. It can done by specifying parentActivityName attribute in an activity. android:parentActivityName = "com.example.test.MainActivity" Then, we need to call setDisplayHomeAsUpEnabled method of getActionBar() in the onCreate method of the activity which enables the back button in the top action bar. getActionBar().setDisplayHomeAsUpEnabled(true); And finally, we need to override onOptionsItemSelected method. When the user press it, activity receives a call to onOptionsItemSelected(). The ID for the action is android.R.id.home. public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: NavUtils.navigateUpFromSameTask(this); return true; } } munotes.in

Page 45


45
User Input Controls 2.4 RECYCLERVIEW The RecyclerView is a more flexible widget and an enhanced version of GridView and ListView. It is a container for big datasets that can be easily scrolled by restricting on a limited number of views. Also, this widget can be used while using dynamic data collections means collections where elements change runtime depending on network events or user actions. Implementation of RecyclerView 1. Plan how the list or grid is going to appear 2. We can use any of the RecyclerView library's standard layout managers. 3. Design the appearance of each element of the list according to how it is going to look and behave. 4. Based on this design, extend the ViewHolder class. 5. This ViewHolder class will provide the functionalities for list items. 6. ViewHolder is a wrapper around a View that is managed by RecyclerView. 7. Adapter is defined to associate data with the ViewHolder views. 8. Three sub parts need to be constructed to implement a basic RecyclerView. Following are these sub parts that offers users the degree of control they require while making various designs of their choice. The Card Layout: It is an XML layout treated as an item for the list created by RecyclerView. The ViewHolder: This class holds the reference to the card layout view that have to be modified dynamically during the program execution by a list of data obtained through either online databases or any other way. The Data Class: This class acts as a structure for storing the information for every item of the RecyclerView. 2.5 DRAWABLES A Drawable resource is a concept in android used for a graphic that can be drawn on the screen. It can retrieved with APIs like getDrawable() or apply to another XML resource with attributes such as android:drawable and android:icon. Example :- Graphical file can be represented via a BitmapDrawable class. Each Drawable is kept as individual files in res/drawable folders. Bitmaps can be stored in the form of following resolutions :- -mdpi, -hdpi, -xhdpi, -xxhdpi. These are subfolders of res/drawable and created by default while creating a project in android studio. munotes.in

Page 46


46 Android Development Fundamental Android system selects the correct bitmap automatically even if these bitmaps are provided in various folders based on the device configuration. In case bitmaps are not provided for all supported resolutions, an Android system balances the closest fit up or down that is typically undesired as the bitmap might get blurred. There are several types of drawable resource files as follows: 1. Shape Drawables Shape Drawables are XML files that allow us to define a geometric object with borders, colors, and gradients which can be assigned to Views. The advantage of using it is that they automatically adjust to the correct size. 2. State Drawables State drawables allow us to define various states. For each state, a drawable can be assigned to the View. The following example defines an assigned drawable for a button depending on its state. munotes.in

Page 47


47
User Input Controls 3. Transition Drawables Transition Drawables define transitions that can be triggered in the coding. 5. Vector drawables Vector drawables are similar to svg files but it has a limited scope. Vector drawables automatically fit to the density of any device. Android supports animated vector drawables by using the AnimatedVectorDrawable class. It allows users to combine vector drawables and animations. Vector drawables create and morph various images. We can start and stop this morphing via code but controlling or halting the animation at a particular frame is not possible. 6. Animation Drawables Users can also define animation drawables and assign it to a View via the setBackgroundResource() method. munotes.in

Page 48


48 Android Development Fundamental 7. 9 Patch Drawables 9 Patch drawables have a one-pixel additional border. From the top and left we can define the area which can be scaled if the Drawable is very small for the view. It is the stretch area. On the right and bottom sides also we can define the area where a text could be placed. 8. Custom Drawables Users can also create custom Drawable, which can use the Canvas API for their display to design them as per the user’s need. 2.6 THEMES AND STYLES Style is a set of attributes in android that can be applied to view elements. Styles has various parameters like font, color, background, margin, text size, text style, etc. Using these properties, we can define our own style and apply it to a UI component or to the entire layout. Themes are a standardized type of style followed throughout the application. View, non-view elements or layout follows the same theme throughout. When the theme is applied, every view applies each of the theme's attributes that it supports. Defining Styles A style is defined in an XML resource under res/values/directory of your project and will have as the root node which is mandatory for the style file. We can define as many styles as we want using