What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and...

108
1 Contents: What is Android? Why develop apps for Android? Android versions The challenges of Android app development. What is Android? Android is an operating system and programming platform developed by Google for smartphones and other mobile devices (such as tablets). It can run on many different devices from many different manufacturers. Android includes a software development kit for writing original code and assembling software modules to create apps for Android users. It also provides a marketplace to distribute apps. All together, Android represents an ecosystem for mobile apps. Why develop apps for Android? Apps are developed for a variety of reasons: addressing business requirements, building new services, creating new businesses, and providing games and other types of content for users. Developers choose to develop for Android in order to reach the majority of mobile device users. Most popular platform for mobile apps As the world's most popular mobile platform, Android powers hundreds of millions of mobile devices in more than 190 countries around the world. It has the largest installed base of any mobile platform and is still growing fast. Every day another million users power up their Android devices for the first time and start looking for apps, games, and other digital content. Exp.No : 1 Introduction to Android Date :

Transcript of What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and...

Page 1: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

1

Contents: What is Android? Why develop apps for Android? Android versions The challenges of Android app development.

What is Android?Android is an operating system and programming platform developed by Google forsmartphones and other mobile devices (such as tablets). It can run on many different devicesfrom many different manufacturers. Android includes a software development kit for writingoriginal code and assembling software modules to create apps for Android users. It alsoprovides a marketplace to distribute apps. All together, Android represents an ecosystem formobile apps.

Why develop apps for Android?Apps are developed for a variety of reasons: addressing business requirements, building newservices, creating new businesses, and providing games and other types of content for users.Developers choose to develop for Android in order to reach the majority of mobile device users.Most popular platform for mobile appsAs the world's most popular mobile platform, Android powers hundreds of millions of mobiledevices in more than 190 countries around the world. It has the largest installed base of anymobile platform and is still growing fast. Every day another million users power up theirAndroid devices for the first time and start looking for apps, games, and other digital content.

Exp.No : 1Introduction to Android

Date :

Page 2: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

2

Best experience for app users

Android provides a touch-screen user interface (UI) for interacting with apps. Android's userinterface is mainly based on direct manipulation, using touch gestures such as swiping, tappingand pinching to manipulate on-screen objects. In addition to the keyboard, there’s acustomizable virtual keyboard for text input. Android can also support game controllers andfull-size physical keyboards connected by Bluetooth or USB.

The Android home screen can contain several pages of app icons, which launch the associatedapps, and widgets, which display live, auto-updating content such as the weather, the user'semail inbox or a news ticker. Android can also play multimedia content such as music,animation, and video. The figure above shows app icons on the home screen (left), playingmusic (center), and displaying widgets (right). Along the top of the screen is a status bar,showing information about the device and its connectivity. The Android home screen may bemade up of several pages, between which the user can swipe back and forth.Android is designed to provide immediate response to user input. Besides a fluid touchinterface, the vibration capabilities of an Android device can provide haptic feedback. Internalhardware such as accelerometers, gyroscopes and proximity sensors, are used by many apps torespond to additional user actions. These sensors can detect rotation of the screen fromportrait to landscape for a wider view or it can allow the user to steer a virtual vehicle in aracing game by rotating the device as if it were a steering wheel.

The Android platform, based on the Linux kernel, is designed primarily for touchscreen mobiledevices such as smartphones and tablets. Since Android devices are usually battery-powered,Android is designed to manage processes to keep power consumption at a minimum, providinglonger battery use.

Easy to develop appsUse the Android software development kit (SDK) to develop apps that take advantage of theAndroid operating system and UI. The SDK includes a comprehensive set of development toolsincluding a debugger, software libraries of prewritten code, a device emulator, documentation,sample code, and tutorials. Use these tools to create apps that look great and take advantageof the hardware capabilities available on each device.

Page 3: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

3

To develop apps using the SDK, use the Java programming language for developing the app andExtensible Markup Language (XML) files for describing data resources. By writing the code inJava and creating a single app binary, you will have an app that can run on both phone andtablet form factors. You can declare your UI in lightweight sets of XML resources, one set forparts of the UI that are common to all form factors and other sets for features specific tophones or tablets. At runtime, Android applies the correct resource sets based on its screensize, density, locale, and so on.

To help you develop your apps efficiently, Google offers a full Java Integrated DevelopmentEnvironment (IDE) called Android Studio, with advanced features for developing, debugging,and packaging Android apps. Using Android Studio, you can develop on any available Androiddevice, or create virtual devices that emulate any hardware configuration.

Android provides rich development architecture. You don’t need to know much about thecomponents of this architecture, but it is useful to know what is available in the system for yourapp to use. The following diagram shows the major components of the Android stack — theoperating system and development architecture.

In the figure above:

1. Apps: Your apps live at this level, along with core system apps for email, SMS messaging,calendars, Internet browsing, or contacts.

2. Java API Framework: All features of Android are available to developers throughapplication programming interfaces (APIs) written in the Java language. You don't needto know the details of all of the APIs to learn how to develop Android apps, but you canlearn more about the following APIs, which are useful for creating apps: View System used to build an app's UI, including lists, buttons, and menus.

Resource Manager used to access to non-code resources such as localized strings,graphics, and layout files.

Notification Manager used to display custom alerts in the status bar.

Page 4: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

4

Activity Manager that manages the lifecycle of apps.

Content Providers that enable apps to access data from other apps.

All framework APIs that Android system apps use.

3. Libraries and Android Runtime: Each app runs in its own process and with its owninstance of the Android Runtime, which enables multiple virtual machines on low-memory devices. Android also includes a set of core runtime libraries that provide mostof the functionality of the Java programming language, including some Java 8 languagefeatures that the Java API framework uses. Many core Android system components andservices are built from native code that requires native libraries written in C and C++.These native libraries are available to apps through the Java API framework.

4. Hardware Abstraction Layer (HAL): This layer provides standard interfaces that exposedevice hardware capabilities to the higher-level Java API framework. The HAL consists ofmultiple library modules, each of which implements an interface for a specific type ofhardware component, such as the camera or bluetooth module.

5. Linux Kernel: The foundation of the Android platform is the Linux kernel. The abovelayers rely on the Linux kernel for underlying functionalities such as threading and low-level memory management. Using a Linux kernel enables Android to take advantage ofkey security features and allows device manufacturers to develop hardware drivers for awell-known kernel.

Many distribution options

You can distribute your Android app in many different ways: email, website or an appmarketplace such as Google Play. Android users download billions of apps and games from theGoogle Play store each month (shown in the figure below). Google Play is a digital distributionservice, operated and developed by Google that serves as the official appstore for Android,allowing consumers to browse and download apps developed with the Android SDK andpublished through Google.

Page 5: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

5

Android versions

Google provides major incremental upgrades to the Android operating system every six to ninemonths, using confectionery-themed names. The latest major release is Android 7.0 "Nougat".

Page 6: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

6

See previous versions and their features at The Android Story.

The Dashboard for Platform Versions is updated regularly to show the distribution of activedevices running each version of Android, based on the number of devices that visit the GooglePlay Store. It's a good practice to support about 90% of the active devices, while targeting yourapp to the latest version.

Note: To provide the best features and functionality across Android versions, use the AndroidSupport Library in your app. This support library allows your app to use recent platform APIs onolder devices.

The challenges of Android app developmentWhile the Android platform provides rich functionality for app development, there are still anumber of challenges you need to address, such as:

Building for a multi-screen world Getting performance right Keeping your code and your users secure Remaining compatible with older platform versions

Page 7: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

7

Understanding the market and the user.

Building for a multi-screen world

Android runs on billions of handheld devices around the world, and supports various formfactors including wearable devices and televisions. Devices can come in different sizes andshapes that affect the screen designs for UI elements in your apps.

In addition, device manufacturers may add their own UI elements, styles, and colors todifferentiate their products. Each manufacturer offers different features with respect tokeyboard forms, screen size, or camera buttons. An app running on one device may look a bitdifferent on another. The challenge for many developers is to design UI elements that can workon all devices. It is also the developer’s responsibility to provide an app’s resources such asicons, logos, other graphics, and text styles to maintain uniformity of appearance acrossdifferent devices.

Maximizing app performanceAn app's performance—how fast it runs, how easily it connects to the network, and how well itmanages battery and memory usage—is affected by factors such as battery life, multimediacontent, and Internet access. You must be aware of these limitations and write code in such away that the resource utilization is balanced and distributed optimally. For example, you willhave to balance the background services by enabling them only when necessary; this will savebattery life of the user’s device.

Keeping your code and your users secureYou need to take precautions to secure your code and the user’s experience when using yourapp. Use tools such as ProGuard (provided in Android Studio), which detects and removesunused classes, fields, methods, and attributes, and encrypt all of your app's code andresources while packaging the app. To protect your user's critical information such as logins andpasswords, you must secure the communication channel to protect data in transit (across theInternet) as well as data at rest (on the device).

Remaining compatible with older platform versionsConsider how to add new Android platform version features to an app, while ensuring that theapp can still run on devices with older platform versions. It is impractical to focus only on the

Page 8: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

8

most recent Android version, as not all users may have upgraded or may be able to upgradetheir devices.

Create Your First Android App

Contents: The development process Using Android Studio Exploring a project Viewing and editing Java code Viewing and editing layouts Understanding the build process Running the app on an emulator or a device Using the log

The development processAn Android app project begins with an idea and a definition of the requirements necessary torealize that idea. As the project progresses, it goes through design, development, and testing.

The above diagram is a high-level picture of the development process, with the following steps: Defining the idea and its requirements: Most apps start with an idea of what it should

do, bolstered by market and user research. During this stage the app's requirements aredefined.

Prototyping the user interface: Use drawings, mock ups and prototypes to show whatthe user interface would look like, and how it would work.

Developing and testing the app: An app consists of one or more activities. For eachactivity you can use Android Studio to do the following, in no particular order:

Create the layout: Place UI elements on the screen in a layout, and assign stringresources and menu items, using the Extensible Markup Language (XML).

Write the Java code: Create source code for components and tests, and use testing anddebugging tools.

Register the activity: Declare the activity in the manifest file.

Page 9: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

9

Define the build: Use the default build configuration or create custom builds fordifferent versions of your app.

Publishing the app: Assemble the final APK (package file) and distribute it throughchannels such as the Google Play.

Using Android StudioAndroid Studio provides tools for the testing, and publishing phases of the developmentprocess, and a unified development environment for creating apps for all Android devices. Thedevelopment environment includes code templates with sample code for common appfeatures, extensive testing tools and frameworks, and a flexible build system.

Starting an Android Studio projectAfter you have successfully installed the Android Studio IDE, double-click the Android Studioapplication icon to start it. Choose Start a new Android Studio project in the Welcomewindow, and name the project the same name that you want to use for the app.When choosing a unique Company Domain, keep in mind that apps published to the GooglePlay must have a unique package name. Since domains are unique, prepending the app's namewith your name, or your company's domain name, should provide an adequately uniquepackage name. If you are not planning to publish the app, you can accept the default exampledomain. Be aware that changing the package name later is extra work.

Choosing target devices and the minimum SDKWhen choosing Target Android Devices, Phone and Tablet are selected by default, as shown inthe figure below. The choice shown in the figure for the Minimum SDK — API 15: Android4.0.3 (IceCreamSandwich) — makes your app compatible with 97% of Android devices activeon the Google Play Store.

Page 10: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

10

Different devices run different versions of the Android system, such as Android 4.0.3 or Android4.4. Each successive version often adds new APIs not available in the previous version. Toindicate which set of APIs are available, each version specifies an API level. For instance,Android 1.0 is API level 1 and Android 4.0.3 is API level 15.The Minimum SDK declares the minimum Android version for your app. Each successive versionof Android provides compatibility for apps that were built using the APIs from previousversions, so your app should always be compatible with future versions of Android while usingthe documented Android APIs.

Choosing a templateAndroid Studio pre-populates your project with minimal code for an activity and a screen layoutbased on a template. A variety of templates are available, ranging from a virtually blanktemplate (Add No Activity) to various types of activities.You can customize the activity after choosing your template. For example, the Empty Activitytemplate provides a single activity accompanied by a single layout resource for the screen. Youcan choose to accept the commonly used name for the activity (such as MainActivity) orchange the name on the Customize the Activity screen. Also, if you use the Empty Activitytemplate, be sure to check the following if they are not already checked:

Generate Layout file: Leave this checked to create the layout resource connected to thisactivity, which is usually named activity_main.xml. The layout defines the userinterface for the activity.

Backwards Compatibility (AppCompat): Leave this checked to include the AppCompatlibrary so that the app is compatible with previous versions of Android even if it usesfeatures found only in newer versions.

Android Studio creates a folder for the newly created project in the AndroidStudioProjectsfolder on your computer.

Android Studio window panesThe Android Studio main window is made up of several logical areas, or panes, as shown in thefigure below.

Page 11: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

11

In the above figure:

1. The Toolbar.The toolbar carries out a wide range of actions, including running theAndroid app and launching Android tools.

2. The Navigation Bar. The navigation bar allows navigation through the project and openfiles for editing. It provides a more compact view of the project structure.

3. The Editor Pane. This pane shows the contents of a selected file in the project. Forexample, after selecting a layout (as shown in the figure), this pane shows the layouteditor with tools to edit the layout. After selecting a Java code file, this pane shows thecode with tools for editing the code.

4. The Status Bar. The status bar displays the status of the project and Android Studioitself, as well as any warnings or messages. You can watch the build progress in thestatus bar.

5. The Project Pane. The project pane shows the project files and project hierarchy.6. The Monitor Pane. The monitor pane offers access to the TODO list for managing tasks,

the Android Monitor for monitoring app execution (shown in the figure), the logcat forviewing log messages, and the Terminal application for performing Terminal activities.

Tip: You can organize the main window to give yourself more screen space by hiding or movingpanes. You can also use keyboard shortcuts to access most features.

Exploring a project

Each project in Android Studio contains the AndroidManifest.xml file, component source-codefiles, and associated resource files. By default, Android Studio organizes your project files basedon the file type, and displays them within the Project: Android view in the left tool pane, asshown below. The view provides quick access to your project's key files.

To switch back to this view from another view, click the vertical Project tab in the far leftcolumn of the Project pane, and choose Android from the pop-up menu at the top of theProject pane, as shown in the figure below.

Page 12: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

12

In the figure above: The Project tab. Click to show the project view. The Android selection in the project drop-down menu. The AndroidManifest.xml file. Used for specifying information about the app for the

Android runtime environment. The template you choose creates this file. The java folder. This folder includes activities, tests, and other components in Java

source code. Every activity, service, and other component is defined as a Java class,usually in its own file. The name of the first activity (screen) the user sees, which alsoinitializes app-wide resources, is customarily MainActivity.

The res folder. This folder holds resources, such as XML layouts, UI strings, and images.An activity usually is associated with an XML resource file that specifies the layout of itsviews. This file is usually named after its activity or function.

The build.gradle (Module: App) file. This file specifies the module's build configuration.The template you choose creates this file, which defines the build configuration,including the minSdkVersion attribute that declares the minimum version for the app,and the targetSdkVersionattribute that declares the highest (newest) version for whichthe app has been optimized. This file also includes a list of dependencies, which arelibraries required by the code — such as the AppCompat library for supporting a widerange of Android versions.

Viewing the Android ManifestBefore the Android system can start an app component, the system must know that thecomponent exists by reading the app's AndroidManifest.xml file. The app must declare all itscomponents in this file, which must be at the root of the app project directory.To view this file, expand the manifests folder in the Project: Android view, and double-click thefile (AndroidManifest.xml). Its contents appear in the editing pane as shown in the figurebelow.

Android namespace and application tag

The Android Manifest is coded in XML and always uses the Android namespace:

Page 13: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

13

xmlns:android="http://schemas.android.com/apk/res/android"package="com.example.android.helloworld">

The package expression shows the unique package name of the new app. Do not change thisonce the app is published.

<application...</application>

The <application tag, with its closing </application> tag, defines the manifest settings for theentire app.

Automatic backupThe android: allowBackup attribute enables automatic app data backup:

...

android:allowBackup="true"

...

Setting the android:allowBackup attribute to true enables the app to be backed upautomatically and restored as needed. Users invest time and effort to configure apps. Switchingto a new device can cancel out all that careful configuration. The system performs thisautomatic backup for nearly all app data by default, and does so without the developer havingto write any additional app code.

For apps whose target SDK version is Android 6.0 (API level 23) and higher, devices runningAndroid 6.0 and higher automatically create backups of app data to the cloud because theandroid:allowBackup attribute defaults to true if omitted. For apps < API level 22 you have toexplicitly add the android:allowBackup attribute and set it to true .

The app icon

The android: icon attribute sets the icon for the app:...

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

Page 14: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

14

...

The android: icon attribute assigns an icon in the mipmap folder (inside the res folder inProject: Android view) to the app.

The icon appears in the Launcher for launching the app. The icon is also used as the default iconfor app components.

App label and string resources

As you can see in the previous figure, the android:label attribute shows the string "Hello World"highlighted. If you click on this string, it changes to show the string resource @string/app_name:

...

android:label="@string/app_name"

...

Tip: Ctrl-click or right-click app_name in the edit pane to see the context menu. Choose Go To >Declaration to see where the string resource is declared: in the strings.xml file. When youchoose Go To > Declaration or open the file by double-clicking strings.xml in the Project:Android view (inside the values folder), its contents appear in the editing pane.

After opening the strings.xml file, you can see that the string name app_name is set to HelloWorld. You can change the app name by changing the Hello World string to something else.String resources are described in a separate lesson.

The app theme

The android: theme attribute sets the app's theme, which defines the appearance of userinterface elements such as text:

...

android:theme="@style/AppTheme">

...

Page 15: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

15

The theme attribute is set to the standard theme AppTheme . Themes are described in aseparate lesson.

Declaring the Android version

Different devices may run different versions of the Android system, such as Android 4.0 orAndroid 4.4. Each successive version can add new APIs not available in the previous version. Toindicate which set of APIs are available, each version specifies an API level. For instance,Android 1.0 is API level 1 and Android 4.4 is API level 19.

The API level allows a developer to declare the minimum version with which the app iscompatible, using the <uses-sdk> manifest tag and its minSdkVersion attribute. For example,the Calendar Provider APIs were added in Android 4.0 (API level 14). If your app can't functionwithout these APIs, declare API level 14 as the app's minimum supported version like this:

<manifest ... >

<uses-sdk android:minSdkVersion="14" android:targetSdkVersion="19" />

...

</manifest>

The minSdkVersion attribute declares the minimum version for the app, and thetargetSdkVersion attribute declares the highest (newest) version which has been optimizedwithin the app. Each successive version of Android provides compatibility for apps that werebuilt using the APIs from previous versions, so the app should always be compatible with futureversions of Android while using the documented Android APIs.

The targetSdkVersion attribute does not prevent an app from being installed on Androidversions that are higher (newer) than the specified value, but it is important because itindicates to the system whether the app should inherit behavior changes in newer versions. Ifyou don't update the targetSdkVersion to the latest version, the system assumes that your apprequires some backward-compatibility behaviors when running on the latest version. Forexample, among the behavior changes in Android 4.4, alarms created with the AlarmManagerAPIs are now inexact by default so that the system can batch app alarms and preserve systempower, but the system will retain the previous API behavior for an app if your target API level islower than "19" .

Page 16: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

16

Viewing and editing Java code

Components are written in Java and listed within module folders in the java folder in theProject: Android view. Each module name begins with the domain name (such ascom.example.android) and includes the app name.

The following example shows an activity component:

1. Click the module folder to expand it and show the MainActivity file for the activitywritten in Java (the MainActivity class).

2. Double-click MainActivity to see the source file in the editing pane, as shown in thefigure below.

At the very top of the MainActivity.java file is a package statement that defines the apppackage. This is followed by an import block condensed in the above figure, with " ... ". Click thedots to expand the block to view it. The import statements import libraries needed for the app,such as the following, which imports the AppCompatActivity library:

import android.support.v7.app.AppCompatActivity;

Each activity in an app is implemented as a Java class. The following class declaration extendsthe AppCompatActivity class to implement features in a way that is backward-compatible withprevious versions of Android:

public class MainActivity extends AppCompatActivity {

...

}As you learned earlier, before the Android system can start an app component such as anactivity, the system must know that the activity exists by reading the app'sAndroidManifest.xml file. Therefore, each activity must be listed in the AndroidManifest.xmlfile.

Viewing and editing layouts Layout resources are written in XML and listed within the layoutfolder in the res folder in the Project: Android view. Click res > layout and then double-clickactivity_main.xml to see the layout file in the editing pane.

Page 17: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

17

Android Studio shows the Design view of the layout, as shown in the figure below. This viewprovides a Palette pane of user interface elements, and a grid showing the screen layout.

Understanding the build process

The Android application package (APK) is the package file format for distributing and installingAndroid mobile apps. The build process involves tools and processes that automatically converteach project into an APK.

Android Studio uses Gradle as the foundation of the build system, with more Android-specificcapabilities provided by the Android Plugin for Gradle. This build system runs as an integratedtool from the Android Studio menu.

Understanding build.gradle files

When you create a project, Android Studio automatically generates the necessary build files inthe Gradle Scripts folder in

Project: Android view. Android Studio build files are named build.gradle as shown below:

Page 18: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

18

Each project has the following:

build.gradle (Project: apptitle)This is the top-level build file for the entire project, located in the root project directory,which defines build configurations that apply to all modules in your project. This file,generated by Android Studio, should not be edited to include app dependencies.build.gradle (Module: app)

Android Studio creates separate build.gradle (Module: app) files for each module. You canedit the build settings to provide custom packaging options for each module, such asadditional build types and product flavors, and to override settings in the manifest or top-level build.gradle file. This file is most often the file to edit when changing app-levelconfigurations, such as declaring dependencies in the dependencies section. The followingshows the contents of a project's build.gradle (Module: app) file:

apply plugin: 'com.android.application'

android {compileSdkVersion 24buildToolsVersion "24.0.1"defaultConfig {

applicationId "com.example.android.helloworld2"minSdkVersion 15targetSdkVersion 24versionCode 1versionName "1.0"testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

}buildTypes {

release {minifyEnabled falseproguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

}}

}

dependencies {compile fileTree(dir: 'libs', include: ['*.jar'])androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {

exclude group: 'com.android.support', module: 'support-annotations'})compile 'com.android.support:appcompat-v7:24.2.1'testCompile 'junit:junit:4.12'

}The build.gradle files use Gradle syntax. Gradle is a Domain Specific Language (DSL) fordescribing and manipulating the build logic using Groovy, which is a dynamic language for the

Page 19: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

19

Java Virtual Machine (JVM). You don't need to learn Groovy to make changes, because theAndroid Plugin for Gradle introduces most of the DSL elements you need.

Plugin and Android blocks

In the above build.gradle (Module: app) file, the first statement applies the Android-specificGradle plug-in build tasks:apply plugin: 'com.android.application'

android {...

}The android { } block specifies the following for the build:The target SDK version for compiling the code:compileSdkVersion 24The version of the build tools to use for building the app:buildToolsVersion "24.0.1"

The defaultConfig block

Core settings and entries for the app are specified in a defaultConfig { } block withinthe android { } block:

...defaultConfig {

applicationId "com.example.hello.helloworld"minSdkVersion 15targetSdkVersion 23versionCode 1versionName "1.0"

testInstrumentationRunner"android.support.test.runner.AndroidJUnitRunner"

}...

The minSdkVersion and targetSdkVersion settings override any AndroidManifest.xml settingsfor the minimum SDK version and the target SDK version. See "Declaring the Android version"previously in this chapter for background information on these settings.The testInstrumentationRunner statement adds the instrumentation support for testing theuser interface with Espresso and UIAutomator. These are described in a separate lesson.

Build typesBuild types for the app are specified in a buildTypes { } block, which controls how the app isbuilt and packaged....

Page 20: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

20

buildTypes {release {

minifyEnabled falseproguardFiles getDefaultProguardFile('proguard-android.txt'),

'proguard-rules.pro'}

}...The build type specified is release for the app's release. Another common build type is debug.Configuring build types is described in a separate lesson.

DependenciesDependencies for the app are defined in the dependencies { } block, which is the part of thebuild.gradle file that is most likely to change as you start developing code that depends onother libraries. The block is part of the standard Gradle API and belongs outside the android {} block....dependencies {

compile fileTree(dir: 'libs', include: ['*.jar'])androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {

exclude group: 'com.android.support', module: 'support-annotations'})compile 'com.android.support:appcompat-v7:24.2.0'testCompile 'junit:junit:4.12'

}In the above snippet, the statement compile fileTree(dir: 'libs', include: ['*.jar']) adds adependency of all ".jar" files inside the libs directory. The compile configuration compiles themain application — everything in it is added to the compilation classpath, and also packagedinto the final APK.

Syncing your projectWhen you make changes to the build configuration files in a project, Android Studio requiresthat you sync the project files so that it can import the build configuration changes and runsome checks to make sure the configuration won't create build errors.To sync the project files, click Sync Now in the notification bar that appears when making achange, or click Sync Project from the menu bar. If Android Studio notices any errors with theconfiguration — for example, if the source code uses API features that are only available in anAPI level higher than the compileSdkVersion — the Messages window appears to describe theissue.

Page 21: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

21

Running the app on an emulator or a deviceWith virtual device emulators, you can test an app on different devices such as tablets orsmartphones — with different API levels for different Android versions — to make sure it looksgood and works for most users. Although it's a good idea, you don't have to depend on having aphysical device available for app development.The Android Virtual Device (AVD) manager creates a virtual device or emulator that simulatesthe configuration for a particular type of Android device. Use the AVD Manager to define thehardware characteristics of a device and its API level, and to save it as a virtual deviceconfiguration. When you start the Android emulator, it reads a specified configuration andcreates an emulated device on your computer that behaves exactly like a physical version ofthat device.

Creating a virtual device

To run an emulator on your computer, use the AVD Manager to create a configuration thatdescribes the virtual device. Select Tools > Android > AVD Manager, or click the AVD Manager

icon in the toolbar.The "Your Virtual Devices" screen appears showing all of the virtual devices created previously.Click the +Create Virtual Device button to create a new virtual device.

You can select a device from a list of predefined hardware devices. For each device, the tableshows its diagonal display size (Size), screen resolution in pixels (Resolution), and pixel density(Density). For example, the pixel density of the Nexus 5 device is xxhdpi, which means the appuses the icons in the xxhdpi folder of the mipmap folder. Likewise, the app will use layouts anddrawables from folders defined for that density as Well.

Page 22: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

22

You also choose the version of the Android system for the device. The Recommended tab shows therecommended systems for the device. More versions are available under the x86 Images and OtherImages tabs.

Running the app on the virtual deviceTo run the app on the virtual device you created in the previous section, follow these steps:

In Android Studio, select Run > Run app or click the Run icon in the toolbar. In the Select Deployment Target window, under Available Emulators, select the virtual device

you created, and click OK.The emulator starts and boots just like a physical device. Depending on the speed of your computer, thismay take a while. The app builds, and once the emulator is ready, Android Studio uploads the app to theemulator and runs it.You should see the app created from the Empty Activity template ("Hello World") as shown in thefollowing figure, which also shows Android Studio's Run pane that displays the actions performed to runthe app on the emulator.Note: When testing on an emulator, it is good practice to start it up once at the very beginning of yoursession, and not to close it until done so that it doesn't have to go through the boot process again.

In the above figure:

Page 23: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

23

The Emulator running the app. The Run Pane. This shows the actions taken to install and run the app.

Running the app on a physical device

Always test your apps on physical device, because users will use the app on physical devices.While emulators are quite good, they can't show all possible device states, such as whathappens if an incoming call occurs while the app is running. To run the app on a physical device,you need the following:

An Android device such as a smartphone or tablet. A data cable to connect the Android device to your computer via the USB port. If you are using Linux or Windows, it may be necessary to perform additional steps to

run the app on a hardware device. Check the Using Hardware Devices documentation.On Windows, you may need to install the appropriate USB driver for the device.See OEM USB Drivers.

To let Android Studio communicate with a device, turn on USB Debugging on the Androiddevice. On Android version 4.2 and newer, the Developer options screen is hidden by default.Follow these steps to turn on USB Debugging:

1. On the physical device, open Settings and choose About phone at the bottom of theSettings screen.

2. Tap the Build number information seven times.3. You read that correctly: Tap it seven times.4. Return to the previous screen (Settings). Developer options now appear at the bottom

of the screen. Tap Developer options.5. Choose USB Debugging.

Now, connect the device and run the app from Android Studio.

Troubleshooting the device connection

If Android Studio does not recognize the device, try the following:1. Disconnect the device from your computer, and then reconnect it.2. Restart Android Studio.3. If your computer still does not find the device or declares it "unauthorized":

a. Disconnect the device from your computer.b. On the device, choose Settings > Developer Options.c. Tap Revoke USB Debugging authorizations.d. Reconnect the device to your computer.e. When prompted, grant authorizations.

4. You may need to install the appropriate USB driver for the device. See Using HardwareDevices documentation.

5. Check the latest documentation, programming forums, or get help from yourinstructors.

Page 24: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

24

Using the log

The log is a powerful debugging tool you can use to look at values, execution paths, andexceptions. After you add logging statements to an app, your log messages appear along withgeneral log messages in the logcat tab of the Android Monitor pane of Android Studio.

To see the Android Monitor pane, click the Android Monitor button at the bottom of theAndroid Studio main window. The Android Monitor offers two tabs:

1. The logcat tab. The logcat tab displays log messages about the app as it is running. If youadd logging statements to the app, your log messages from these statements appearwith the other log messages under this tab.

2. The Monitors tab. The Monitors tab monitors the performance of the app, which can behelpful for debugging and tuning your code.

Adding logging statements to your appLogging statements add whatever messages you specify to the log. Adding logging statementsat certain points in the code allows the developer to look at values, execution paths, andexceptions.For example, the following logging statement adds "MainActivity" and "Hello World" to thelog:Log.d("MainActivity", "Hello World");

The following are the elements of this statement: Log: The Log class is the API for sending log messages. d: You assign a log level so that you can filter the log messages using the drop-down menu in the

center of the logcat tab pane. The following are log levels you can assign:o d: Choose Debug or Verbose to see these messages.o e: Choose Error or Verbose to see these messages.o w: Choose Warning or Verbose to see these messages.o i: Choose Info or Verbose to see these messages.

"MainActivity": The first argument is a log tag which can be used to filter messages underthe logcat tab. This is commonly the name of the activity from which the message originates.However, you can make this anything that is useful to you for debugging the app. The bestpractice is to use a constant as a log tag, as follows:

1. Define the log tag as a constant before using it in logging statement:private static final String LOG_TAG =MainActivity.class.getSimpleName();

2. Use the constant in the logging statements:Log.d(LOG_TAG, "Hello World");

3. "Hello World": The second argument is the actual message that appears after thelog level and log tag under the logcat tab.

Viewing your log messagesThe Run pane appears in place of the Android Monitor pane when you run the app on anemulator or a device. After starting to run the app, click the Android Monitor button at the

Page 25: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

25

bottom of the main window, and then click the logcat tab in the Android Monitor pane if it isnot already selected.

In the above figure: The logging statement in the onCreate() method of MainActivity. Android Monitor pane showing logcat log messages, including the message from the

logging statement.

By default, the log display is set to Verbose in the drop-down menu at the top ofthe logcat display to show all messages. You can change this to Debug to see messages thatstart with Log.d, or change it to Error to see messages that start with Log.e, and so on.

Page 26: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

26

Exp.No:2DEVELOP AN APPLICATION THAT USES GUI COMPONENTS,

FONT AND COLORSDate:

Aim:

To develop a Simple Android Application that uses GUI components, Font and Colors.

Algorithm:

Start the program. Creating a New project:

a. Open Android Studio and then click on File -> New -> New project.

b. Then type the Application name and click Next.

c. Then select the Minimum SDK as shown below and click Next.

Page 27: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

27

d. Then select the Empty Activity and click Next.

e. Finally click Finish.

Page 28: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

28

f. It will take some time to build and load the project.g. After completion it will look as given below.

Designing layout for the Android Application.

Click on app -> res -> layout -> activity_main.xml

Now click on Text as shown below.

Then delete the code which is there and type the code as given below

Page 29: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

29

Code for Activity_main.xml:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:orientation="vertical"android:layout_width="match_parent"android:layout_height="match_parent"><TextView

android:id="@+id/textView"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_margin="30dp"android:gravity="center"android:text="Hello World!"android:textSize="25sp"android:textStyle="bold" />

<Buttonandroid:id="@+id/button1"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_margin="20dp"android:gravity="center"android:text="Change font size"android:textSize="25sp" />

<Buttonandroid:id="@+id/button2"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_margin="20dp"android:gravity="center"android:text="Change color"android:textSize="25sp" />

</LinearLayout> So now the designing part is completed

Java Coding for the Android Application:

Click on app -> java -> com.example.exno1 -> MainActivity.

Page 30: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

30

Code for MainActivity.java:

package com.example.exno1;import android.graphics.Color;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView;public class MainActivity extends AppCompatActivity{

int ch=1;float font=30;@Overrideprotected void onCreate(Bundle savedInstanceState){

super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);final TextView t= (TextView) findViewById(R.id.textView);Button b1= (Button) findViewById(R.id.button1);b1.setOnClickListener(new View.OnClickListener() {

@Overridepublic void onClick(View v) {

t.setTextSize(font);font = font + 5;if (font == 50)

font = 30;} });

Button b2= (Button) findViewById(R.id.button2);b2.setOnClickListener(new View.OnClickListener() {

@Overridepublic void onClick(View v) {

switch (ch) {case 1:

t.setTextColor(Color.RED);break;

case 2:t.setTextColor(Color.GREEN);break;

case 3:t.setTextColor(Color.BLUE);break;

case 4:t.setTextColor(Color.CYAN);

Page 31: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

31

break;case 5:

t.setTextColor(Color.YELLOW);break;

case 6:t.setTextColor(Color.MAGENTA);break;

}ch++;if (ch == 7)

ch = 1;} }); } }

So now the Coding part is also completed. Now run the application to see the output. Stop the program.

Output:

Result:

Thus a Simple Android Application that uses GUI components, Font and Colors is developedand executed successfully.

Page 32: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

32

EXP.NO:3DEVELOP AN APPLICATION THAT USES LAYOUT MANAGERS

AND EVENT LISTNERS.DATE:

Aim:

To develop a Simple Android Application that uses Layout Managers and Event Listeners.

Algorithm:

1. Start the program.2. Creating a New project.

Open Android Stdio and then click on File -> New -> New project.

Then type the Application name as “ex.no.2″ and click Next.

Page 33: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

33

Then select the Minimum SDK as shown below and click Next.

Then select the Empty Activity and click Next.

Finally click Finish.

Page 34: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

34

It will take some time to build and load the project. After completion it will look as given below.

Creating Second Activity for the Android Application:

Click on File -> New -> Activity -> Empty Activity.

Type the Activity Name as SecondActivity and click Finish button.

Page 35: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

35

Thus Second Activity For the application is created.

Designing layout for the Android Application:

Designing Layout for Main Activity:

Click on app -> res -> layout -> activity_main.xml.

Now click on Text as shown below.

Then delete the code which is there and type the code as given below.

Page 36: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

36

Code for Activity_main.xml:

<?xml version="1.0" encoding="utf-8"?><RelativeLayout 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"tools:context=".MainActivity"><LinearLayout

android:layout_width="match_parent"android:layout_height="100dp"><TextView

android:id="@+id/textView"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_margin="30dp"android:text="Details Form"android:textSize="25sp"android:gravity="center"/>

</LinearLayout><GridLayout

android:id="@+id/gridLayout"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_marginTop="100dp"android:layout_marginBottom="200dp"android:columnCount="2"android:rowCount="3"><TextView

android:id="@+id/textView1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_margin="10dp"android:layout_row="0"android:layout_column="0"android:text="Name"android:textSize="20sp"android:gravity="center"/>

<EditTextandroid:id="@+id/editText"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_margin="10dp"android:layout_row="0"

Page 37: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

37

android:layout_column="1"android:ems="10"/>

<TextViewandroid:id="@+id/textView2"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_margin="10dp"android:layout_row="1"android:layout_column="0"android:text="Reg.No"android:textSize="20sp"android:gravity="center"/>

<EditTextandroid:id="@+id/editText2"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_margin="10dp"android:layout_row="1"android:layout_column="1"android:inputType="number"android:ems="10"/>

<TextViewandroid:id="@+id/textView3"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_margin="10dp"android:layout_row="2"android:layout_column="0"android:text="Dept"android:textSize="20sp"android:gravity="center"/>

<Spinnerandroid:id="@+id/spinner"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_margin="10dp"android:layout_row="2"android:layout_column="1"android:spinnerMode="dropdown"/>

</GridLayout><Button

android:id="@+id/button"android:layout_width="wrap_content"android:layout_height="wrap_content"

Page 38: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

38

android:layout_alignParentBottom="true"android:layout_centerInParent="true"android:layout_marginBottom="150dp"android:text="Submit"/>

</RelativeLayout>

Now click on Design and your activity will look as given below.

So now the designing part of Main Activity is completed.

Designing Layout for Second Activity:

Click on app -> res -> layout -> activity_second.xml.

Now click on Text as shown below.

Page 39: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

39

Then delete the code which is there and type the code as given below.

Code for Activity_second.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout 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"tools:context="com.example.devang.exno2.SecondActivity"android:orientation="vertical"android:gravity="center"><TextView

android:id="@+id/textView1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_margin="20dp"android:text="New Text"android:textSize="30sp"/>

<TextViewandroid:id="@+id/textView2"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_margin="20dp"android:text="New Text"android:textSize="30sp"/>

<TextViewandroid:id="@+id/textView3"android:layout_width="wrap_content"

Page 40: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

40

android:layout_height="wrap_content"android:layout_margin="20dp"android:text="New Text"android:textSize="30sp"/>

</LinearLayout>

Now click on Design and your activity will look as given below.

So now the designing part of Second Activity is also completed.

Java Coding for the Android Application:

Java Coidng for Main Activity:

Click on app -> java -> com.example.exno2 -> MainActivity.

Then delete the code which is there and type the code as given below.

Page 41: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

41

Code for MainActivity.java:

package com.example.exno2;import android.content.Intent;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.ArrayAdapter;import android.widget.Button;import android.widget.EditText;import android.widget.Spinner;public class MainActivity extends AppCompatActivity {

//Defining the ViewsEditText e1,e2;Button bt;Spinner s;//Data for populating in Spinner

String [] dept_array={"CSE","ECE","IT","Mech","Civil"};String name,reg,dept;@Override

protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//Referring the Viewse1= (EditText) findViewById(R.id.editText);e2= (EditText) findViewById(R.id.editText2);bt= (Button) findViewById(R.id.button);s= (Spinner) findViewById(R.id.spinner);//Creating Adapter for Spinner for adapting the data from array to SpinnerArrayAdapter adapter= new

ArrayAdapter(MainActivity.this,android.R.layout.simple_spinner_item,dept_array);s.setAdapter(adapter);//Creating Listener for Button

bt.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {

//Getting the Values from Views(Edittext & Spinner)name=e1.getText().toString();reg=e2.getText().toString();dept=s.getSelectedItem().toString();//Intent For Navigating to Second ActivityIntent i = new Intent(MainActivity.this,SecondActivity.class);//For Passing the Values to Second Activityi.putExtra("name_key", name);

Page 42: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

42

i.putExtra("reg_key",reg);i.putExtra("dept_key", dept);startActivity(i);

} }); } }

So now the Coding part of Main Activity is completed.

Java Coding for Second Activity:

Click on app -> java -> com.example.exno2 -> SecondActivity.

Then delete the code which is there and type the code as given below.

Code for SecondActivity.java:

package com.example.exno2;import android.content.Intent;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.widget.TextView;public class SecondActivity extends AppCompatActivity {

TextView t1,t2,t3;String name,reg,dept;@Override

protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_second);t1= (TextView) findViewById(R.id.textView1);

t2= (TextView) findViewById(R.id.textView2);

Page 43: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

43

t3= (TextView) findViewById(R.id.textView3);//Getting the IntentIntent i = getIntent();//Getting the Values from First Activity using the Intent received

name=i.getStringExtra("name_key");reg=i.getStringExtra("reg_key");dept=i.getStringExtra("dept_key");//Setting the Values to Intent

t1.setText(name);t2.setText(reg);t3.setText(dept);

}}

Output:

Result:

Thus a Simple Android Application that uses Layout Managers and Event Listeners is developedand executed successfully.

Page 44: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

44

EXP.NO:4DEVELOP AN NATIVE CALCULATOR APPLICATION

DATE:

Aim:

To develop a Simple Android Application for Native Calculator.

Algorithm:

Start the program. Creating a New project:

Open Android Studio and then click on File -> New -> New project.

Then type the Application name and click Next.

Then select the Minimum SDK as shown below and click Next.

Page 45: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

45

Then select the Empty Activity and click Next.

Finally click Finish.

It will take some time to build and load the project. After completion it will look as given below.

Page 46: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

46

Designing layout for the Android Application.

Click on app -> res -> layout -> activity_main.xml

Now click on Text as shown below.

Then delete the code which is there and type the code as given below

Page 47: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

47

Code for Activity_main.xml:

<?xml version="1.0" encoding="utf-8"?><LinearLayout

xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_margin="20dp"><LinearLayout

android:id="@+id/linearLayout1"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_margin="20dp"><EditText

android:id="@+id/editText1"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_weight="1"android:inputType="numberDecimal"android:textSize="20sp" />

<EditTextandroid:id="@+id/editText2"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_weight="1"android:inputType="numberDecimal"android:textSize="20sp" />

</LinearLayout><LinearLayout

android:id="@+id/linearLayout2"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_margin="20dp"><Button

android:id="@+id/Add"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_weight="1"android:text="+"android:textSize="30sp"/>

<Buttonandroid:id="@+id/Sub"android:layout_width="match_parent"

Page 48: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

48

android:layout_height="wrap_content"android:layout_weight="1"android:text="-"android:textSize="30sp"/>

<Buttonandroid:id="@+id/Mul"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_weight="1"android:text="*"android:textSize="30sp"/>

<Buttonandroid:id="@+id/Div"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_weight="1"android:text="/"android:textSize="30sp"/>

</LinearLayout><TextView

android:id="@+id/textView"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginTop="50dp"android:text="Answer is"android:textSize="30sp"android:gravity="center"/>

</LinearLayout> So now the designing part is completed

Java Coding for the Android Application:

Click on app -> java -> com.example.exno1 -> MainActivity.

Page 49: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

49

Then delete the code which is there and type the code as given below.

Code for MainActivity.java:

package com. exno3;import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;import android.text.TextUtils;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;public class MainActivity extends AppCompatActivity implements OnClickListener{

//Defining the ViewsEditText Num1;EditText Num2;Button Add;Button Sub;Button Mul;Button Div;TextView Result;@Override

public void onCreate(Bundle savedInstanceState){

super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//Referring the Views

Num1 = (EditText) findViewById(R.id.editText1);Num2 = (EditText) findViewById(R.id.editText2);Add = (Button) findViewById(R.id.Add);Sub = (Button) findViewById(R.id.Sub);Mul = (Button) findViewById(R.id.Mul);Div = (Button) findViewById(R.id.Div);Result = (TextView) findViewById(R.id.textView);// set a listenerAdd.setOnClickListener(this);Sub.setOnClickListener(this);Mul.setOnClickListener(this);Div.setOnClickListener(this);

}@Override

public void onClick (View v)

Page 50: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

50

{float num1 = 0;float num2 = 0;float result = 0;String oper = "";// check if the fields are emptyif (TextUtils.isEmpty(Num1.getText().toString()) ||

TextUtils.isEmpty(Num2.getText().toString()))return;

// read EditText and fill variables with numbersnum1 = Float.parseFloat(Num1.getText().toString());num2 = Float.parseFloat(Num2.getText().toString());// defines the button that has been clicked and performs the corresponding operation

// write operation into oper, we will use it later for outputswitch (v.getId()){

case R.id.Add:oper = "+";result = num1 + num2;break;

case R.id.Sub:oper = "-";result = num1 - num2;break;

case R.id.Mul:oper = "*";result = num1 * num2;break;

case R.id.Div:oper = "/";result = num1 / num2;break;

default:break;

}// form the output lineResult.setText(num1 + " " + oper + " " + num2 + " = " + result);

}}

So now the Coding part is also completed. Now run the application to see the output.

Page 51: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

51

Output:

Result:

Thus a Simple Android Application for Native Calculator is developed and executed successfully.

Page 52: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

52

EXP.NO:5WRITE AN APPLICATION THAT DRAWS BASIC GRAPHICAL

PRIMITIVES ON THE SCREENDATE:

Aim :

To develop a Simple Android Application that draws basic Graphical Primitives on the screen.

Algorithm:

Start the program. Creating a New project:

Open Android Studio and then click on File -> New -> New project.

Then type the Application name and click Next.

Then select the Minimum SDK as shown below and click Next.

Page 53: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

53

Then select the Empty Activity and click Next.

Finally click Finish.

Page 54: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

54

It will take some time to build and load the project. After completion it will look as given below.

Designing layout for the Android Application.

Click on app -> res -> layout -> activity_main.xml

Now click on Text as shown below.

Then delete the code which is there and type the code as given below

Page 55: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

55

Code for Activity_main.xml:

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"android:layout_height="match_parent"><ImageView

android:layout_width="match_parent"android:layout_height="match_parent"android:id="@+id/imageView" />

</RelativeLayout>

So now the designing part is completed

Java Coding for the Android Application:

Click on app -> java -> com.example.exno1 -> MainActivity.

Then delete the code which is there and type the code as given below.

Code for MainActivity.java:

package com.example.exno4;

import android.app.Activity;import android.graphics.Bitmap;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.graphics.drawable.BitmapDrawable;import android.os.Bundle;import android.widget.ImageView;

Page 56: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

56

public class MainActivity extends Activity{

@Overridepublic void onCreate(Bundle savedInstanceState){

super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//Creating a BitmapBitmap bg = Bitmap.createBitmap(720, 1280, Bitmap.Config.ARGB_8888);//Setting the Bitmap as background for the ImageViewImageView i = (ImageView) findViewById(R.id.imageView);i.setBackgroundDrawable(new BitmapDrawable(bg));//Creating the Canvas ObjectCanvas canvas = new Canvas(bg);//Creating the Paint Object and set its color & TextSizePaint paint = new Paint();paint.setColor(Color.BLUE);paint.setTextSize(50);//To draw a Rectanglecanvas.drawText("Rectangle", 420, 150, paint);canvas.drawRect(400, 200, 650, 700, paint);//To draw a Circlecanvas.drawText("Circle", 120, 150, paint);canvas.drawCircle(200, 350, 150, paint);//To draw a Squarecanvas.drawText("Square", 120, 800, paint);canvas.drawRect(50, 850, 350, 1150, paint);//To draw a Linecanvas.drawText("Line", 480, 800, paint);canvas.drawLine(520, 850, 520, 1150, paint);

}}

So now the Coding part is also completed. Now run the application to see the output. Stop the program.

Page 57: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

57

Output:

Result:

Thus a Simple Android Application that draws basic Graphical Primitives on the screen isdeveloped and executed successfully.

Page 58: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

58

EXP.NO:6 DEVELOP AN APPLICATION THAT MAKES USE OF DATABASE.

DATE:

Aim :

To develop a Simple Android Application that makes use of Database.

Algorithm :

Start the program. Creating a New project:

Open Android Studio and then click on File -> New -> New project.

Then type the Application name and click Next.

Then select the Minimum SDK as shown below and click Next.

Page 59: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

59

Then select the Empty Activity and click Next.

Finally click Finish.

It will take some time to build and load the project. After completion it will look as given below.

Page 60: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

60

Designing layout for the Android Application.

Click on app -> res -> layout -> activity_main.xml

Now click on Text as shown below.

Then delete the code which is there and type the code as given below

Page 61: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

61

Code for Activity_main.xml:

<?xml version="1.0" encoding="utf-8"?><AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"android:layout_height="match_parent"><TextView

android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_x="50dp"android:layout_y="20dp"android:text="Student Details"android:textSize="30sp" />

<TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_x="20dp"android:layout_y="110dp"android:text="Enter Rollno:"android:textSize="20sp" />

<EditTextandroid:id="@+id/Rollno"android:layout_width="150dp"android:layout_height="wrap_content"android:layout_x="175dp"android:layout_y="100dp"android:inputType="number"android:textSize="20sp" />

<TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_x="20dp"android:layout_y="160dp"android:text="Enter Name:"android:textSize="20sp" />

<EditTextandroid:id="@+id/Name"android:layout_width="150dp"android:layout_height="wrap_content"android:layout_x="175dp"android:layout_y="150dp"android:inputType="text"android:textSize="20sp" />

<TextView

Page 62: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

62

android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_x="20dp"android:layout_y="210dp"android:text="Enter Marks:"android:textSize="20sp" />

<EditTextandroid:id="@+id/Marks"android:layout_width="150dp"android:layout_height="wrap_content"android:layout_x="175dp"android:layout_y="200dp"android:inputType="number"android:textSize="20sp" />

<Buttonandroid:id="@+id/Insert"android:layout_width="150dp"android:layout_height="wrap_content"android:layout_x="25dp"android:layout_y="300dp"android:text="Insert"android:textSize="30dp" />

<Buttonandroid:id="@+id/Delete"android:layout_width="150dp"android:layout_height="wrap_content"android:layout_x="200dp"android:layout_y="300dp"android:text="Delete"android:textSize="30dp" />

<Buttonandroid:id="@+id/Update"android:layout_width="150dp"android:layout_height="wrap_content"android:layout_x="25dp"android:layout_y="400dp"android:text="Update"android:textSize="30dp" />

<Buttonandroid:id="@+id/View"android:layout_width="150dp"android:layout_height="wrap_content"android:layout_x="200dp"android:layout_y="400dp"

Page 63: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

63

android:text="View"android:textSize="30dp" />

<Buttonandroid:id="@+id/ViewAll"android:layout_width="200dp"android:layout_height="wrap_content"android:layout_x="100dp"android:layout_y="500dp"android:text="View All"android:textSize="30dp" />

</AbsoluteLayout>

So now the designing part is completed

Java Coding for the Android Application:

Click on app -> java -> com.example.exno1 -> MainActivity.

Then delete the code which is there and type the code as given below.

Code for MainActivity.java:

package com.example.exno5;

import android.app.Activity;import android.app.AlertDialog.Builder;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;

Page 64: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

64

import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;

public class MainActivity extends Activity implements OnClickListener{

EditText Rollno,Name,Marks;Button Insert,Delete,Update,View,ViewAll;SQLiteDatabase db;/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState){

super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Rollno=(EditText)findViewById(R.id.Rollno);

Name=(EditText)findViewById(R.id.Name);Marks=(EditText)findViewById(R.id.Marks);Insert=(Button)findViewById(R.id.Insert);Delete=(Button)findViewById(R.id.Delete);Update=(Button)findViewById(R.id.Update);View=(Button)findViewById(R.id.View);ViewAll=(Button)findViewById(R.id.ViewAll);Insert.setOnClickListener(this);

Delete.setOnClickListener(this);Update.setOnClickListener(this);View.setOnClickListener(this);ViewAll.setOnClickListener(this);// Creating database and table

db=openOrCreateDatabase("StudentDB", Context.MODE_PRIVATE, null);db.execSQL("CREATE TABLE IF NOT EXISTS student(rollno VARCHAR,name VARCHAR,marks

VARCHAR);");}public void onClick(View view){

// Inserting a record to the Student tableif(view==Insert){

// Checking for empty fieldsif(Rollno.getText().toString().trim().length()==0||

Name.getText().toString().trim().length()==0||Marks.getText().toString().trim().length()==0)

Page 65: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

65

{showMessage("Error", "Please enter all values");return;

}db.execSQL("INSERT INTO student VALUES('"+Rollno.getText()+"','"+Name.getText()+

"','"+Marks.getText()+"');");showMessage("Success", "Record added");clearText();

}// Deleting a record from the Student tableif(view==Delete){

// Checking for empty roll numberif(Rollno.getText().toString().trim().length()==0){

showMessage("Error", "Please enter Rollno");return;

}Cursor c=db.rawQuery("SELECT * FROM student WHERE rollno='"+Rollno.getText()+"'",

null);if(c.moveToFirst()){

db.execSQL("DELETE FROM student WHERE rollno='"+Rollno.getText()+"'");showMessage("Success", "Record Deleted");

}else{

showMessage("Error", "Invalid Rollno");}clearText();

}// Updating a record in the Student tableif(view==Update){

// Checking for empty roll numberif(Rollno.getText().toString().trim().length()==0){

showMessage("Error", "Please enter Rollno");return;

}Cursor c=db.rawQuery("SELECT * FROM student WHERE rollno='"+Rollno.getText()+"'",

null);if(c.moveToFirst()) {

Page 66: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

66

db.execSQL("UPDATE student SET name='" + Name.getText() + "',marks='" +Marks.getText() +

"' WHERE rollno='"+Rollno.getText()+"'");showMessage("Success", "Record Modified");

}else {

showMessage("Error", "Invalid Rollno");}clearText();

}// Display a record from the Student tableif(view==View){

// Checking for empty roll numberif(Rollno.getText().toString().trim().length()==0){

showMessage("Error", "Please enter Rollno");return;

}Cursor c=db.rawQuery("SELECT * FROM student WHERE rollno='"+Rollno.getText()+"'",

null);if(c.moveToFirst()){

Name.setText(c.getString(1));Marks.setText(c.getString(2));

}else{

showMessage("Error", "Invalid Rollno");clearText();

}}// Displaying all the recordsif(view==ViewAll){

Cursor c=db.rawQuery("SELECT * FROM student", null);if(c.getCount()==0){

showMessage("Error", "No records found");return;

}StringBuffer buffer=new StringBuffer();while(c.moveToNext()){

Page 67: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

67

buffer.append("Rollno: "+c.getString(0)+"\n");buffer.append("Name: "+c.getString(1)+"\n");buffer.append("Marks: "+c.getString(2)+"\n\n");

}showMessage("Student Details", buffer.toString());

}}public void showMessage(String title,String message){

Builder builder=new Builder(this);builder.setCancelable(true);builder.setTitle(title);builder.setMessage(message);builder.show();

}public void clearText(){

Rollno.setText("");Name.setText("");Marks.setText("");Rollno.requestFocus();

}}

So now the Coding part is also completed. Now run the application to see the output. Stop the program.

Page 68: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

68

Output:

Result :

Thus a Simple Android Application that makes use of Database is developed andexecuted successfully.

Page 69: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

69

EXP.NO:7

DEVELOP AN APPLICATION THAT MAKES USE OF RSS FEED

DATE:

Aim :

To develop a Android Application that makes use of RSS Feed.

Algorithm :

1. Start the program.2. Creating a New project:

Open Android Studio and then click on File -> New -> New project.

Then type the Application name as “ex.no.6″ and click Next.

Page 70: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

70

Then select the Minimum SDK as shown below and click Next.

Then select the Empty Activity and click Next.

Finally click Finish.

It will take some time to build and load the project. After completion it will look as given below.

Page 71: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

71

Designing layout for the Android Application:

Click on app -> res -> layout -> activity_main.xml

Now click on Text as shown below.

Then delete the code which is there and type the code as given below.

Page 72: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

72

Code for Activity_main.xml:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="fill_parent"android:layout_height="fill_parent"android:orientation="vertical" ><ListView

android:id="@+id/listView"android:layout_width="match_parent"android:layout_height="wrap_content" />

</LinearLayout>

Now click on Design and your application will look as given below.

So now the designing part is completed.

Adding permissions in Manifest for the Android Application:

Click on app -> manifests -> AndroidManifest.xml

Page 73: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

73

Now include the INTERNET permissions in the AndroidManifest.xml fileas shown below

Code for AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="com.example.exno6" ><uses-permission android:name="android.permission.INTERNET"/><application

android:allowBackup="true"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:supportsRtl="true"android:theme="@style/AppTheme" ><activity android:name=".MainActivity" >

<intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" />

</intent-filter></activity>

</application></manifest>

So now the Permissions are added in the Manifest.

Page 74: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

74

Java Coding for the Android Application:

Click on app -> java -> com.example.exno6 -> MainActivity.

Then delete the code which is there and type the code as given below.

Code for MainActivity.java:

package com.example.exno6;

import android.app.ListActivity;import android.content.Intent;import android.net.Uri;import android.os.AsyncTask;import android.os.Bundle;import android.view.View;import android.widget.ArrayAdapter;import android.widget.ListView;import org.xmlpull.v1.XmlPullParser;import org.xmlpull.v1.XmlPullParserException;import org.xmlpull.v1.XmlPullParserFactory;import java.io.IOException;import java.io.InputStream;import java.net.MalformedURLException;import java.net.URL;import java.util.ArrayList;import java.util.List;

public class MainActivity extends ListActivity

Page 75: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

75

{List headlines;List links;@Overrideprotected void onCreate(Bundle savedInstanceState){

super.onCreate(savedInstanceState);new MyAsyncTask().execute();

}class MyAsyncTask extends AsyncTask<Object,Void,ArrayAdapter>{

@Overrideprotected ArrayAdapter doInBackground(Object[] params){

headlines = new ArrayList();links = new ArrayList();try{

URL url = new URL("https://codingconnect.net/feed");XmlPullParserFactory factory = XmlPullParserFactory.newInstance();factory.setNamespaceAware(false);XmlPullParser xpp = factory.newPullParser();// We will get the XML from an input streamxpp.setInput(getInputStream(url), "UTF_8");boolean insideItem = false;// Returns the type of current event: START_TAG, END_TAG, etc..int eventType = xpp.getEventType();while (eventType != XmlPullParser.END_DOCUMENT){

if (eventType == XmlPullParser.START_TAG){

if (xpp.getName().equalsIgnoreCase("item")){

insideItem = true;}else if (xpp.getName().equalsIgnoreCase("title")){

if (insideItem)headlines.add(xpp.nextText()); //extract the headline

}else if (xpp.getName().equalsIgnoreCase("link")){

if (insideItem)links.add(xpp.nextText()); //extract the link of article

Page 76: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

76

}}else if(eventType==XmlPullParser.END_TAG &&

xpp.getName().equalsIgnoreCase("item")){

insideItem=false;}eventType = xpp.next(); //move to next element

}

}catch (MalformedURLException e){

e.printStackTrace();}catch (XmlPullParserException e){

e.printStackTrace();}catch (IOException e){

e.printStackTrace();}return null;

}protected void onPostExecute(ArrayAdapter adapter){

adapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1,headlines);

setListAdapter(adapter);}

}@Overrideprotected void onListItemClick(ListView l, View v, int position, long id){

Uri uri = Uri.parse((links.get(position)).toString());Intent intent = new Intent(Intent.ACTION_VIEW, uri);startActivity(intent);

}public InputStream getInputStream(URL url){

try{

return url.openConnection().getInputStream();

Page 77: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

77

}catch (IOException e){

return null;}

}} So now the Coding part is also completed. Now run the application to see the output.

Output:

Result:

Thus Android Application that makes use of RSS Feed is developed and executed successfully.

Page 78: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

78

Aim :

To develop a Android Application that implements Multi threading.

Algorithm:

Start the program. Creating a New project:

Open Android Studio and then click on File -> New -> New project.

Then type the Application name and click Next.

Then select the Minimum SDK as shown below and click Next.

EXP.NO:8

IMPLEMENT AN APPLICATION THAT IMPLEMENTS MULTITHREADING.DATE:

Page 79: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

79

Then select the Empty Activity and click Next.

Finally click Finish.

It will take some time to build and load the project. After completion it will look as given below.

Page 80: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

80

Designing layout for the Android Application.

Click on app -> res -> layout -> activity_main.xml

Now click on Text as shown below.

Then delete the code which is there and type the code as given below

Page 81: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

81

Code for Activity_main.xml:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical" ><ImageView

android:id="@+id/imageView"android:layout_width="250dp"android:layout_height="250dp"android:layout_margin="50dp"android:layout_gravity="center" />

<Buttonandroid:id="@+id/button"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_margin="10dp"android:layout_gravity="center"android:text="Load Image 1" />

<Buttonandroid:id="@+id/button2"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_margin="10dp"android:layout_gravity="center"android:text="Load image 2" />

</LinearLayout>

So now the designing part is completed

Java Coding for the Android Application:

Click on app -> java -> com.example.exno1 -> MainActivity.

Then delete the code which is there and type the code as given below.

Page 82: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

82

Code for MainActivity.java:

package com.example.exno7;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.widget.Button;import android.widget.ImageView;public class MainActivity extends AppCompatActivity{

ImageView img;Button bt1,bt2;@Overrideprotected void onCreate(Bundle savedInstanceState){

super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);bt1 = (Button)findViewById(R.id.button);bt2= (Button) findViewById(R.id.button2);img = (ImageView)findViewById(R.id.imageView);bt1.setOnClickListener(new View.OnClickListener(){

@Overridepublic void onClick(View v){

new Thread(new Runnable(){

@Overridepublic void run(){

img.post(new Runnable(){

@Overridepublic void run(){

img.setImageResource(R.drawable.india1);} }); } }).start(); } });

bt2.setOnClickListener(new View.OnClickListener(){

@Overridepublic void onClick(View v){

new Thread(new Runnable() {@Override

Page 83: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

83

public void run(){

img.post(new Runnable(){

@Overridepublic void run(){

img.setImageResource(R.drawable.india2);} }); }

}).start();} }); } }

So now the Coding part is also completed. Now run the application to see the output. Stop the program.

Output:

Result:

Thus Android Application that implements Multi threading is developed andexecuted successfully.

Page 84: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

84

Aim :

To develop a Android Application that writes data to the SD Card.

Algorithm :

1. Start the program.2. Creating a New project:

Open Android Studio and then click on File -> New -> New project.

Then type the Application name as “ex.no.9″ and click Next.

Then select the Minimum SDK as shown below and click Next.

EXP.NO:9 IMPLEMENT AN APPLICATION THAT USES DATA TO THESDCARD

DATE:

Page 85: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

85

Then select the Empty Activity and click Next.

Finally click Finish.

It will take some time to build and load the project. After completion it will look as given below.

Page 86: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

86

Designing layout for the Android Application:

Click on app -> res -> layout -> activity_main.xml.

Now click on Text as shown below.

Then delete the code which is there and type the code as given below.

Page 87: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

87

Code for Activity_main.xml:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"android:layout_height="match_parent"android:layout_margin="20dp"android:orientation="vertical"><EditText

android:id="@+id/editText"android:layout_width="match_parent"android:layout_height="wrap_content"android:singleLine="true"android:textSize="30dp" />

<Buttonandroid:id="@+id/button"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_margin="10dp"android:text="Write Data"android:textSize="30dp" />

<Buttonandroid:id="@+id/button2"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_margin="10dp"android:text="Read data"android:textSize="30dp" />

<Buttonandroid:id="@+id/button3"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_margin="10dp"android:text="Clear"android:textSize="30dp" />

</LinearLayout>

Now click on Design and your application will look as given below.

Page 88: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

88

So now the designing part is completed.

Adding permissions in Manifest for the Android Application:

Click on app -> manifests -> AndroidManifest.xml

Now include the WRITE_EXTERNAL_STORAGE permissions in theAndroidManifest.xml file as shown below

Page 89: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

89

Code for AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="com.example.exno9" ><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-

permission><application

android:allowBackup="true"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:supportsRtl="true"android:theme="@style/AppTheme" ><activity android:name=".MainActivity" >

<intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" />

</intent-filter></activity>

</application></manifest>

So now the Permissions are added in the Manifest.

Java Coding for the Android Application:

Click on app -> java -> com.example.exno9 -> MainActivity.

Then delete the code which is there and type the code as given below.

Page 90: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

90

Code for MainActivity.java:

package com.example.exno9;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast;import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStreamReader;public class MainActivity extends AppCompatActivity{

EditText e1;Button write,read,clear;@Overrideprotected void onCreate(Bundle savedInstanceState){

super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);e1= (EditText) findViewById(R.id.editText);write= (Button) findViewById(R.id.button);read= (Button) findViewById(R.id.button2);clear= (Button) findViewById(R.id.button3);write.setOnClickListener(new View.OnClickListener(){

@Overridepublic void onClick(View v){

String message=e1.getText().toString();try{

File f=new File("/sdcard/myfile.txt");f.createNewFile();FileOutputStream fout=new FileOutputStream(f);fout.write(message.getBytes());fout.close();Toast.makeText(getBaseContext(),"Data Written in

SDCARD",Toast.LENGTH_LONG).show();}catch (Exception e)

Page 91: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

91

{Toast.makeText(getBaseContext(),e.getMessage(),Toast.LENGTH_LONG).show();

}}

});read.setOnClickListener(new View.OnClickListener(){

@Overridepublic void onClick(View v){

String message;String buf = "";try{

File f = new File("/sdcard/myfile.txt");FileInputStream fin = new FileInputStream(f);BufferedReader br = new BufferedReader(new InputStreamReader(fin));while ((message = br.readLine()) != null){

buf += message;}e1.setText(buf);br.close();fin.close();Toast.makeText(getBaseContext(),"Data Recived from

SDCARD",Toast.LENGTH_LONG).show();}catch (Exception e){

Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();}

}});

clear.setOnClickListener(new View.OnClickListener(){

@Overridepublic void onClick(View v){

e1.setText("");}

});}

}

Page 92: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

92

Output:

Result:

Thus Android Application that writes data to the SD Card is developed andexecuted successfully.

Page 93: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

93

Aim:

To develop an Android Application that creates an alert upon receiving a message.

Algorithm:

1. Start the program.2. Creating a New project.

Open Android Studio and then click on File -> New -> New project.

Then type the Application name and click Next.

EXP.NO:10

IMPLEMENT AN APPLICATION THAT CREATES AN ALERT UPONRECEIVING A MESSAGE.DATE:

Page 94: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

94

Then select the Minimum SDK as shown below and click Next.

Then select the Empty Activity and click Next.

Finally click Finish.

It will take some time to build and load the project. After completion it will look as given below.

Page 95: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

95

Designing layout for the Android Application.

Click on app -> res -> layout -> activity_main.xml

Now click on Text as shown below.

Then delete the code which is there and type the code as given below

Page 96: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

96

Code for Activity_main.xml:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"android:layout_height="match_parent"android:layout_margin="10dp"android:orientation="vertical"><TextView

android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Message"android:textSize="30sp" />

<EditTextandroid:id="@+id/editText"android:layout_width="match_parent"android:layout_height="wrap_content"android:singleLine="true"android:textSize="30sp" />

<Buttonandroid:id="@+id/button"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_margin="30dp"android:layout_gravity="center"android:text="Notify"android:textSize="30sp"/>

</LinearLayout>

So now the designing part is completed

Java Coding for the Android Application:

Click on app -> java -> com.example.exno1 -> MainActivity.

Then delete the code which is there and type the code as given below.

Page 97: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

97

Code for MainActivity.java:

package com.example.exno10;

import android.app.Notification;import android.app.NotificationManager;import android.app.PendingIntent;import android.content.Intent;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.widget.Button;import android.widget.EditText;

public class MainActivity extends AppCompatActivity{

Button notify;EditText e;@Overrideprotected void onCreate(Bundle savedInstanceState){

super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);

notify= (Button) findViewById(R.id.button);e= (EditText) findViewById(R.id.editText);

notify.setOnClickListener(new View.OnClickListener(){

@Overridepublic void onClick(View v){

Intent intent = new Intent(MainActivity.this, SecondActivity.class);PendingIntent pending = PendingIntent.getActivity(MainActivity.this, 0, intent, 0);Notification noti = new Notification.Builder(MainActivity.this).setContentTitle("New

Message").setContentText(e.getText().toString()).setSmallIcon(R.mipmap.ic_launcher).setContentIntent(pending).build();

NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

noti.flags |= Notification.FLAG_AUTO_CANCEL;manager.notify(0, noti);

}});

}}

Page 98: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

98

So now the Coding part is also completed. Now run the application to see the output. Stop the program.

Output:

Result:

Thus Android Application that creates an alert upon receiving a message is developed andexecuted successfully.

Page 99: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

99

EXP.NO: 11 WRITE AN MOBILE APPLICATION THAT CREATES AN ALARMCLOCK.

DATE:

Aim:

To develop a Android Application that creates Alarm Clock.

Algorithm:

1. Start the program.2. Creating a New project.

Open Android Studio and then click on File -> New -> New project.

Then type the Application name as “ex.no.10″ and click Next.

Page 100: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

100

Then select the Minimum SDK as shown below and click Next.

Then select the Empty Activity and click Next.

Finally click Finish.

It will take some time to build and load the project. After completion it will look as given below.

Page 101: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

101

Creating Second Activity for the Android Application:

Click on File -> New -> Activity -> Empty Activity.

Type the Activity Name as AlarmReceiver and click Finish button.

Thus Second Activity For the application is created.

Page 102: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

102

Designing layout for the Android Application:

Click on app -> res -> layout -> activity_main.xml.

Now click on Text as shown below.

Then delete the code which is there and type the code as given below.

Code for Activity_main.xml:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical">

<TimePickerandroid:id="@+id/timePicker"android:layout_width="wrap_content"

Page 103: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

103

android:layout_height="wrap_content"android:layout_gravity="center" />

<ToggleButtonandroid:id="@+id/toggleButton"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center"android:layout_margin="20dp"android:checked="false"android:onClick="OnToggleClicked" />

</LinearLayout>

Now click on Design and your application will look as given below.

So now the designing part is completed.

Changes in Manifest for the Android Application:

Click on app -> manifests -> AndroidManifest.xml

Page 104: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

104

Now change the activity tag to receiver tag in the AndroidManifest.xml file as shownbelow

Code for AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="com.example.exno11" ><application

android:allowBackup="true"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:supportsRtl="true"android:theme="@style/AppTheme" ><activity android:name=".MainActivity" >

<intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" />

</intent-filter></activity><receiver android:name=".AlarmReceiver" ></receiver>

</application></manifest>

So now the changes are done in the Manifest.

Page 105: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

105

Java Coding for the Android Application:

Java Coding for Main Activity:

Click on app -> java -> com.example.exno10 -> MainActivity.

Then delete the code which is there and type the code as given below.

Code for MainActivity.java:

package com.example.exno11;

import android.app.AlarmManager;import android.app.PendingIntent;import android.content.Intent;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.widget.TimePicker;import android.widget.Toast;import android.widget.ToggleButton;

import java.util.Calendar;

public class MainActivity extends AppCompatActivity{

TimePicker alarmTimePicker;PendingIntent pendingIntent;AlarmManager alarmManager;

Page 106: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

106

@Overrideprotected void onCreate(Bundle savedInstanceState){

super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);alarmTimePicker = (TimePicker) findViewById(R.id.timePicker);alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

}public void OnToggleClicked(View view){

long time;if (((ToggleButton) view).isChecked()){

Toast.makeText(MainActivity.this, "ALARM ON", Toast.LENGTH_SHORT).show();Calendar calendar = Calendar.getInstance();calendar.set(Calendar.HOUR_OF_DAY, alarmTimePicker.getCurrentHour());calendar.set(Calendar.MINUTE, alarmTimePicker.getCurrentMinute());Intent intent = new Intent(this, AlarmReceiver.class);pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);

time=(calendar.getTimeInMillis()-(calendar.getTimeInMillis()%60000));if(System.currentTimeMillis()>time){

if (calendar.AM_PM == 0)time = time + (1000*60*60*12);

elsetime = time + (1000*60*60*24);

}alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time, 10000, pendingIntent);

}else{

alarmManager.cancel(pendingIntent);Toast.makeText(MainActivity.this, "ALARM OFF", Toast.LENGTH_SHORT).show();

}}

}

So now the Coding part of Main Activity is completed.

Page 107: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

107

Java Coding for Alarm Receiver:

Click on app -> java -> com.example.exno11 -> AlarmReceiver.

Then delete the code which is there and type the code as given below.

Code for AlarmReceiver.java:

package com.example.exno11;import android.content.BroadcastReceiver;

import android.content.Context;import android.content.Intent;import android.media.Ringtone;import android.media.RingtoneManager;import android.net.Uri;import android.widget.Toast;public class AlarmReceiver extends BroadcastReceiver

{@Overridepublic void onReceive(Context context, Intent intent){

Toast.makeText(context, "Alarm! Wake up! Wake up!", Toast.LENGTH_LONG).show();Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);if (alarmUri == null){

alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);}Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri);ringtone.play();

}}

Page 108: What is Android?...The latest major release is Android 7.0 "Nougat". 6 See previous versions and their features at The Android Story. The Dashboard for Platform Versions is updated

108

Output:

Result:Thus Android Application that creates Alarm Clock is developed and executed successfully.