0% found this document useful (0 votes)
4 views

Mobile Application Development - Android

The document provides a comprehensive guide to Android development, covering topics such as features, application categories, architecture, components, and environment setup. It includes detailed instructions on using Android Studio, creating applications, managing resources, and implementing various functionalities like notifications, services, and UI design. Additionally, it addresses best practices, testing, and integration with social media platforms.

Uploaded by

richard kipkoech
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Mobile Application Development - Android

The document provides a comprehensive guide to Android development, covering topics such as features, application categories, architecture, components, and environment setup. It includes detailed instructions on using Android Studio, creating applications, managing resources, and implementing various functionalities like notifications, services, and UI design. Additionally, it addresses best practices, testing, and integration with social media platforms.

Uploaded by

richard kipkoech
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 723

Contents

Why Android............................................................................................................................................2
Features of Android.....................................................................................................................................3
Android Applications...................................................................................................................................4
Categories of Android applications..............................................................................................................5
History of Android.......................................................................................................................................5
What is API level?........................................................................................................................................6
Android - Environment Setup......................................................................................................................8
Set-up Java Development Kit (JDK)..........................................................................................................8
Android IDEs............................................................................................................................................9
Android - Studio...................................................................................................................................9
Step 1 - System Requirements..................................................................................................10
Step 2 - Setup Android Studio....................................................................................................10
Overview......................................................................................................................................10
Installation.........................................................................................................................................10
Step 3 - Create Android Virtual Device...................................................................................19
Hello Word Example.......................................................................................................................21
Android - Architecture.......................................................................................................................22
Linux kernel......................................................................................................................................23
Libraries..............................................................................................................................................23
Android Libraries.............................................................................................................................24
Android Runtime.............................................................................................................................24
Application Framework.................................................................................................................25
Applications.......................................................................................................................................25
Android - Application Components...............................................................................................25
Activities.............................................................................................................................................26
Services..............................................................................................................................................26
Broadcast Receivers......................................................................................................................26
Content Providers...........................................................................................................................27
Additional Components.................................................................................................................27

1|Page
Android - Hello World Example......................................................................................................28
Create Android Application..........................................................................................................28
Anatomy of Android Application................................................................................................31
The Main Activity File....................................................................................................................33
The Manifest File.............................................................................................................................34
The Strings File................................................................................................................................35
The Layout File.................................................................................................................................35
Running the Application...............................................................................................................36
Android Resources Organizing & Accessing..............................................................................37
Organize resource in Android Studio.......................................................................................37
Alternative Resources...................................................................................................................39
Accessing Resources.....................................................................................................................41
Accessing Resources in Code...........................................................................................41
Example........................................................................................................................................41
Example........................................................................................................................................42
Example........................................................................................................................................42
Accessing Resources in XML............................................................................................43
Android - Activities.............................................................................................................................43
Example..............................................................................................................................................45
Android - Services...............................................................................................................................48
Example..............................................................................................................................................52
Android - Broadcast Receivers.......................................................................................................58
Creating the Broadcast Receiver...............................................................................................59
Registering Broadcast Receiver.................................................................................................59
Broadcasting Custom Intents.....................................................................................................61
Example..............................................................................................................................................62
Android - Content Providers............................................................................................................67
Content URIs.....................................................................................................................................68
Create Content Provider...............................................................................................................69
Example..............................................................................................................................................70
Android - Fragments..........................................................................................................................83
Fragment Life Cycle.......................................................................................................................84
How to use Fragments?................................................................................................................86

2|Page
Types of Fragments.......................................................................................................................86
Android - Intents and Filters............................................................................................................86
Intent Objects...................................................................................................................................88
Action.............................................................................................................................................88
Data................................................................................................................................................89
Category.......................................................................................................................................90
Extras.............................................................................................................................................90
Flags...............................................................................................................................................90
Component Name...................................................................................................................91
Types of Intents...............................................................................................................................91
Explicit Intents.........................................................................................................................91
Implicit Intents.........................................................................................................................92
Example..............................................................................................................................................94
Intent Filters......................................................................................................................................99
Example............................................................................................................................................100
Android - UI Layouts.........................................................................................................................109
Android Layout Types..................................................................................................................111
Layout Attributes..........................................................................................................................112
View Identification........................................................................................................................115
Android - UI Controls........................................................................................................................115
Android UI Controls......................................................................................................................116
Create UI Controls.........................................................................................................................117
Android - Event Handling...............................................................................................................118
Event Listeners & Event Handlers...........................................................................................118
Event Listeners Registration.....................................................................................................119
Touch Mode.....................................................................................................................................120
Focus.................................................................................................................................................120
onTouchEvent().............................................................................................................................120
Event Handling Examples..........................................................................................................121
Event Listeners Registration Using an Anonymous Inner Class................121
Exercise............................................................................................................................................126
Android - Styles and Themes........................................................................................................127
Defining Styles...............................................................................................................................127

3|Page
Using Styles....................................................................................................................................127
Style Inheritance...........................................................................................................................128
Applying Colors to Theme Attributes.....................................................................................129
Using a Custom Nine-Patch With Buttons............................................................................130
Steps to create Nine-Patch Buttons..........................................................................131
Android Themes............................................................................................................................132
Styling the colour palette...........................................................................................................133
Default Styles & Themes............................................................................................................134
Android - Custom Components....................................................................................................135
Creating a Simple Custom Component.................................................................................136
Android - Drag and Drop................................................................................................................140
The Drag/Drop Process...............................................................................................................141
The DragEvent Class....................................................................................................................141
Constants..................................................................................................................................141
Methods......................................................................................................................................142
Listening for Drag Event.............................................................................................................143
Starting a Drag Event..................................................................................................................143
Example............................................................................................................................................143
Android - Notifications.....................................................................................................................150
Create and Send Notifications..................................................................................................152
Step 1 - Create Notification Builder...........................................................................152
Step 2 - Setting Notification Properties..................................................................152
Step 3 - Attach Actions......................................................................................................152
Step 4 - Issue the notification.......................................................................................153
The NotificationCompat.Builder Class...................................................................................153
Example............................................................................................................................................155
Big View Notification....................................................................................................................161
Android - Location Based Services.............................................................................................162
The Location Object.....................................................................................................................163
Get the Current Location............................................................................................................164
Get the Updated Location..........................................................................................................165
Location Quality of Service........................................................................................................165
Displaying a Location Address.................................................................................................166

4|Page
Example............................................................................................................................................167
Create Android Application.............................................................................................167
Android - Sending Email.................................................................................................................176
Intent Object - Action to send Email.......................................................................................177
Intent Object - Data/Type to send Email...............................................................................177
Intent Object - Extra to send Email.........................................................................................177
Example............................................................................................................................................179
Android - Sending SMS....................................................................................................................184
Example............................................................................................................................................185
Using Built-in Intent to send SMS............................................................................................191
Intent Object - Action to send SMS.........................................................................................192
Intent Object - Data/Type to send SMS.................................................................................192
Intent Object - Extra to send SMS...........................................................................................192
Example............................................................................................................................................192
Android - Phone Calls......................................................................................................................200
Intent Object - Action to make Phone Call...........................................................................200
Intent Object - Data/Type to make Phone Call...................................................................200
Example............................................................................................................................................200
Publishing Android Application.....................................................................................................205
Android development life cycle...............................................................................................206
Export Android Application Process........................................................................................207
Apk development process...............................................................................................208
Google Play Registration............................................................................................................210
Signing Your App Manually........................................................................................................211
Some of App markets..................................................................................................................212
Android - Alert Dialog......................................................................................................................213
Dialog fragment.............................................................................................................................214
List dialog........................................................................................................................................215
Single-choice list dialog..............................................................................................................215
Example............................................................................................................................................216
Android - Animations.......................................................................................................................223
Tween Animation..........................................................................................................................223
Example............................................................................................................................................224

5|Page
Android - Audio Capture.................................................................................................................238
Example............................................................................................................................................239
Android - Audio Manager................................................................................................................249
Example............................................................................................................................................251
Android - Auto Complete................................................................................................................259
Example............................................................................................................................................260
Android - Best Practices..................................................................................................................268
Best Practices - User input.........................................................................................................268
Best Practices - Background jobs............................................................................................268
AsyncTask Vs Services......................................................................................................269
Best Practices - Performance....................................................................................................269
Best Practices - Security and privacy....................................................................................269
Example............................................................................................................................................270
Android - Bluetooth..........................................................................................................................279
Example............................................................................................................................................280
Android - Camera..............................................................................................................................289
Using existing android camera application in our application......................................289
Example............................................................................................................................................291
Android - Clipboard..........................................................................................................................298
Copying data..................................................................................................................................299
Pasting data....................................................................................................................................299
Example............................................................................................................................................300
Android - Custom Fonts..................................................................................................................309
Example............................................................................................................................................310
Android - Data Backup....................................................................................................................314
Example............................................................................................................................................316
Test your BackupAgent...............................................................................................................318
Install your application on a suitable Android system image....................319
Ensure data backup is enabled....................................................................................319
Performing backup..............................................................................................................319
Uninstall and reinstall your application..................................................................319
Android - Developer Tools.............................................................................................................320
SDK tools..........................................................................................................................................320

6|Page
Android.............................................................................................................................................321
DDMS.................................................................................................................................................321
Running DDMS........................................................................................................................321
How it works............................................................................................................................321
Making SMS..............................................................................................................................322
Making Call...............................................................................................................................323
Capturing ScreenShot........................................................................................................326
Sqlite3...............................................................................................................................................327
Use Sqlite3 from a remote shell..................................................................................327
Using Sqlite3 directly.........................................................................................................328
Platform tools.................................................................................................................................328
Android - Emulator...........................................................................................................................328
Creating AVD..................................................................................................................................328
Changing Orientation..................................................................................................................329
Emulator Commands...................................................................................................................331
Emulator - Sending SMS.............................................................................................................332
Sending SMS through Telnet.........................................................................................332
Emulator - Making Call................................................................................................................334
Emulator - Transferring files.....................................................................................................335
Android - Facebook Integration....................................................................................................336
Registering your application..........................................................................................336
Downloading SDK and integrating it.........................................................................337
Creating facebook login application..........................................................................337
Intent share.....................................................................................................................................338
Example............................................................................................................................................339
Android - Gestures............................................................................................................................346
Handling Pinch Gesture..............................................................................................................347
Example............................................................................................................................................348
Android - Google Maps....................................................................................................................355
Google Map - Layout file...................................................................................................355
Google Map - AndroidManifest file.............................................................................355
Customizing Google Map............................................................................................................356
Adding Marker........................................................................................................................356

7|Page
Changing Map Type.............................................................................................................356
Enable/Disable zoom...........................................................................................................356
Example............................................................................................................................................357
Android - Image Effects..................................................................................................................363
Example............................................................................................................................................365
Android - Image Switcher...............................................................................................................379
Example............................................................................................................................................381
Android - Internal Storage.............................................................................................................388
Writing file.......................................................................................................................................389
Reading file.....................................................................................................................................389
Example............................................................................................................................................391
Android - JetPlayer............................................................................................................................399
Example............................................................................................................................................400
Using JetCreator............................................................................................................................401
Installing python...................................................................................................................401
Installing WxPython............................................................................................................402
Ruuning JetCreator..............................................................................................................402
Creating JetContent.............................................................................................................403
Verifying Results...........................................................................................................................404
Android - JSON Parser......................................................................................................................405
JSON - Elements.............................................................................................................................405
JSON - Parsing................................................................................................................................406
Example............................................................................................................................................407
Android - LinkedIn Integration......................................................................................................414
Integrating Linkedin SDK............................................................................................................415
Registering your application..........................................................................................415
Downloading SDK and integrating it.........................................................................416
Posting updates on Linkedin application...............................................................416
Intent share.....................................................................................................................................416
Example............................................................................................................................................417
Android - Loading Spinner.............................................................................................................425
Example............................................................................................................................................426
Android - Localization......................................................................................................................432

8|Page
Localizing Strings..........................................................................................................................433
Italy, res/values-it/strings.xml......................................................................................433
Spanish, res/values-it/strings.xml..............................................................................433
French, res/values-it/strings.xml.................................................................................434
Example............................................................................................................................................434
Android - Login Screen....................................................................................................................439
Example............................................................................................................................................440
Android - MediaPlayer.....................................................................................................................449
Example............................................................................................................................................450
Android - Multitouch.........................................................................................................................462
Example............................................................................................................................................463
Android - Navigation........................................................................................................................473
Providing Up Navigation.............................................................................................................473
Handling device back button....................................................................................................473
Example............................................................................................................................................474
Android - Network Connection.....................................................................................................481
Checking Network Connection.................................................................................................482
Performing Network Operations..............................................................................................482
Example............................................................................................................................................484
Android - NFC Guide.........................................................................................................................493
How It Works...................................................................................................................................493
Three Modes of Operation...............................................................................................494
How it works with Android.........................................................................................................494
Future Applications......................................................................................................................496
Android - PHP/MYSQL.......................................................................................................................496
PHP - MYSQL...................................................................................................................................496
Creating Database...............................................................................................................496
Creating Tables......................................................................................................................496
Inserting Values in tables................................................................................................497
PHP - GET and POST methods.......................................................................................497
Android - Connecting MYSQL....................................................................................................498
Connecting Via Get Method............................................................................................498
Connecting Via Post Method..........................................................................................498

9|Page
Example............................................................................................................................................499
PHP - MYSQL part.................................................................................................................499
Android Part............................................................................................................................500
Android - Progress Circle................................................................................................................513
Example............................................................................................................................................514
Android Progress Bar using ProgressDialog............................................................................521
Example............................................................................................................................................521
Android - Push Notification............................................................................................................527
Example............................................................................................................................................529
Android - RenderScript....................................................................................................................537
How RenderScript Works............................................................................................................537
How to Begin..................................................................................................................................537
A RenderScript Kernel.......................................................................................................537
RenderScript APIs.................................................................................................................538
How to use RenderScript Support Library.............................................................539
Android - RSS Reader......................................................................................................................540
RSS Example...................................................................................................................................540
RSS Elements.................................................................................................................................540
Parsing RSS.....................................................................................................................................540
Example............................................................................................................................................542
Android - Screen Cast......................................................................................................................554
Screen Cast Steps.........................................................................................................................554
Step 1..........................................................................................................................................554
Step 2..........................................................................................................................................554
Step 3..........................................................................................................................................554
Step 4..........................................................................................................................................555
Android - SDK Manager...................................................................................................................558
Running Android SDK Manager....................................................................................559
Recommended Packages..................................................................................................560
Enabling Proxy in Android SDK Manager................................................................560
Adding New Third Party Sites...................................................................................................561
Android - Sensors..............................................................................................................................562
Getting list of sensors supported............................................................................................563

10 | P a g e
Example............................................................................................................................................564
Android - Session Management...................................................................................................570
Shared Preferences......................................................................................................................570
Session Management through Shared Preferences..........................................................571
Example............................................................................................................................................571
Android - Shared Preferences.......................................................................................................581
Example............................................................................................................................................583
Android - SIP Protocol......................................................................................................................590
Applications.....................................................................................................................................590
Requirements.................................................................................................................................590
SIP Classes......................................................................................................................................591
Functions of SIP.............................................................................................................................591
Components of SIP.......................................................................................................................591
UAC................................................................................................................................................591
UAS................................................................................................................................................592
SipManager.....................................................................................................................................592
Android - Spelling Checker............................................................................................................593
Example............................................................................................................................................594
Android - SQLite Database............................................................................................................603
Database - Package.....................................................................................................................603
Database - Creation.....................................................................................................................603
Database - Insertion.....................................................................................................................604
Database - Fetching.....................................................................................................................604
Database - Helper class..............................................................................................................605
Example............................................................................................................................................605
Android - Support Library...............................................................................................................626
Support Library Features............................................................................................................626
Downloading the Support Libraries........................................................................................627
Choosing Support Libraries............................................................................................628
Changes in Android build.gradle.................................................................................628
Android - Testing...............................................................................................................................629
Test Structure.................................................................................................................................629
Testing Tools in android.............................................................................................................629

11 | P a g e
JUnit...................................................................................................................................................630
Monkey.............................................................................................................................................631
Monkey features...................................................................................................................631
Monkey Usage........................................................................................................................631
Example............................................................................................................................................633
Android - Text To Speech...............................................................................................................638
Example............................................................................................................................................640
Android - TextureView.....................................................................................................................648
Example............................................................................................................................................649
Android - Twitter Integration.........................................................................................................656
Integrating Twitter SDK..............................................................................................................656
Registering your application..........................................................................................657
Downloading SDK and integrating it.........................................................................658
Posting tweets on twitter application......................................................................658
Intent share.....................................................................................................................................659
Example............................................................................................................................................660
Android - UI Design..........................................................................................................................668
UI screen components.................................................................................................................668
Understanding Screen Components.......................................................................................669
View and ViewGroups........................................................................................................669
Types of layout.......................................................................................................................669
Linear Layout..........................................................................................................................670
AbsoluteLayout......................................................................................................................670
TableLayout.............................................................................................................................670
RelativeLayout.......................................................................................................................671
FrameLayout............................................................................................................................671
Units of Measurement.................................................................................................................672
Screen Densities............................................................................................................................673
Optimizing layouts........................................................................................................................673
Android - UI Patterns........................................................................................................................673
UI Patterns components.............................................................................................................673
Action Bar........................................................................................................................................674
Action Bar Components.....................................................................................................674

12 | P a g e
Confirming and Acknowledging...............................................................................................675
Confirming................................................................................................................................675
Acknowledging.......................................................................................................................675
Settings............................................................................................................................................675
Placement of Settings........................................................................................................676
Help....................................................................................................................................................676
Placement of Help................................................................................................................676
Selection..........................................................................................................................................676
Using Contextual Action Bar (CAB)............................................................................677
Android - UI Testing..........................................................................................................................677
uiautomatorviewer.......................................................................................................................677
uiautomator....................................................................................................................................682
Example............................................................................................................................................683
Android - WebView...........................................................................................................................688
Example............................................................................................................................................690
Android - Wi-Fi....................................................................................................................................697
Example............................................................................................................................................698
Android - Widgets.............................................................................................................................703
Widget - XML file...........................................................................................................................704
Widget - Layout file......................................................................................................................704
Widget - Java file...........................................................................................................................704
Widget - Manifest file...................................................................................................................705
Example............................................................................................................................................705
Android - XML Parser.......................................................................................................................712
XML - Elements..............................................................................................................................713
XML - Parsing..................................................................................................................................713
Example............................................................................................................................................715
Android Questions and Answers..................................................................................................720
Android - Useful Resources...........................................................................................................721

13 | P a g e
MOBILE APPLICATION
DEVELOPMENT
 Android is an open source and Linux-based operating system for mobile
devices such as smartphones and tablet computers.
 Android was developed by the Open Handset Alliance, led by Google,
and other companies.
 Android programming is based on Java programming language so if you
have basic understanding on Java programming then it will be a fun to
learn Android application development.

14 | P a g e
Android is an open source and Linux-based Operating System for mobile
devices such as smartphones and tablet computers. Android was developed by
the Open Handset Alliance, led by Google, and other companies.

Android offers a unified approach to application development for mobile devices


which means developers need only develop for Android, and their applications
should be able to run on different devices powered by Android.

The first beta version of the Android Software Development Kit (SDK) was
released by Google in 2007 where as the first commercial version, Android 1.0,
was released in September 2008.

On June 27, 2012, at the Google I/O conference, Google announced the next
Android version, 4.1 Jelly Bean. Jelly Bean is an incremental update, with the
primary aim of improving the user interface, both in terms of functionality and
performance.

The source code for Android is available under free and open source software
licenses. Google publishes most of the code under the Apache License version
2.0 and the rest, Linux kernel changes, under the GNU General Public License
version 2.

Why Android

15 | P a g e
Features of Android
Sr.N
Feature & Description
o.

Beautiful UI
1 Android OS basic screen provides a beautiful and intuitive user
interface.

Connectivity
2 GSM/EDGE, IDEN, CDMA, EV-DO, UMTS, Bluetooth, Wi-Fi, LTE,
NFC and WiMAX.

Storage
3 SQLite, a lightweight relational database, is used for data storage
purposes.

Media support
4 H.263, H.264, MPEG-4 SP, AMR, AMR-WB, AAC, HE-AAC, AAC 5.1,
MP3, MIDI, Ogg Vorbis, WAV, JPEG, PNG, GIF, and BMP.

Messaging
5
SMS and MMS

16 | P a g e
Web browser
6 Based on the open-source WebKit layout engine, coupled with
Chrome's V8 JavaScript engine supporting HTML5 and CSS3.

Multi-touch
7 Android has native support for multi-touch which was initially
made available in handsets such as the HTC Hero.

Multi-tasking
8 User can jump from one task to another and same time various
application can run simultaneously.

Resizable widgets
9 Widgets are resizable, so users can expand them to show more
content or shrink them to save space.

Multi-Language
10
Supports single direction and bi-directional text.

GCM
Google Cloud Messaging (GCM) is a service that lets developers
11
send short message data to their users on Android devices,
without needing a proprietary sync solution.

Wi-Fi Direct
12 A technology that lets apps discover and pair directly, over a
high-bandwidth peer-to-peer connection.

Android Beam
13 A popular NFC-based technology that lets users instantly share,
just by touching two NFC-enabled phones together.

Android Applications

Android applications are usually developed in the Java language using the
Android Software Development Kit.

Once developed, Android applications can be packaged easily and sold out
either through a store such as Google Play, SlideME, Opera Mobile
Store, Mobango, F-droid and the Amazon Appstore.

Android powers hundreds of millions of mobile devices in more than 190


countries around the world. It's the largest installed base of any mobile platform
and growing fast. Every day more than 1 million new Android devices are
activated worldwide.

17 | P a g e
This tutorial has been written with an aim to teach you how to develop and
package Android application. We will start from environment setup for Android
application programming and then drill down to look into various aspects of
Android applications.

Categories of Android applications


There are many android applications in the market.
The top categories are

History of Android
The code names of android ranges from A to N currently, such as Aestro,
Blender, Cupcake, Donut, Eclair, Froyo, Gingerbread, Honeycomb, Ice Cream
Sandwitch, Jelly Bean, KitKat, Lollipop and Marshmallow. Let's understand the
android history in a sequence

18 | P a g e
What is API level?
API Level is an integer value that uniquely identifies the framework API revision
offered by a version of the Android platform.

Platform API
VERSION_CODE
Version Level

Android 6.0 23 MARSHMALLOW

Android 5.1 22 LOLLIPOP_MR1

Android 5.0 21 LOLLIPOP

KitKat for
Android 4.4W 20 KITKAT_WATCH
Wearables Only

Android 4.4 19 KITKAT

Android 4.3 18 JELLY_BEAN_MR2

Android 4.2,
17 JELLY_BEAN_MR1
4.2.2

19 | P a g e
Android 4.1,
16 JELLY_BEAN
4.1.1

Android 4.0.3,
15 ICE_CREAM_SANDWICH_MR1
4.0.4

Android 4.0,
14 ICE_CREAM_SANDWICH
4.0.1, 4.0.2

Android 3.2 13 HONEYCOMB_MR2

Android 3.1.x 12 HONEYCOMB_MR1

Android 3.0.x 11 HONEYCOMB

Android 2.3.4
10 GINGERBREAD_MR1
Android 2.3.3

Android 2.3.2
Android 2.3.1 9 GINGERBREAD
Android 2.3

Android 2.2.x 8 FROYO

Android 2.1.x 7 ECLAIR_MR1

Android 2.0.1 6 ECLAIR_0_1

Android 2.0 5 ECLAIR

Android 1.6 4 DONUT

Android 1.5 3 CUPCAKE

Android 1.1 2 BASE_1_1

Android 1.0 1 BASE

20 | P a g e
Android - Environment Setup

You will be glad to know that you can start your Android application
development on either of the following operating systems −

 Microsoft Windows XP or later version.


 Mac OS X 10.5.8 or later version with Intel chip.
 Linux including GNU C Library 2.7 or later.

Second point is that all the required tools to develop Android applications are
freely available and can be downloaded from the Web. Following is the list of
software's you will need before you start your Android application programming.

 Java JDK5 or later version


 Android Studio

Here last two components are optional and if you are working on Windows
machine then these components make your life easy while doing Java based
application development. So let us have a look how to proceed to set required
environment.

Set-up Java Development Kit (JDK)


You can download the latest version of Java JDK from Oracle's Java site − Java
SE Downloads. You will find instructions for installing JDK in downloaded files,
follow the given instructions to install and configure the setup. Finally set PATH
and JAVA_HOME environment variables to refer to the directory that
contains java and javac, typically java_install_dir/bin and java_install_dir
respectively.

If you are running Windows and installed the JDK in C:\jdk1.8.0_102, you would
have to put the following line in your C:\autoexec.bat file.

21 | P a g e
set PATH=C:\jdk1.8.0_102\bin;%PATH%
set JAVA_HOME=C:\jdk1.8.0_102
Alternatively, you could also right-click on My Computer, select Properties,
then Advanced, then Environment Variables. Then, you would update the PATH
value and press the OK button.
On Linux, if the SDK is installed in /usr/local/jdk1.8.0_102 and you use the C
shell, you would put the following code into your .cshrc file.
setenv PATH /usr/local/jdk1.8.0_102/bin:$PATH
setenv JAVA_HOME /usr/local/jdk1.8.0_102

Alternatively, if you use Android studio, then it will know automatically where
you have installed your Java.

Android IDEs
There are so many sophisticated Technologies are available to develop android
applications, the familiar technologies, which are predominantly using tools as
following:

 Android Studio
 InteliJidea
 Eclipse IDE(Deprecated)

Android - Studio

Step 1 - System Requirements

22 | P a g e
You will be delighted, to know that you can start your Android application
development on either of the following operating systems −

 Microsoft® Windows® 10/8/7/Vista/2003 (32 or 64-bit)


 Mac® OS X® 10.8.5 or higher, up to 10.9 (Mavericks)
 GNOME or KDE desktop

Second point is that all the required tools to develop Android applications are
open source and can be downloaded from the Web. Following is the list of
software's you will need before you start your Android application programming.

 Java JDK5 or later version


 Java Runtime Environment (JRE) 6
 Android Studio

Step 2 - Setup Android Studio

Overview
Android Studio is the official IDE for android application development.It works
based on IntelliJ IDEA, You can download the latest version of android studio
from Android Studio 2.2 Download, If you are new to installing Android Studio on
windows,you will find a file, which is named as android-studio-bundle-
143.3101438-windows.exe.So just download and run on windows machine
according to android studio wizard guideline.
If you are installing Android Studio on Mac or Linux, You can download the latest
version from Android Studio Mac Download,or Android Studio Linux Download,
check the instructions provided along with the downloaded file for Mac OS and
Linux. This tutorial will consider that you are going to setup your environment on
Windows machine having Windows 8.1 operating system.

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

Installation
So let's launch Android Studio.exe,Make sure before launch Android Studio, Our
Machine should required installed Java JDK. To install Java JDK,take a references
of Android environment setup

23 | P a g e
Once you launched Android Studio, its time to mention JDK7 path or later
version in android studio installer.

24 | P a g e
Below the image initiating JDK to android SDK

25 | P a g e
Need to check the components, which are required to create applications, below
the image has selected Android Studio, Android SDK, Android Virtual
Machine and performance(Intel chip).

Need to specify the location of local machine path for Android studio and
Android SDK, below the image has taken default location of windows 8.1 x64 bit
architecture.

26 | P a g e
Need to specify the ram space for Android emulator by default it would take
512MB of local machine RAM.

27 | P a g e
At final stage, it would extract SDK packages into our local machine, it would
take a while time to finish the task and would take 2626MB of Hard disk space.

28 | P a g e
After done all above steps perfectly, you must get finish button and it gonna be
open android studio project with Welcome to android studio message as shown
below

29 | P a g e
You can start your application development by calling start a new android studio
project. in a new installation frame should ask Application name, package
information and location of the project.

30 | P a g e
After entered application name, it going to be called select the form factors your
application runs on, here need to specify Minimum SDK, in our tutorial, I have
declared as API23: Android 6.0(Mashmallow)

31 | P a g e
The next level of installation should contain selecting the activity to mobile, it
specifies the default layout for Applications

At the final stage it going to be open development tool to write the application
code.

Step 3 - Create Android Virtual Device


32 | P a g e
To test your Android applications, you will need a virtual Android device. So
before we start writing our code, let us create an Android virtual device. Launch
Android AVD Manager Clicking AVD_Manager icon as shown below

After Click on a virtual device icon, it going to be shown by default virtual


devices which are present on your SDK, or else need to create a virtual device
by clicking Create new Virtual device button

If your AVD is created successfully it means your environment is ready for


Android application development. If you like, you can close this window using
top-right cross button. Better you re-start your machine and once you are done
with this last step, you are ready to proceed for your first Android example but
before that we will see few more important concepts related to Android
Application Development.

33 | P a g e
Hello Word Example
Before Writing a Hello word code, you must know about XML tags.To write hello
word code, you should redirect to App>res>layout>Activity_main.xml

To show hello word, we need to call text view with layout ( about text view and
layout, you must take references at Relative Layout and Text View ).
<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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView android:text="@string/hello_world"
android:layout_width="550dp"
android:layout_height="wrap_content" />
</RelativeLayout>
Need to run the program by clicking Run>Run App or else need to
call shift+f10key. Finally, result should be placed at Virtual devices as shown
below

34 | P a g e
Android - Architecture
Android operating system is a stack of software components which is roughly
divided into five sections and four main layers as shown below in the
architecture diagram.

35 | P a g e
Linux kernel
At the bottom of the layers is Linux - Linux 3.6 with approximately 115 patches.
This provides a level of abstraction between the device hardware and it
contains all the essential hardware drivers like camera, keypad,
display etc. Also, the kernel handles all the things that Linux is really good at
such as networking and a vast array of device drivers, which take the pain out of
interfacing to peripheral hardware.

Libraries
On top of Linux kernel there is a set of libraries including open-source Web
browser engine WebKit, well known library libc, SQLite database which
is a useful repository for storage and sharing of application data,
libraries to play and record audio and video, SSL libraries responsible
for Internet security etc.

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

36 | P a g e
Android Libraries
This category encompasses those Java-based libraries that are specific to
Android development. Examples of libraries in this category include the
application framework libraries in addition to those that facilitate user interface
building, graphics drawing and database access. A summary of some key core
Android libraries available to the Android developer is as follows −

 android.app − Provides access to the application model and is the cornerstone


of all Android applications.
 android.content − Facilitates content access, publishing and messaging
between applications and application components.
 android.database − Used to access data published by content providers and
includes SQLite database management classes.
 android.opengl − A Java interface to the OpenGL ES 3D graphics rendering
API.
 android.os − Provides applications with access to standard operating system
services including messages, system services and inter-process communication.
 android.text − Used to render and manipulate text on a device display.
 android.view − The fundamental building blocks of application user interfaces.
 android.widget − A rich collection of pre-built user interface components such
as buttons, labels, list views, layout managers, radio buttons etc.
 android.webkit − A set of classes intended to allow web-browsing capabilities
to be built into applications.

Having covered the Java-based core libraries in the Android runtime, it is now
time to turn our attention to the C/C++ based libraries contained in this layer of
the Android software stack.

Android Runtime
This is the third section of the architecture and available on the second layer
from the bottom. This section provides a key component called Dalvik Virtual
Machine which is a kind of Java Virtual Machine specially designed and
optimized for Android.

The Dalvik VM makes use of Linux core features like memory management and
multi-threading, which is intrinsic in the Java language. The Dalvik VM enables
every Android application to run in its own process, with its own instance of the
Dalvik virtual machine.

The Android runtime also provides a set of core libraries which enable Android
application developers to write Android applications using standard Java
programming language.

37 | P a g e
Application Framework
The Application Framework layer provides many higher-level services to
applications in the form of Java classes. Application developers are allowed to
make use of these services in their applications.

The Android framework includes the following key services −

 Activity Manager − Controls all aspects of the application lifecycle and activity
stack.
 Content Providers − Allows applications to publish and share data with other
applications.
 Resource Manager − Provides access to non-code embedded resources such
as strings, color settings and user interface layouts.
 Notifications Manager − Allows applications to display alerts and notifications
to the user.
 View System − An extensible set of views used to create application user
interfaces.

Applications
You will find all the Android application at the top layer. You will write your
application to be installed on this layer only. Examples of such applications are
Contacts Books, Browser, Games etc.

Android - Application Components


Application components are the essential building blocks of an Android
application. These components are loosely coupled by the application manifest
file AndroidManifest.xml that describes each component of the application and
how they interact.

There are following four main components that can be used within an Android
application −

Sr.N
Components & Description
o

Activities
1
They dictate the UI and handle the user interaction to the smart phone screen.

38 | P a g e
Services
2
They handle background processing associated with an application.

Broadcast Receivers
3
They handle communication between Android OS and applications.

Content Providers
4
They handle data and database management issues.

Activities
An activity represents a single screen with a user interface,in-short Activity
performs actions on the screen. For example, an email application might have
one activity that shows a list of new emails, another activity to compose an
email, and another activity for reading emails. If an application has more than
one activity, then one of them should be marked as the activity that is
presented when the application is launched.

An activity is implemented as a subclass of Activity class as follows −

public class MainActivity extends Activity {


}

Services
A service is a component that runs in the background to perform long-running
operations. For example, a service might play music in the background while the
user is in a different application, or it might fetch data over the network without
blocking user interaction with an activity.

A service is implemented as a subclass of Service class as follows −

public class MyService extends Service {


}

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

Broadcast Receivers
Broadcast Receivers simply respond to broadcast messages from other
applications or from the system. For example, applications can also initiate
broadcasts to let other applications know that some data has been downloaded

39 | P a g e
to the device and is available for them to use, so this is broadcast receiver who
will intercept this communication and will initiate appropriate action.

A broadcast receiver is implemented as a subclass of BroadcastReceiver class


and each message is broadcaster as an Intent object.

public class MyReceiver extends BroadcastReceiver {


public void onReceive(context,intent){}
}

Content Providers
A content provider component supplies data from one application to others on
request. Such requests are handled by the methods of
the ContentResolver class. The data may be stored in the file system, the
database or somewhere else entirely.

A content provider is implemented as a subclass of ContentProvider class and


must implement a standard set of APIs that enable other applications to perform
transactions.

public class MyContentProvider extends ContentProvider {


public void onCreate(){}
}

We will go through these tags in detail while covering application components in


individual chapters.

Additional Components
There are additional components which will be used in the construction of above
mentioned entities, their logic, and wiring between them. These components are

S.N
Components & Description
o

Fragments
1
Represents a portion of user interface in an Activity.

Views
2
UI elements that are drawn on-screen including buttons, lists forms etc.

3 Layouts

40 | P a g e
View hierarchies that control screen format and appearance of the views.

Intents
4
Messages wiring components together.

Resources
5
External elements, such as strings, constants and drawable pictures.

Manifest
6
Configuration file for the application.

Android - Hello World Example


Let us start actual programming with Android Framework. Before you start
writing your first example using Android SDK, you have to make sure that you
have set-up your Android development environment properly as explained
in Android - Environment Set-up tutorial. I also assume that you have a little bit
working knowledge with Android studio.

So let us proceed to write a simple Android Application which will print "Hello
World!".

Create Android Application


The first step is to create a simple Android Application using Android studio.
When you click on Android studio icon, it will show screen as shown below

41 | P a g e
You can start your application development by calling start a new android studio
project. in a new installation frame should ask Application name, package
information and location of the project.−

42 | P a g e
After entered application name, it going to be called select the form factors your
application runs on, here need to specify Minimum SDK, in our tutorial, I have
declared as API23: Android 6.0(Mashmallow) −

43 | P a g e
The next level of installation should contain selecting the activity to mobile, it
specifies the default layout for Applications.

At the final stage it going to be open development tool to write the application
code.

Anatomy of Android Application


44 | P a g e
Before you run your app, you should be aware of a few directories and files in
the Android project −

Sr.N
Folder, File & Description
o.

Java
1 This contains the .java source files for your project. By default, it includes
an MainActivity.java source file having an activity class that runs when your
app is launched using the app icon.

2 res/drawable-hdpi
This is a directory for drawable objects that are designed for high-density

45 | P a g e
screens.

3 res/layout
This is a directory for files that define your app's user interface.

res/values
4 This is a directory for other various XML files that contain a collection of
resources, such as strings and colours definitions.

AndroidManifest.xml
5 This is the manifest file which describes the fundamental characteristics of the
app and defines each of its components.

Build.gradle
6 This is an auto generated file which contains compileSdkVersion,
buildToolsVersion, applicationId, minSdkVersion, targetSdkVersion,
versionCode and versionName

Following section will give a brief overview of the important application files.

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

The Main Activity File


The main activity code is a Java file MainActivity.java. This is the actual
application file which ultimately gets converted to a Dalvik executable and runs
your application. Following is the default code generated by the application
wizard for Hello World! application −
package com.example.helloworld;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}

46 | P a g e
Here, R.layout.activity_main refers to the activity_main.xml file located in
the res/layout folder. The onCreate() method is one of many methods that are
figured when an activity is loaded.

The Manifest File


Whatever component you develop as a part of your application, you must
declare all its components in a manifest.xml which resides at the root of the
application project directory. This file works as an interface between Android OS
and your application, so if you do not declare your component in this file, then it
will not be considered by the OS. For example, a default manifest file will look
like as following file −
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tutorialspoint7.myapplication">

<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>
Here <application>...</application> tags enclosed the components related to
the application. Attribute android:icon will point to the application icon available
under res/drawable-hdpi. The application uses the image named ic_launcher.png
located in the drawable folders
The <activity> tag is used to specify an activity and android:name attribute
specifies the fully qualified class name of the Activity subclass and
the android:label attributes specifies a string to use as the label for the activity.
You can specify multiple activities using <activity> tags.
The action for the intent filter is named android.intent.action.MAIN to indicate
that this activity serves as the entry point for the application. The category for
the intent-filter is named android.intent.category.LAUNCHER to indicate that the
application can be launched from the device's launcher icon.
The @string refers to the strings.xml file explained below.
Hence, @string/app_name refers to the app_name string defined in the

47 | P a g e
strings.xml file, which is "HelloWorld". Similar way, other strings get populated
in the application.

Following is the list of tags which you will use in your manifest file to specify
different Android application components −

 <activity>elements for activities


 <service> elements for services
 <receiver> elements for broadcast receivers
 <provider> elements for content providers

The Strings File


The strings.xml file is located in the res/values folder and it contains all the
text that your application uses. For example, the names of buttons, labels,
default text, and similar types of strings go into this file. This file is responsible
for their textual content. For example, a default strings file will look like as
following file −
<resources>
<string name="app_name">HelloWorld</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
<string name="title_activity_main">MainActivity</string>
</resources>

The Layout File


The activity_main.xml is a layout file available in res/layout directory, that is
referenced by your application when building its interface. You will modify this
file very frequently to change the layout of your application. For your "Hello
World!" application, this file will have following content related to default layout

<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" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:padding="@dimen/padding_medium"
android:text="@string/hello_world"
tools:context=".MainActivity" />

48 | P a g e
</RelativeLayout>
This is an example of simple RelativeLayout which we will study in a separate
chapter. The TextView is an Android control used to build the GUI and it have
various attributes like android:layout_width, android:layout_height etc which are
being used to set its width and height etc.. The @string refers to the strings.xml
file located in the res/values folder. Hence, @string/hello_world refers to the
hello string defined in the strings.xml file, which is "Hello World!".

Running the Application


Let's try to run our Hello World! application we just created. I assume you had
created your AVD while doing environment set-up. To run the app from Android
studio, open one of your project's activity files and click Run icon from the tool
bar. Android studio installs the app on your AVD and starts it and if everything is
fine with your set-up and application, it will display following Emulator window −

Congratulations!!! you have developed your first Android Application and now
just keep following rest of the tutorial step by step to become a great Android
Developer. All the very best.

49 | P a g e
Android Resources Organizing & Accessing
here are many more items which you use to build a good Android application.
Apart from coding for the application, you take care of various
other resources like static content that your code uses, such as bitmaps,
colors, layout definitions, user interface strings, animation instructions, and
more. These resources are always maintained separately in various sub-
directories under res/ directory of the project.

This tutorial will explain you how you can organize your application resources,
specify alternative resources and access them in your applications.

Organize resource in Android Studio


MyProject/
app/
manifest/
AndroidManifest.xml
java/
MyActivity.java
res/
drawable/
icon.png
layout/
activity_main.xml
info.xml
values/
strings.xml

Sr.N
Directory & Resource Type
o.

anim/
1 XML files that define property animations. They are saved in res/anim/ folder
and accessed from the R.anim class.

color/
2 XML files that define a state list of colors. They are saved in res/color/ and
accessed from the R.color class.

3 drawable/

50 | P a g e
Image files like .png, .jpg, .gif or XML files that are compiled into bitmaps,
state lists, shapes, animation drawable. They are saved in res/drawable/ and
accessed from the R.drawable class.

layout/
4 XML files that define a user interface layout. They are saved in res/layout/ and
accessed from the R.layout class.

menu/
5 XML files that define application menus, such as an Options Menu, Context
Menu, or Sub Menu. They are saved in res/menu/ and accessed from
the R.menu class.

raw/
6 Arbitrary files to save in their raw form. You need to
call Resources.openRawResource() with the resource ID, which
is R.raw.filename to open such raw files.

values/
XML files that contain simple values, such as strings, integers, and colors. For
example, here are some filename conventions for resources you can create in
this directory −
 arrays.xml for resource arrays, and accessed from the R.array class.
 integers.xml for resource integers, and accessed from
7 the R.integer class.
 bools.xml for resource boolean, and accessed from the R.bool class.
 colors.xml for color values, and accessed from the R.color class.
 dimens.xml for dimension values, and accessed from
the R.dimen class.
 strings.xml for string values, and accessed from the R.string class.
 styles.xml for styles, and accessed from the R.style class.

xml/
8 Arbitrary XML files that can be read at runtime by
calling Resources.getXML(). You can save various configuration files here
which will be used at run time.

Alternative Resources
Your application should provide alternative resources to support specific device
configurations. For example, you should include alternative drawable resources (
i.e.images ) for different screen resolution and alternative string resources for
different languages. At runtime, Android detects the current device
configuration and loads the appropriate resources for your application.

51 | P a g e
To specify configuration-specific alternatives for a set of resources, follow the
following steps −

 Create a new directory in res/ named in the form <resources_name>-


<config_qualifier>. Here resources_name will be any of the resources
mentioned in the above table, like layout, drawable etc. The qualifier will
specify an individual configuration for which these resources are to be used. You
can check official documentation for a complete list of qualifiers for different
type of resources.
 Save the respective alternative resources in this new directory. The resource
files must be named exactly the same as the default resource files as shown in
the below example, but these files will have content specific to the alternative.
For example though image file name will be same but for high resolution screen,
its resolution will be high.

Below is an example which specifies images for a default screen and alternative
images for high resolution screen.

MyProject/
app/
manifest/
AndroidManifest.xml
java/
MyActivity.java
res/
drawable/
icon.png
background.png
drawable-hdpi/
icon.png
background.png
layout/
activity_main.xml
info.xml
values/
strings.xml

Below is another example which specifies layout for a default language and
alternative layout for Arabic language.

MyProject/

52 | P a g e
app/
manifest/
AndroidManifest.xml
java/
MyActivity.java
res/
drawable/
icon.png
background.png
drawable-hdpi/
icon.png
background.png
layout/
activity_main.xml
info.xml
layout-ar/
main.xml
values/
strings.xml

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

Accessing Resources
During your application development you will need to access defined resources
either in your code, or in your layout XML files. Following section explains how to
access your resources in both the scenarios −

Accessing Resources in Code


When your Android application is compiled, a R class gets generated, which
contains resource IDs for all the resources available in your res/ directory. You
can use R class to access that resource using sub-directory and resource name
or directly resource ID.

Example
To access res/drawable/myimage.png and set an ImageView you will use
following code −

53 | P a g e
ImageView imageView = (ImageView) findViewById(R.id.myimageview);
imageView.setImageResource(R.drawable.myimage);
Here first line of the code make use of R.id.myimageview to get ImageView
defined with id myimageview in a Layout file. Second line of code makes use
of R.drawable.myimage to get an image with name myimage available in
drawable sub-directory under /res.

Example
Consider next example where res/values/strings.xml has following definition −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello, World!</string>
</resources>

Now you can set the text on a TextView object with ID msg using a resource ID
as follows −

TextView msgTextView = (TextView) findViewById(R.id.msg);


msgTextView.setText(R.string.hello);

Example
Consider a layout res/layout/activity_main.xml with the following definition −
<?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" >

<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a TextView" />

<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a Button" />

</LinearLayout>

This application code will load this layout for an Activity, in the onCreate()
method as follows −

public void onCreate(Bundle savedInstanceState) {


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

54 | P a g e
}

Accessing Resources in XML


Consider the following resource XML res/values/strings.xml file that includes a
color resource and a string resource −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="opaque_red">#f00</color>
<string name="hello">Hello!</string>
</resources>

Now you can use these resources in the following layout file to set the text color
and text string as follows −

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


<EditText
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textColor="@color/opaque_red"
android:text="@string/hello" />
Now if you will go through previous chapter once again where I have
explained Hello World! example, and I'm sure you will have better
understanding on all the concepts explained in this chapter. So I highly
recommend to check previous chapter for working example and check how I
have used various resources at very basic level.
Android - Activities
An activity represents a single screen with a user interface just like window or
frame of Java.Android activity is the subclass of ContextThemeWrapper class.

If you have worked with C, C++ or Java programming language then you must
have seen that your program starts from main() function. Very similar way,
Android system initiates its program with in an Activity starting with a call
on onCreate() callback method. There is a sequence of callback methods that
start up an activity and a sequence of callback methods that tear down an
activity as shown in the below Activity life cycle diagram: (image courtesy :
android.com )

55 | P a g e
The Activity class defines the following call backs i.e. events. You don't need to
implement all the callbacks methods. However, it's important that you
understand each one and implement those that ensure your app behaves the
way users expect.

Sr.N
Callback & Description
o

1 onCreate()

56 | P a g e
This is the first callback and called when the activity is first created.

onStart()
2
This callback is called when the activity becomes visible to the user.

onResume()
3
This is called when the user starts interacting with the application.

onPause()
The paused activity does not receive user input and cannot execute any code
4
and called when the current activity is being paused and the previous activity is
being resumed.

onStop()
5
This callback is called when the activity is no longer visible.

onDestroy()
6
This callback is called before the activity is destroyed by the system.

onRestart()
7
This callback is called when the activity restarts after stopping it.

Example
This example will take you through simple steps to show Android application
activity life cycle. Follow the following steps to modify the Android application
we created in Hello World Example chapter −

Ste
Description
p

You will use Android studio to create an Android application and name it
1 as HelloWorld under a package com.example.helloworld as explained in
the Hello World Example chapter.

Modify main activity file MainActivity.java as explained below. Keep rest of the
2
files unchanged.

Run the application to launch Android emulator and verify the result of the
3
changes done in the application.

Following is the content of the modified main activity


file src/com.example.helloworld/MainActivity.java. This file includes each
of the fundamental life cycle methods. The Log.d() method has been used to
generate log messages −

57 | P a g e
package com.example.helloworld;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;

public class MainActivity extends Activity {


String msg = "Android : ";

/** Called when the activity is first created. */


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(msg, "The onCreate() event");
}

/** Called when the activity is about to become visible. */


@Override
protected void onStart() {
super.onStart();
Log.d(msg, "The onStart() event");
}

/** Called when the activity has become visible. */


@Override
protected void onResume() {
super.onResume();
Log.d(msg, "The onResume() event");
}

/** Called when another activity is taking focus. */


@Override
protected void onPause() {
super.onPause();
Log.d(msg, "The onPause() event");
}

/** Called when the activity is no longer visible. */


@Override
protected void onStop() {
super.onStop();
Log.d(msg, "The onStop() event");
}

/** Called just before the activity is destroyed. */


@Override
public void onDestroy() {

58 | P a g e
super.onDestroy();
Log.d(msg, "The onDestroy() event");
}
}

An activity class loads all the UI component using the XML file available
in res/layout folder of the project. Following statement loads UI components
from res/layout/activity_main.xml file:

setContentView(R.layout.activity_main);

An application can have one or more activities without any restrictions. Every
activity you define for your application must be declared in
your AndroidManifest.xml file and the main activity for your app must be
declared in the manifest with an <intent-filter> that includes the MAIN action
and LAUNCHER category as follows:

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


<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tutorialspoint7.myapplication">

<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>

If either the MAIN action or LAUNCHER category are not declared for one of your
activities, then your app icon will not appear in the Home screen's list of apps.

Let's try to run our modified Hello World! application we just modified. I
assume you had created your AVD while doing environment setup. To run the
app from Android studio, open one of your project's activity files and click Run

59 | P a g e
icon from the toolbar. Android studio installs the app on your AVD and starts it
and if everything is fine with your setup and application, it will display Emulator
window and you should see following log messages in LogCat window in
Android studio −

08-23 10:32:07.682 4480-4480/com.example.helloworld D/Android :: The


onCreate() event
08-23 10:32:07.683 4480-4480/com.example.helloworld D/Android :: The
onStart() event
08-23 10:32:07.685 4480-4480/com.example.helloworld D/Android :: The
onResume() event

Let us try to click lock screen button on the Android emulator and it will
generate following events messages in LogCat window in android studio:

08-23 10:32:53.230 4480-4480/com.example.helloworld D/Android :: The


onPause() event
08-23 10:32:53.294 4480-4480/com.example.helloworld D/Android :: The
onStop() event

Let us again try to unlock your screen on the Android emulator and it will
generate following events messages in LogCat window in Android studio:

08-23 10:34:41.390 4480-4480/com.example.helloworld D/Android :: The


onStart() event
08-23 10:34:41.392 4480-4480/com.example.helloworld D/Android :: The
onResume() event

Next, let us again try to click Back button on the Android emulator and it will
generate following events messages in LogCat window in Android studio and
this completes the Activity Life Cycle for an Android Application.

08-23 10:37:24.806 4480-4480/com.example.helloworld D/Android ::


The onPause() event
08-23 10:37:25.668 4480-4480/com.example.helloworld D/Android ::
The onStop() event

60 | P a g e
08-23 10:37:25.669 4480-4480/com.example.helloworld D/Android ::
The onDestroy() event

Android - Services
A service is a component that runs in the background to perform long-running
operations without needing to interact with the user and it works even if
application is destroyed. A service can essentially take two states −

Sr.N
State & Description
o.

Started
A service is started when an application component, such as an activity,
1
starts it by calling startService(). Once started, a service can run in the
background indefinitely, even if the component that started it is destroyed.

Bound
A service is bound when an application component binds to it by
2 calling bindService(). A bound service offers a client-server interface that
allows components to interact with the service, send requests, get results, and
even do so across processes with interprocess communication (IPC).

A service has life cycle callback methods that you can implement to monitor
changes in the service's state and you can perform work at the appropriate
stage. The following diagram on the left shows the life cycle when the service is
created with startService() and the diagram on the right shows the life cycle
when the service is created with bindService(): (image courtesy : android.com )

61 | P a g e
To create an service, you create a Java class that extends the Service base class
or one of its existing subclasses. The Service base class defines various
callback methods and the most important are given below. You don't need to
implement all the callbacks methods. However, it's important that you
understand each one and implement those that ensure your app behaves the
way users expect.

Sr.N
Callback & Description
o.

onStartCommand()
The system calls this method when another component, such as an activity,
1 requests that the service be started, by calling startService(). If you implement
this method, it is your responsibility to stop the service when its work is done,
by calling stopSelf() or stopService() methods.

62 | P a g e
onBind()
The system calls this method when another component wants to bind with the
service by calling bindService(). If you implement this method, you must
2
provide an interface that clients use to communicate with the service, by
returning an IBinder object. You must always implement this method, but if
you don't want to allow binding, then you should return null.

onUnbind()
3 The system calls this method when all clients have disconnected from a
particular interface published by the service.

onRebind()
The system calls this method when new clients have connected to the service,
4
after it had previously been notified that all had disconnected in
its onUnbind(Intent).

onCreate()
The system calls this method when the service is first created
5
using onStartCommand() or onBind(). This call is required to perform one-
time set-up.

onDestroy()
The system calls this method when the service is no longer used and is being
6
destroyed. Your service should implement this to clean up any resources such
as threads, registered listeners, receivers, etc.

The following skeleton service demonstrates each of the life cycle methods −

package com.tutorialspoint;

import android.app.Service;
import android.os.IBinder;
import android.content.Intent;
import android.os.Bundle;

public class HelloService extends Service {

/** indicates how to behave if the service is killed */


int mStartMode;

/** interface for clients that bind */


IBinder mBinder;

/** indicates whether onRebind should be used */


boolean mAllowRebind;

/** Called when the service is being created. */

63 | P a g e
@Override
public void onCreate() {

/** The service is starting, due to a call to startService() */


@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
return mStartMode;
}

/** A client is binding to the service with bindService() */


@Override
public IBinder onBind(Intent intent) {
return mBinder;
}

/** Called when all clients have unbound with unbindService() */


@Override
public boolean onUnbind(Intent intent) {
return mAllowRebind;
}

/** Called when a client is binding to the service with


bindService()*/
@Override
public void onRebind(Intent intent) {

/** Called when The service is no longer used and is being


destroyed */
@Override
public void onDestroy() {

}
}

Example
This example will take you through simple steps to show how to create your own
Android Service. Follow the following steps to modify the Android application we
created in Hello World Example chapter −

Ste
Description
p

64 | P a g e
You will use Android StudioIDE to create an Android application and name it
as My Application under a
1
package com.example.tutorialspoint7.myapplication as explained in the Hello
World Example chapter.

Modify main activity file MainActivity.java to


2
add startService() and stopService() methods.

Create a new java file MyService.java under the package com.example.My


3 Application. This file will have implementation of Android service related
methods.

Define your service in AndroidManifest.xml file using <service.../> tag. An


4
application can have one or more services without any restrictions.

Modify the default content of res/layout/activity_main.xml file to include two


5
buttons in linear layout.

No need to change any constants in res/values/strings.xml file. Android studio


6
take care of string values

Run the application to launch Android emulator and verify the result of the
7
changes done in the application.

Following is the content of the modified main activity file MainActivity.java.


This file can include each of the fundamental life cycle methods. We have
added startService() and stopService() methods to start and stop the service.

package com.example.tutorialspoint7.myapplication;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.View;

public class MainActivity extends Activity {


String msg = "Android : ";

/** Called when the activity is first created. */


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

65 | P a g e
Log.d(msg, "The onCreate() event");
}

public void startService(View view) {


startService(new Intent(getBaseContext(), MyService.class));
}

// Method to stop the service


public void stopService(View view) {
stopService(new Intent(getBaseContext(), MyService.class));
}
}

Following is the content of MyService.java. This file can have implementation


of one or more methods associated with Service based on requirements. For
now we are going to implement only two
methods onStartCommand() and onDestroy() −

package com.example.tutorialspoint7.myapplication;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.widget.Toast;

/**
* Created by TutorialsPoint7 on 8/23/2016.
*/

public class MyService extends Service {


@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
// Let it continue running until it is stopped.
Toast.makeText(this, "Service Started",
Toast.LENGTH_LONG).show();
return START_STICKY;
}

@Override
public void onDestroy() {

66 | P a g e
super.onDestroy();
Toast.makeText(this, "Service Destroyed",
Toast.LENGTH_LONG).show();
}
}

Following will the modified content of AndroidManifest.xml file. Here we have


added <service.../> tag to include our service −

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


<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tutorialspoint7.myapplication">

<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>

<service android:name=".MyService" />


</application>

</manifest>

Following will be the content of res/layout/activity_main.xml file to include


two buttons −

<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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"

67 | P a g e
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Example of services"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point "
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_above="@+id/imageButton"
android:layout_centerHorizontal="true"
android:layout_marginBottom="40dp" />

<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/abc"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button2"
android:text="Start Services"
android:onClick="startService"
android:layout_below="@+id/imageButton"
android:layout_centerHorizontal="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stop Services"
android:id="@+id/button"
android:onClick="stopService"
android:layout_below="@+id/button2"
android:layout_alignLeft="@+id/button2"
android:layout_alignStart="@+id/button2"

68 | P a g e
android:layout_alignRight="@+id/button2"
android:layout_alignEnd="@+id/button2" />

</RelativeLayout>

Let's try to run our modified Hello World! application we just modified. I
assume you had created your AVD while doing environment setup. To run the
app from Android studio, open one of your project's activity files and click Run
icon from the tool bar. Android Studio installs the app on your AVD and starts it
and if everything is fine with your set-up and application, it will display following
Emulator window −

69 | P a g e
Now to start your service, let's click on Start Service button, this will start the
service and as per our programming in onStartCommand() method, a
message Service Started will appear on the bottom of the the simulator as
follows −

To stop the service, you can click the Stop Service button.

Android - Broadcast Receivers


Broadcast Receivers simply respond to broadcast messages from other
applications or from the system itself. These messages are sometime called
events or intents. For example, applications can also initiate broadcasts to let

70 | P a g e
other applications know that some data has been downloaded to the device and
is available for them to use, so this is broadcast receiver who will intercept this
communication and will initiate appropriate action.

There are following two important steps to make BroadcastReceiver works for
the system broadcasted intents −

 Creating the Broadcast Receiver.


 Registering Broadcast Receiver

There is one additional steps in case you are going to implement your custom
intents then you will have to create and broadcast those intents.

Creating the Broadcast Receiver


A broadcast receiver is implemented as a subclass of BroadcastReceiver class
and overriding the onReceive() method where each message is received as
a Intent object parameter.
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Intent Detected.",
Toast.LENGTH_LONG).show();
}
}

Registering Broadcast Receiver


An application listens for specific broadcast intents by registering a broadcast
receiver in AndroidManifest.xml file. Consider we are going to
register MyReceiver for system generated event ACTION_BOOT_COMPLETED
which is fired by the system once the Android system has completed the boot
process.

71 | P a g e
Broadcast-Receiver
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<receiver android:name="MyReceiver">

<intent-filter>
<action
android:name="android.intent.action.BOOT_COMPLETED">
</action>
</intent-filter>

</receiver>
</application>
Now whenever your Android device gets booted, it will be intercepted by
BroadcastReceiver MyReceiver and implemented logic inside onReceive() will be
executed.
There are several system generated events defined as final static fields in
the Intent class. The following table lists a few important system events.
Sr.N
Event Constant & Description
o

android.intent.action.BATTERY_CHANGED
1 Sticky broadcast containing the charging state, level, and other information
about the battery.

2 android.intent.action.BATTERY_LOW
Indicates low battery condition on the device.

72 | P a g e
3 android.intent.action.BATTERY_OKAY
Indicates the battery is now okay after being low.

4 android.intent.action.BOOT_COMPLETED
This is broadcast once, after the system has finished booting.

5 android.intent.action.BUG_REPORT
Show activity for reporting a bug.

6 android.intent.action.CALL
Perform a call to someone specified by the data.

android.intent.action.CALL_BUTTON
7 The user pressed the "call" button to go to the dialer or other appropriate UI for
placing a call.

8 android.intent.action.DATE_CHANGED
The date has changed.

9 android.intent.action.REBOOT
Have the device reboot.

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

Broadcasting Custom Intents


If you want your application itself should generate and send custom intents then
you will have to create and send those intents by using
the sendBroadcast() method inside your activity class. If you use
the sendStickyBroadcast(Intent) method, the Intent is sticky, meaning
the Intent you are sending stays around after the broadcast is complete.
public void broadcastIntent(View view) {
Intent intent = new Intent();
intent.setAction("com.tutorialspoint.CUSTOM_INTENT");
sendBroadcast(intent);
}
This intent com.tutorialspoint.CUSTOM_INTENT can also be registered in similar
way as we have regsitered system generated intent.
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<receiver android:name="MyReceiver">

73 | P a g e
<intent-filter>
<action android:name="com.tutorialspoint.CUSTOM_INTENT">
</action>
</intent-filter>

</receiver>
</application>

Example
This example will explain you how to create BroadcastReceiver to intercept
custom intent. Once you are familiar with custom intent, then you can program
your application to intercept system generated intents. So let's follow the
following steps to modify the Android application we created in Hello World
Example chapter −
Ste
Description
p

You will use Android studio to create an Android application and name it as My
1 Application under a package com.example.tutorialspoint7.myapplication as explained
in the Hello World Example chapter.

2 Modify main activity file MainActivity.java to add broadcastIntent() method.

Create a new java file called MyReceiver.java under the


3
package com.example.tutorialspoint7.myapplication to define a BroadcastReceiver.

An application can handle one or more custom and system intents without any
4 restrictions. Every intent you want to intercept must be registered in
your AndroidManifest.xml file using <receiver.../> tag

Modify the default content of res/layout/activity_main.xml file to include a button to


5
broadcast intent.

6 No need to modify the string file, Android studio take care of string.xml file.

Run the application to launch Android emulator and verify the result of the changes
7
done in the application.

74 | P a g e
Following is the content of the modified main activity file MainActivity.java.
This file can include each of the fundamental life cycle methods. We have
added broadcastIntent() method to broadcast a custom intent.
package com.example.tutorialspoint7.myapplication;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends Activity {

/** Called when the activity is first created. */


@Override

public void onCreate(Bundle savedInstanceState) {


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

// broadcast a custom intent.

public void broadcastIntent(View view){


Intent intent = new Intent();
intent.setAction("com.tutorialspoint.CUSTOM_INTENT");
sendBroadcast(intent);
}
}
Following is the content of MyReceiver.java:
package com.example.tutorialspoint7.myapplication;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

/**
* Created by TutorialsPoint7 on 8/23/2016.
*/
public class MyReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Intent Detected.",
Toast.LENGTH_LONG).show();
}
}

75 | P a g e
Following will the modified content of AndroidManifest.xml file. Here we have
added <receiver.../> tag to include our service:
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tutorialspoint7.myapplication">

<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="MyReceiver">
<intent-filter>
<action
android:name="com.tutorialspoint.CUSTOM_INTENT">
</action>
</intent-filter>

</receiver>
</application>

</manifest>
Following will be the content of res/layout/activity_main.xml file to include a
button to broadcast our custom intent −
<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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView
android:id="@+id/textView1"

76 | P a g e
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Example of Broadcast"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point "
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_above="@+id/imageButton"
android:layout_centerHorizontal="true"
android:layout_marginBottom="40dp" />

<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/abc"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button2"
android:text="Broadcast Intent"
android:onClick="broadcastIntent"
android:layout_below="@+id/imageButton"
android:layout_centerHorizontal="true" />

</RelativeLayout>
Let's try to run our modified Hello World! application we just modified. I
assume you had created your AVD while doing environment set-up. To run the
app from Android studio, open one of your project's activity files and click Run
icon from the tool bar. Android Studio installs the app on your AVD and starts it
and if everything is fine with your set-up and application, it will display following
Emulator window −

77 | P a g e
Now to broadcast our custom intent, let's click on Broadcast Intent button,
this will broadcast our custom
intent "com.tutorialspoint.CUSTOM_INTENT" which will be intercepted by our
registered BroadcastReceiver i.e. MyReceiver and as per our implemented logic
a toast will appear on the bottom of the the simulator as follows −

78 | P a g e
You can try implementing other BroadcastReceiver to intercept system
generated intents like system boot up, date changed, low battery etc.

Android - Content Providers


A content provider component supplies data from one application to others on
request. Such requests are handled by the methods of the ContentResolver
class. A content provider can use different ways to store its data and the data
can be stored in a database, in files, or even over a network.

79 | P a g e
ContentProvider
sometimes it is required to share data across applications. This is
where content providers become very useful.
Content providers let you centralize content in one place and have many
different applications access it as needed. A content provider behaves very
much like a database where you can query it, edit its content, as well as add or
delete content using insert(), update(), delete(), and query() methods. In most
cases this data is stored in an SQlite database.
A content provider is implemented as a subclass of ContentProvider class and
must implement a standard set of APIs that enable other applications to perform
transactions.
public class My Application extends ContentProvider {
}

Content URIs
To query a content provider, you specify the query string in the form of a URI
which has following format −

<prefix>://<authority>/<data_type>/<id>

Here is the detail of various parts of the URI −

Sr.N
Part & Description
o

80 | P a g e
1 prefix
This is always set to content://

authority
2 This specifies the name of the content provider, for
example contacts, browser etc. For third-party content providers, this could be
the fully qualified name, such as com.tutorialspoint.statusprovider

data_type
This indicates the type of data that this particular provider provides. For
3 example, if you are getting all the contacts from the Contacts content provider,
then the data path would be people and URI would look like
thiscontent://contacts/people

id
4 This specifies the specific record requested. For example, if you are looking for
contact number 5 in the Contacts content provider then URI would look like
this content://contacts/people/5.

Create Content Provider


This involves number of simple steps to create your own content provider.

 First of all you need to create a Content Provider class that extends
the ContentProviderbaseclass.
 Second, you need to define your content provider URI address which will be
used to access the content.
 Next you will need to create your own database to keep the content. Usually,
Android uses SQLite database and framework needs to
override onCreate() method which will use SQLite Open Helper method to create
or open the provider's database. When your application is launched,
the onCreate() handler of each of its Content Providers is called on the main
application thread.
 Next you will have to implement Content Provider queries to perform different
database specific operations.
 Finally register your Content Provider in your activity file using <provider> tag.

Here is the list of methods which you need to override in Content Provider class
to have your Content Provider working −

81 | P a g e
ContentProvider
 onCreate() This method is called when the provider is started.
 query() This method receives a request from a client. The result is returned as
a Cursor object.
 insert()This method inserts a new record into the content provider.
 delete() This method deletes an existing record from the content provider.
 update() This method updates an existing record from the content provider.
 getType() This method returns the MIME type of the data at the given URI.

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

Example
This example will explain you how to create your own ContentProvider. So let's
follow the following steps to similar to what we followed while creating Hello
World Example−
Ste
Description
p

You will use Android StudioIDE to create an Android application and name it as My
1
Application under a package com.example.MyApplication, with blank Activity.

Modify main activity file MainActivity.java to add two new


2
methods onClickAddName() and onClickRetrieveStudents().

3 Create a new java file called StudentsProvider.java under the


package com.example.MyApplication to define your actual provider and associated

82 | P a g e
methods.

4 Register your content provider in your AndroidManifest.xml file using <provider.../> tag

Modify the default content of res/layout/activity_main.xml file to include a small GUI


5
to add students records.

6 No need to change string.xml.Android studio take care of string.xml file.

Run the application to launch Android emulator and verify the result of the changes
7
done in the application.

Following is the content of the modified main activity


file src/com.example.MyApplication/MainActivity.java. This file can include
each of the fundamental life cycle methods. We have added two new
methods onClickAddName() and onClickRetrieveStudents() to handle user
interaction with the application.
package com.example.MyApplication;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;

import android.content.ContentValues;
import android.content.CursorLoader;

import android.database.Cursor;

import android.view.Menu;
import android.view.View;

import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClickAddName(View view) {
// Add a new student record
ContentValues values = new ContentValues();
values.put(StudentsProvider.NAME,

83 | P a g e
((EditText)findViewById(R.id.editText2)).getText().toString());

values.put(StudentsProvider.GRADE,

((EditText)findViewById(R.id.editText3)).getText().toString());

Uri uri = getContentResolver().insert(


StudentsProvider.CONTENT_URI, values);

Toast.makeText(getBaseContext(),
uri.toString(), Toast.LENGTH_LONG).show();
}
public void onClickRetrieveStudents(View view) {
// Retrieve student records
String URL =
"content://com.example.MyApplication.StudentsProvider";

Uri students = Uri.parse(URL);


Cursor c = managedQuery(students, null, null, null, "name");

if (c.moveToFirst()) {
do{
Toast.makeText(this,
c.getString(c.getColumnIndex(StudentsProvider._ID))
+
", " + c.getString(c.getColumnIndex(
StudentsProvider.NAME)) +
", " + c.getString(c.getColumnIndex(
StudentsProvider.GRADE)),
Toast.LENGTH_SHORT).show();
} while (c.moveToNext());
}
}
}
Create new file StudentsProvider.java
under com.example.MyApplication package and following is the content
of src/com.example.MyApplication/StudentsProvider.java −
package com.example.MyApplication;

import java.util.HashMap;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;

84 | P a g e
import android.database.Cursor;
import android.database.SQLException;

import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;

import android.net.Uri;
import android.text.TextUtils;

public class StudentsProvider extends ContentProvider {


static final String PROVIDER_NAME =
"com.example.MyApplication.StudentsProvider";
static final String URL = "content://" + PROVIDER_NAME +
"/students";
static final Uri CONTENT_URI = Uri.parse(URL);

static final String _ID = "_id";


static final String NAME = "name";
static final String GRADE = "grade";

private static HashMap<String, String> STUDENTS_PROJECTION_MAP;

static final int STUDENTS = 1;


static final int STUDENT_ID = 2;

static final UriMatcher uriMatcher;


static{
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(PROVIDER_NAME, "students", STUDENTS);
uriMatcher.addURI(PROVIDER_NAME, "students/#", STUDENT_ID);
}

/**
* Database specific constant declarations
*/

private SQLiteDatabase db;


static final String DATABASE_NAME = "College";
static final String STUDENTS_TABLE_NAME = "students";
static final int DATABASE_VERSION = 1;
static final String CREATE_DB_TABLE =
" CREATE TABLE " + STUDENTS_TABLE_NAME +
" (_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
" name TEXT NOT NULL, " +
" grade TEXT NOT NULL);";

/**
* Helper class that actually creates and manages

85 | P a g e
* the provider's underlying data repository.
*/

private static class DatabaseHelper extends SQLiteOpenHelper {


DatabaseHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_DB_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
db.execSQL("DROP TABLE IF EXISTS " +
STUDENTS_TABLE_NAME);
onCreate(db);
}
}

@Override
public boolean onCreate() {
Context context = getContext();
DatabaseHelper dbHelper = new DatabaseHelper(context);

/**
* Create a write able database which will trigger its
* creation if it doesn't already exist.
*/

db = dbHelper.getWritableDatabase();
return (db == null)? false:true;
}

@Override
public Uri insert(Uri uri, ContentValues values) {
/**
* Add a new student record
*/
long rowID = db.insert( STUDENTS_TABLE_NAME, "", values);

/**
* If record is added successfully
*/
if (rowID > 0) {
Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID);

86 | P a g e
getContext().getContentResolver().notifyChange(_uri,
null);
return _uri;
}

throw new SQLException("Failed to add a record into " + uri);


}

@Override
public Cursor query(Uri uri, String[] projection,
String selection,String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(STUDENTS_TABLE_NAME);

switch (uriMatcher.match(uri)) {
case STUDENTS:
qb.setProjectionMap(STUDENTS_PROJECTION_MAP);
break;

case STUDENT_ID:
qb.appendWhere( _ID + "=" +
uri.getPathSegments().get(1));
break;

default:
}

if (sortOrder == null || sortOrder == ""){


/**
* By default sort on student names
*/
sortOrder = NAME;
}

Cursor c = qb.query(db, projection, selection,


selectionArgs,null, null, sortOrder);
/**
* register to watch a content URI for changes
*/
c.setNotificationUri(getContext().getContentResolver(), uri);
return c;
}

@Override
public int delete(Uri uri, String selection, String[]
selectionArgs) {
int count = 0;
switch (uriMatcher.match(uri)){
case STUDENTS:

87 | P a g e
count = db.delete(STUDENTS_TABLE_NAME, selection,
selectionArgs);
break;

case STUDENT_ID:
String id = uri.getPathSegments().get(1);
count = db.delete( STUDENTS_TABLE_NAME, _ID + " = " +
id +
(!TextUtils.isEmpty(selection) ? "
AND (" + selection + ')' : ""), selectionArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI " +
uri);
}

getContext().getContentResolver().notifyChange(uri, null);
return count;
}

@Override
public int update(Uri uri, ContentValues values,
String selection, String[] selectionArgs) {
int count = 0;
switch (uriMatcher.match(uri)) {
case STUDENTS:
count = db.update(STUDENTS_TABLE_NAME, values,
selection, selectionArgs);
break;

case STUDENT_ID:
count = db.update(STUDENTS_TABLE_NAME, values,
_ID + " = " + uri.getPathSegments().get(1) +
(!TextUtils.isEmpty(selection) ? "
AND (" +selection + ')' : ""), selectionArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri
);
}

getContext().getContentResolver().notifyChange(uri, null);
return count;
}

@Override
public String getType(Uri uri) {
switch (uriMatcher.match(uri)){
/**

88 | P a g e
* Get all student records
*/
case STUDENTS:
return "vnd.android.cursor.dir/vnd.example.students";
/**
* Get a particular student
*/
case STUDENT_ID:
return "vnd.android.cursor.item/vnd.example.students";
default:
throw new IllegalArgumentException("Unsupported URI: "
+ uri);
}
}
}
Following will the modified content of AndroidManifest.xml file. Here we have
added <provider.../> tag to include our content provider:
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.MyApplication">

<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>

<provider android:name="StudentsProvider"

android:authorities="com.example.MyApplication.StudentsProvider"/>
</application>
</manifest>
Following will be the content of res/layout/activity_main.xml file−
<?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"

89 | P a g e
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.MyApplication.MainActivity">

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Content provider"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point "
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true" />

<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/abc"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button2"
android:text="Add Name"
android:layout_below="@+id/editText3"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2"
android:layout_alignLeft="@+id/textView2"
android:layout_alignStart="@+id/textView2"
android:onClick="onClickAddName"/>

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"

90 | P a g e
android:layout_below="@+id/imageButton"
android:layout_alignRight="@+id/imageButton"
android:layout_alignEnd="@+id/imageButton" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText2"
android:layout_alignTop="@+id/editText"
android:layout_alignLeft="@+id/textView1"
android:layout_alignStart="@+id/textView1"
android:layout_alignRight="@+id/textView1"
android:layout_alignEnd="@+id/textView1"
android:hint="Name"
android:textColorHint="@android:color/holo_blue_light" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText3"
android:layout_below="@+id/editText"
android:layout_alignLeft="@+id/editText2"
android:layout_alignStart="@+id/editText2"
android:layout_alignRight="@+id/editText2"
android:layout_alignEnd="@+id/editText2"
android:hint="Grade"
android:textColorHint="@android:color/holo_blue_bright" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Retrive student"
android:id="@+id/button"
android:layout_below="@+id/button2"
android:layout_alignRight="@+id/editText3"
android:layout_alignEnd="@+id/editText3"
android:layout_alignLeft="@+id/button2"
android:layout_alignStart="@+id/button2"
android:onClick="onClickRetrieveStudents"/>
</RelativeLayout>
Make sure you have following content of res/values/strings.xml file:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">My Application</string>
</resources>;
Let's try to run our modified My Application application we just created. I
assume you had created your AVD while doing environment set-up. To run the
app from Android Studio IDE, open one of your project's activity files and click

91 | P a g e
Run icon from the tool bar. Android Studio installs the app on your AVD and
starts it and if everything is fine with your set-up and application, it will display
following Emulator window, be patience because it may take sometime based
on your computer speed −

Now let's enter student Name and Grade and finally click on Add
Name button, this will add student record in the database and will flash a
message at the bottom showing ContentProvider URI along with record number
added in the database. This operation makes use of our insert() method. Let's
repeat this process to add few more students in the database of our content
provider.

92 | P a g e
Once you are done with adding records in the database, now its time to ask
ContentProvider to give us those records back, so let's click Retrieve
Students button which will fetch and display all the records one by one which is
as per our the implementation of our query() method.
You can write activities against update and delete operations by providing
callback functions in MainActivity.java file and then modify user interface to
have buttons for update and deleted operations in the same way as we have
done for add and read operations.

This way you can use existing Content Provider like Address Book or you can use
Content Provider concept in developing nice database oriented applications
where you can perform all sort of database operations like read, write, update
and delete as explained above in the example.

93 | P a g e
Android - Fragments
A Fragment is a piece of an activity which enable more modular activity
design. It will not be wrong if we say, a fragment is a kind of sub-activity.

Following are important points about fragment −

 A fragment has its own layout and its own behaviour with its own life cycle
callbacks.
 You can add or remove fragments in an activity while the activity is running.
 You can combine multiple fragments in a single activity to build a multi-pane UI.
 A fragment can be used in multiple activities.
 Fragment life cycle is closely related to the life cycle of its host activity which
means when the activity is paused, all the fragments available in the activity will
also be stopped.
 A fragment can implement a behaviour that has no user interface component.
 Fragments were added to the Android API in Honeycomb version of Android
which API version 11.
You create fragments by extending Fragment class and You can insert a
fragment into your activity layout by declaring the fragment in the activity's
layout file, as a <fragment> element.

Prior to fragment introduction, we had a limitation because we can show only a


single activity on the screen at one given point in time. So we were not able to
divide device screen and control different parts separately. But with the
introduction of fragment we got more flexibility and removed the limitation of
having a single activity on the screen at a time. Now we can have a single
activity but each activity can comprise of multiple fragments which will have
their own layout, events and complete life cycle.

Following is a typical example of how two UI modules defined by fragments can


be combined into one activity for a tablet design, but separated for a handset
design.

94 | P a g e
The application can embed two fragments in Activity A, when running on a
tablet-sized device. However, on a handset-sized screen, there's not enough
room for both fragments, so Activity A includes only the fragment for the list of
articles, and when the user selects an article, it starts Activity B, which includes
the second fragment to read the article.

Fragment Life Cycle


Android fragments have their own life cycle very similar to an android activity.
This section briefs different stages of its life cycle.

95 | P a g e
Fragment lifecycle
Here is the list of methods which you can to override in your fragment class −

 onAttach()The fragment instance is associated with an activity instance.The


fragment and the activity is not fully initialized. Typically you get in this method
a reference to the activity which uses the fragment for further initialization work.
 onCreate() The system calls this method when creating the fragment. You
should initialize essential components of the fragment that you want to retain
when the fragment is paused or stopped, then resumed.
 onCreateView() The system calls this callback when it's time for the fragment
to draw its user interface for the first time. To draw a UI for your fragment, you
must return a View component from this method that is the root of your
fragment's layout. You can return null if the fragment does not provide a UI.
 onActivityCreated()The onActivityCreated() is called after the onCreateView()
method when the host activity is created. Activity and fragment instance have
been created as well as the view hierarchy of the activity. At this point, view can
be accessed with the findViewById() method. example. In this method you can
instantiate objects which require a Context object
 onStart()The onStart() method is called once the fragment gets visible.
 onResume()Fragment becomes active.
 onPause() The system calls this method as the first indication that the user is
leaving the fragment. This is usually where you should commit any changes that
should be persisted beyond the current user session.
 onStop()Fragment going to be stopped by calling onStop()
 onDestroyView()Fragment view will destroy after call this method
 onDestroy()onDestroy() called to do final clean up of the fragment's state but
Not guaranteed to be called by the Android platform.

How to use Fragments?


This involves number of simple steps to create Fragments.

 First of all decide how many fragments you want to use in an activity. For
example let's we want to use two fragments to handle landscape and portrait
modes of the device.
 Next based on number of fragments, create classes which will extend
the Fragment class. The Fragment class has above mentioned callback
functions. You can override any of the functions based on your requirements.
 Corresponding to each fragment, you will need to create layout files in XML file.
These files will have layout for the defined fragments.
 Finally modify activity file to define the actual logic of replacing fragments
based on your requirement.

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

96 | P a g e
Types of Fragments
Basically fragments are divided as three stages as shown below.

 Single frame fragments − Single frame fragments are using for hand hold
devices like mobiles, here we can show only one fragment as a view.
 List fragments − fragments having special list view is called as list fragment
 Fragments transaction − Using with fragment transaction. we can move one
fragment to another fragment.

Android - Intents and Filters


An Android Intent is an abstract description of an operation to be performed. It
can be used with startActivity to launch an Activity, broadcastIntent to send
it to any interested BroadcastReceiver components,
and startService(Intent) or bindService(Intent, ServiceConnection,
int) to communicate with a background Service.
The intent itself, an Intent object, is a passive data structure holding
an abstract description of an operation to be performed.
For example, let's assume that you have an Activity that needs to launch an
email client and sends an email using your Android device. For this purpose,
your Activity would send an ACTION_SEND along with appropriate chooser, to
the Android Intent Resolver. The specified chooser gives the proper interface for
the user to pick how to send your email data.
Intent email = new Intent(Intent.ACTION_SEND,
Uri.parse("mailto:"));
email.putExtra(Intent.EXTRA_EMAIL, recipients);
email.putExtra(Intent.EXTRA_SUBJECT, subject.getText().toString());
email.putExtra(Intent.EXTRA_TEXT, body.getText().toString());
startActivity(Intent.createChooser(email, "Choose an email client
from..."));

Above syntax is calling startActivity method to start an email activity and result
should be as shown below −

97 | P a g e
For example, assume that you have an Activity that needs to open URL in a web
browser on your Android device. For this purpose, your Activity will send
ACTION_WEB_SEARCH Intent to the Android Intent Resolver to open given URL in
the web browser. The Intent Resolver parses through a list of Activities and
chooses the one that would best match your Intent, in this case, the Web
Browser Activity. The Intent Resolver then passes your web page to the web
browser and starts the Web Browser Activity.

String q = "tutorialspoint";
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH );
intent.putExtra(SearchManager.QUERY, q);
startActivity(intent);
Above example will search as tutorialspoint on android search engine and it
gives the result of tutorialspoint in your an activity

There are separate mechanisms for delivering intents to each type of


component − activities, services, and broadcast receivers.

Sr.N
Method & Description
o

Context.startActivity()
1 The Intent object is passed to this method to launch a new activity or get an
existing activity to do something new.

Context.startService()
2 The Intent object is passed to this method to initiate a service or deliver new
instructions to an ongoing service.

98 | P a g e
Context.sendBroadcast()
3 The Intent object is passed to this method to deliver the message to all
interested broadcast receivers.

Intent Objects
An Intent object is a bundle of information which is used by the component that
receives the intent as well as information used by the Android system.

An Intent object can contain the following components based on what it is


communicating or going to perform −

Action
This is mandatory part of the Intent object and is a string naming the action to
be performed — or, in the case of broadcast intents, the action that took place
and is being reported. The action largely determines how the rest of the intent
object is structured . The Intent class defines a number of action constants
corresponding to different intents. Here is a list of Android Intent Standard
Actions

The action in an Intent object can be set by the setAction() method and read by
getAction().

Data
Adds a data specification to an intent filter. The specification can be just a data
type (the mimeType attribute), just a URI, or both a data type and a URI. A URI is
specified by separate attributes for each of its parts −

These attributes that specify the URL format are optional, but also mutually
dependent −

 If a scheme is not specified for the intent filter, all the other URI attributes are
ignored.
 If a host is not specified for the filter, the port attribute and all the path
attributes are ignored.

The setData() method specifies data only as a URI, setType() specifies it only as
a MIME type, and setDataAndType() specifies it as both a URI and a MIME type.
The URI is read by getData() and the type by getType().

Some examples of action/data pairs are −

99 | P a g e
Sr.N
Action/Data Pair & Description
o.

1 ACTION_VIEW content://contacts/people/1
Display information about the person whose identifier is "1".

2 ACTION_DIAL content://contacts/people/1
Display the phone dialer with the person filled in.

3 ACTION_VIEW tel:123
Display the phone dialer with the given number filled in.

4 ACTION_DIAL tel:123
Display the phone dialer with the given number filled in.

5 ACTION_EDIT content://contacts/people/1
Edit information about the person whose identifier is "1".

6 ACTION_VIEW content://contacts/people/
Display a list of people, which the user can browse through.

7 ACTION_SET_WALLPAPER
Show settings for choosing wallpaper

ACTION_SYNC
8 It going to be synchronous the data,Constant Value
is android.intent.action.SYNC

9 ACTION_SYSTEM_TUTORIAL
It will start the platform-defined tutorial(Default tutorial or start up tutorial)

10 ACTION_TIMEZONE_CHANGED
It intimates when time zone has changed

11 ACTION_UNINSTALL_PACKAGE
It is used to run default uninstaller

Category
The category is an optional part of Intent object and it's a string containing
additional information about the kind of component that should handle the
intent. The addCategory() method places a category in an Intent object,
removeCategory() deletes a category previously added, and getCategories()
gets the set of all categories currently in the object. Here is a list of Android
Intent Standard Categories.

You can check detail on Intent Filters in below section to understand how do we
use categories to choose appropriate activity corresponding to an Intent.

100 | P a g e
Extras
This will be in key-value pairs for additional information that should be delivered
to the component handling the intent. The extras can be set and read using the
putExtras() and getExtras() methods respectively. Here is a list of Android Intent
Standard Extra Data

Flags
These flags are optional part of Intent object and instruct the Android system
how to launch an activity, and how to treat it after it's launched etc.

Sr.N
Flags & Description
o

FLAG_ACTIVITY_CLEAR_TASK
If set in an Intent passed to Context.startActivity(), this flag will cause any
1 existing task that would be associated with the activity to be cleared before the
activity is started. That is, the activity becomes the new root of an otherwise
empty task, and any old activities are finished. This can only be used in
conjunction with FLAG_ACTIVITY_NEW_TASK.

FLAG_ACTIVITY_CLEAR_TOP
If set, and the activity being launched is already running in the current task,
2 then instead of launching a new instance of that activity, all of the other
activities on top of it will be closed and this Intent will be delivered to the (now
on top) old activity as a new Intent.

FLAG_ACTIVITY_NEW_TASK
3 This flag is generally used by activities that want to present a "launcher" style
behavior: they give the user a list of separate things that can be done, which
otherwise run completely independently of the activity launching them.

Component Name
This optional field is an android ComponentName object representing either
Activity, Service or BroadcastReceiver class. If it is set, the Intent object is
delivered to an instance of the designated class otherwise Android uses other
information in the Intent object to locate a suitable target.

The component name is set by setComponent(), setClass(), or setClassName()


and read by getComponent().

Types of Intents
There are following two types of intents supported by Android

101 | P a g e
Explicit Intents
Explicit intent going to be connected internal world of application,suppose if you
wants to connect one activity to another activity, we can do this quote by
explicit intent, below image is connecting first activity to second activity by
clicking button.

These intents designate the target component by its name and they are
typically used for application-internal messages - such as an activity starting a
subordinate service or launching a sister activity. For example −

// Explicit Intent by specifying its class name


Intent i = new Intent(FirstActivity.this, SecondActivity.class);

// Starts TargetActivity
startActivity(i);

102 | P a g e
Implicit Intents
These intents do not name a target and the field for the component name is left
blank. Implicit intents are often used to activate components in other
applications. For example −

Intent read1=new Intent();


read1.setAction(android.content.Intent.ACTION_VIEW);
read1.setData(ContactsContract.Contacts.CONTENT_URI);
startActivity(read1);

Above code will give result as shown below

103 | P a g e
The target component which receives the intent can use
the getExtras() method to get the extra data sent by the source component.
For example −
// Get bundle object at appropriate place in your code
Bundle extras = getIntent().getExtras();

// Extract data using passed keys


String value1 = extras.getString("Key1");
String value2 = extras.getString("Key2");

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

Example
Following example shows the functionality of a Android Intent to launch various
Android built-in applications.

Ste
Description
p

You will use Android studio IDE to create an Android application and name it as My
1
Application under a package com.example.saira_000.myapplication.

Modify src/main/java/MainActivity.java file and add the code to define two listeners
2
corresponding two buttons ie. Start Browser and Start Phone.

Modify layout XML file res/layout/activity_main.xml to add three buttons in linear


3
layout.

Run the application to launch Android emulator and verify the result of the changes
4
done in the application.

Following is the content of the modified main activity file src/com.example.My


Application/MainActivity.java.
package com.example.saira_000.myapplication;

import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

104 | P a g e
import android.widget.Button;

public class MainActivity extends AppCompatActivity {


Button b1,b2;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

b1=(Button)findViewById(R.id.button);
b1.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
Intent i = new
Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("http://www.example.com"));
startActivity(i);
}
});

b2=(Button)findViewById(R.id.button2);
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new
Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("tel:9510300000"));
startActivity(i);
}
});
}
}
Following will be the content of res/layout/activity_main.xml file −
<?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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView

105 | P a g e
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Intent Example"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true" />

<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/abc"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_below="@+id/imageButton"
android:layout_alignRight="@+id/imageButton"
android:layout_alignEnd="@+id/imageButton" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Browser"
android:id="@+id/button"
android:layout_alignTop="@+id/editText"
android:layout_alignRight="@+id/textView1"
android:layout_alignEnd="@+id/textView1"
android:layout_alignLeft="@+id/imageButton"
android:layout_alignStart="@+id/imageButton" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Phone"

106 | P a g e
android:id="@+id/button2"
android:layout_below="@+id/button"
android:layout_alignLeft="@+id/button"
android:layout_alignStart="@+id/button"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2" />
</RelativeLayout>
Following will be the content of res/values/strings.xml to define two new
constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">My Applicaiton</string>
</resources>
Following is the default content of AndroidManifest.xml −
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.saira_000.myapplication">

<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>
Let's try to run your My Application application. I assume you had created
your AVD while doing environment setup. To run the app from Android Studio,
open one of your project's activity files and click Run icon from the
toolbar.Android Studio installs the app on your AVD and starts it and if
everything is fine with your setup and application, it will display following
Emulator window −

107 | P a g e
Now click on Start Browser button, which will start a browser configured and
display http://www.example.com as shown below −

108 | P a g e
Similar way you can launch phone interface using Start Phone button, which will
allow you to dial already given phone number.

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

<intent-filter>
<action android:name="android.intent.action.VIEW" />
<action android:name="com.example.My Application.LAUNCH" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="http" />
</intent-filter>

109 | P a g e
</activity>
Once this activity is defined along with above mentioned filters, other activities
will be able to invoke this activity using either
the android.intent.action.VIEW, or using the com.example.My
Application.LAUNCH action provided their category
is android.intent.category.DEFAULT.
The <data> element specifies the data type expected by the activity to be
called and for above example our custom activity expects the data to start with
the "http://"

There may be a situation that an intent can pass through the filters of more than
one activity or service, the user may be asked which component to activate. An
exception is raised if no target can be found.

There are following test Android checks before invoking an activity −

 A filter <intent-filter> may list more than one action as shown above but this list
cannot be empty; a filter must contain at least one <action> element, otherwise
it will block all intents. If more than one actions are mentioned then Android
tries to match one of the mentioned actions before invoking the activity.
 A filter <intent-filter> may list zero, one or more than one categories. if there is
no category mentioned then Android always pass this test but if more than one
categories are mentioned then for an intent to pass the category test, every
category in the Intent object must match a category in the filter.
 Each <data> element can specify a URI and a data type (MIME media type).
There are separate attributes like scheme, host, port, and path for each part
of the URI. An Intent object that contains both a URI and a data type passes the
data type part of the test only if its type matches a type listed in the filter.

Example
Following example is a modification of the above example. Here we will see how
Android resolves conflict if one intent is invoking two activities defined in , next
how to invoke a custom activity using a filter and third one is an exception case
if Android does not file appropriate activity defined for an intent.

Ste
Description
p

You will use android studio to create an Android application and name it as My
1
Application under a package com.example.tutorialspoint7.myapplication;.

2 Modify src/Main/Java/MainActivity.java file and add the code to define three listeners

110 | P a g e
corresponding to three buttons defined in layout file.

Add a new src/Main/Java/CustomActivity.java file to have one custom activity which


3
will be invoked by different intents.

Modify layout XML file res/layout/activity_main.xml to add three buttons in linear


4
layout.

Add one layout XML file res/layout/custom_view.xml to add a simple <TextView> to


5
show the passed data through intent.

Modify AndroidManifest.xml to add <intent-filter> to define rules for your intent to


6
invoke custom activity.

Run the application to launch Android emulator and verify the result of the changes
7
done in the application.

Following is the content of the modified main activity


file src/MainActivity.java.
package com.example.tutorialspoint7.myapplication;

import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {


Button b1,b2,b3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button);
b1.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
Intent i = new
Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("http://www.example.com"));
startActivity(i);
}

111 | P a g e
});

b2 = (Button)findViewById(R.id.button2);
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent("com.example.
tutorialspoint7.myapplication.
LAUNCH",Uri.parse("http://www.example.com"));
startActivity(i);
}
});

b3 = (Button)findViewById(R.id.button3);
b3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent("com.example.
My Application.LAUNCH",
Uri.parse("https://www.example.com"));
startActivity(i);
}
});
}
}
Following is the content of the modified main activity file src/com.example.My
Application/CustomActivity.java.
package com.example.tutorialspoint7.myapplication;

import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.widget.TextView;

/**
* Created by TutorialsPoint7 on 8/23/2016.
*/
public class CustomActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.custom_view);
TextView label = (TextView) findViewById(R.id.show_data);
Uri url = getIntent().getData();
label.setText(url.toString());
}
}
Following will be the content of res/layout/activity_main.xml file −

112 | P a g e
<?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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"

tools:context="com.example.tutorialspoint7.myapplication.MainActivi
ty">

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Intent Example"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true" />

<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/abc"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_below="@+id/imageButton"
android:layout_alignRight="@+id/imageButton"
android:layout_alignEnd="@+id/imageButton" />

113 | P a g e
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Browser"
android:id="@+id/button"
android:layout_alignTop="@+id/editText"
android:layout_alignLeft="@+id/imageButton"
android:layout_alignStart="@+id/imageButton"
android:layout_alignEnd="@+id/imageButton" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start browsing with launch action"
android:id="@+id/button2"
android:layout_below="@+id/button"
android:layout_alignLeft="@+id/button"
android:layout_alignStart="@+id/button"
android:layout_alignEnd="@+id/button" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Exceptional condition"
android:id="@+id/button3"
android:layout_below="@+id/button2"
android:layout_alignLeft="@+id/button2"
android:layout_alignStart="@+id/button2"
android:layout_toStartOf="@+id/editText"
android:layout_alignParentEnd="true" />
</RelativeLayout>
Following will be the content of res/layout/custom_view.xml file −
<?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/show_data"
android:layout_width="fill_parent"
android:layout_height="400dp"/>
</LinearLayout>
Following will be the content of res/values/strings.xml to define two new
constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">My Application</string>
</resources>
Following is the default content of AndroidManifest.xml −

114 | P a g e
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tutorialspoint7.myapplication">

<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>

<activity
android:name="com.example.tutorialspoint7.myapplication.CustomActiv
ity">

<intent-filter>
<action android:name = "android.intent.action.VIEW" />
<action android:name =
"com.example.tutorialspoint7.myapplication.LAUNCH" />
<category android:name =
"android.intent.category.DEFAULT" />
<data android:scheme = "http" />
</intent-filter>

</activity>
</application>

</manifest>
Let's try to run your My Application application. I assume you had created
your AVD while doing environment setup. To run the app from Android Studio,
open one of your project's activity files and click Run icon from the toolbar.
Android Studio installs the app on your AVD and starts it and if everything is fine
with your setup and application, it will display following Emulator window −

115 | P a g e
Now let's start with first button "Start Browser with VIEW Action". Here we have
defined our custom activity with a filter "android.intent.action.VIEW", and there
is already one default activity against VIEW action defined by Android which is
launching web browser, So android displays following two options to select the
activity you want to launch.

116 | P a g e
Now if you select Browser, then Android will launch web browser and open
example.com website but if you select IndentDemo option then Android will
launch CustomActivity which does nothing but just capture passed data and
displays in a text view as follows −

117 | P a g e
Now go back using back button and click on "Start Browser with LAUNCH Action"
button, here Android applies filter to choose define activity and it simply launch
your custom activity

Again, go back using back button and click on "Exception Condition" button,
here Android tries to find out a valid filter for the given intent but it does not find
a valid activity defined because this time we have used data as https instead
of http though we are giving a correct action, so Android raises an exception
and shows following screen −

118 | P a g e
Android - UI Layouts
The basic building block for user interface is a View object which is created from
the View class and occupies a rectangular area on the screen and is responsible
for drawing and event handling. View is the base class for widgets, which are
used to create interactive UI components like buttons, text fields, etc.
The ViewGroup is a subclass of View and provides invisible container that hold
other Views or other ViewGroups and define their layout properties.
At third level we have different layouts which are subclasses of ViewGroup class
and a typical layout defines the visual structure for an Android user interface
and can be created either at run time using View/ViewGroup objects or you
can declare your layout using simple XML file main_layout.xml which is located
in the res/layout folder of your project.

119 | P a g e
Layout params
This tutorial is more about creating your GUI based on layouts defined in XML
file. A layout may contain any type of widgets such as buttons, labels,
textboxes, and so on. Following is a simple example of XML file having
LinearLayout −

<?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" >

<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a TextView" />

<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a Button" />

<!-- More GUI components go here -->

</LinearLayout>

120 | P a g e
Once your layout has created, you can load the layout resource from your
application code, in your Activity.onCreate() callback implementation as shown
below −
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

Android Layout Types


There are number of Layouts provided by Android which you will use in almost
all the Android applications to provide different view, look and feel.

Sr.N
Layout & Description
o

Linear Layout
1
LinearLayout is a view group that aligns all children in a single direction,
vertically or horizontally.

Relative Layout
2
RelativeLayout is a view group that displays child views in relative positions.

Table Layout
3
TableLayout is a view that groups views into rows and columns.

Absolute Layout
4
AbsoluteLayout enables you to specify the exact location of its children.

Frame Layout
5
The FrameLayout is a placeholder on screen that you can use to display a single
view.

List View
6
ListView is a view group that displays a list of scrollable items.

Grid View
7
GridView is a ViewGroup that displays items in a two-dimensional, scrollable
grid.

Layout Attributes
121 | P a g e
Each layout has a set of attributes which define the visual properties of that
layout. There are few common attributes among all the layouts and their are
other attributes which are specific to that layout. Following are common
attributes and will be applied to all the layouts:

Sr.N
Attribute & Description
o

1 android:id
This is the ID which uniquely identifies the view.

2 android:layout_width
This is the width of the layout.

3 android:layout_height
This is the height of the layout

4 android:layout_marginTop
This is the extra space on the top side of the layout.

5 android:layout_marginBottom
This is the extra space on the bottom side of the layout.

6 android:layout_marginLeft
This is the extra space on the left side of the layout.

7 android:layout_marginRight
This is the extra space on the right side of the layout.

8 android:layout_gravity
This specifies how child Views are positioned.

android:layout_weight
9 This specifies how much of the extra space in the layout should be allocated to
the View.

10 android:layout_x
This specifies the x-coordinate of the layout.

11 android:layout_y
This specifies the y-coordinate of the layout.

12 android:layout_width
This is the width of the layout.

13 android:paddingLeft
This is the left padding filled for the layout.

122 | P a g e
14 android:paddingRight
This is the right padding filled for the layout.

15 android:paddingTop
This is the top padding filled for the layout.

16 android:paddingBottom
This is the bottom padding filled for the layout.

Here width and height are the dimension of the layout/view which can be
specified in terms of dp (Density-independent Pixels), sp ( Scale-independent
Pixels), pt ( Points which is 1/72 of an inch), px( Pixels), mm ( Millimeters) and
finally in (inches).

You can specify width and height with exact measurements but more often, you
will use one of these constants to set the width or height −

 android:layout_width=wrap_content tells your view to size itself to the


dimensions required by its content.
 android:layout_width=fill_parent tells your view to become as big as its
parent view.

Gravity attribute plays important role in positioning the view object and it can
take one or more (separated by '|') of the following constant values.

Constant Value Description

Push object to the top of its container, not changing its


top 0x30
size.

Push object to the bottom of its container, not changing its


bottom 0x50
size.

Push object to the left of its container, not changing its


left 0x03
size.

Push object to the right of its container, not changing its


right 0x05
size.

Place object in the vertical center of its container, not


center_vertical 0x10
changing its size.

123 | P a g e
Grow the vertical size of the object if needed so it
fill_vertical 0x70
completely fills its container.

Place object in the horizontal center of its container, not


center_horizontal 0x01
changing its size.

Grow the horizontal size of the object if needed so it


fill_horizontal 0x07
completely fills its container.

Place the object in the center of its container in both the


center 0x11
vertical and horizontal axis, not changing its size.

Grow the horizontal and vertical size of the object if


fill 0x77
needed so it completely fills its container.

Additional option that can be set to have the top and/or


bottom edges of the child clipped to its container's bounds.
clip_vertical 0x80 The clip will be based on the vertical gravity: a top gravity
will clip the bottom edge, a bottom gravity will clip the top
edge, and neither will clip both edges.

Additional option that can be set to have the left and/or


right edges of the child clipped to its container's bounds.
clip_horizontal 0x08 The clip will be based on the horizontal gravity: a left
gravity will clip the right edge, a right gravity will clip the
left edge, and neither will clip both edges.

Push object to the beginning of its container, not changing


start 0x00800003
its size.

Push object to the end of its container, not changing its


end 0x00800005
size.

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

View Identification

124 | P a g e
A view object may have a unique ID assigned to it which will identify the View
uniquely within the tree. The syntax for an ID, inside an XML tag is −

android:id="@+id/my_button"

Following is a brief description of @ and + signs −

 The at-symbol (@) at the beginning of the string indicates that the XML parser
should parse and expand the rest of the ID string and identify it as an ID
resource.
 The plus-symbol (+) means that this is a new resource name that must be
created and added to our resources. To create an instance of the view object
and capture it from the layout, use the following −
Button myButton = (Button) findViewById(R.id.my_button);

Android - UI Controls
Input controls are the interactive components in your app's user interface.
Android provides a wide variety of controls you can use in your UI, such as
buttons, text fields, seek bars, check box, zoom buttons, toggle buttons, and
many more.

UI Elements
A View is an object that draws something on the screen that the user can
interact with and a ViewGroup is an object that holds other View (and
ViewGroup) objects in order to define the layout of the user interface.

You define your layout in an XML file which offers a human-readable structure
for the layout, similar to HTML. For example, a simple vertical layout with a text
view and a button looks like this −

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


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"

125 | P a g e
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I am a TextView" />

<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I am a Button" />
</LinearLayout>

Android UI Controls
There are number of UI controls provided by Android that allow you to build the
graphical user interface for your app.

Sr.N
UI Control & Description
o.

TextView
1
This control is used to display text to the user.

EditText
2
EditText is a predefined subclass of TextView that includes rich editing
capabilities.

AutoCompleteTextView
3
The AutoCompleteTextView is a view that is similar to EditText, except that it
shows a list of completion suggestions automatically while the user is typing.

Button
4
A push-button that can be pressed, or clicked, by the user to perform an action.

ImageButton
5 An ImageButton is an AbsoluteLayout which enables you to specify the exact
location of its children. This shows a button with an image (instead of text) that
can be pressed or clicked by the user.

6 CheckBox

126 | P a g e
An on/off switch that can be toggled by the user. You should use check box
when presenting users with a group of selectable options that are not mutually
exclusive.

ToggleButton
7
An on/off button with a light indicator.

RadioButton
8
The RadioButton has two states: either checked or unchecked.

RadioGroup
9
A RadioGroup is used to group together one or more RadioButtons.

ProgressBar
10
The ProgressBar view provides visual feedback about some ongoing tasks,
such as when you are performing a task in the background.

Spinner
11
A drop-down list that allows users to select one value from a set.

TimePicker
12
The TimePicker view enables users to select a time of the day, in either 24-
hour mode or AM/PM mode.

DatePicker
13
The DatePicker view enables users to select a date of the day.

Create UI Controls
Input controls are the interactive components in your app's user interface.
Android provides a wide variety of controls you can use in your UI, such as
buttons, text fields, seek bars, check box, zoom buttons, toggle buttons, and
many more.

As explained in previous chapter, a view object may have a unique ID assigned


to it which will identify the View uniquely within the tree. The syntax for an ID,
inside an XML tag is −

android:id="@+id/text_id"

127 | P a g e
To create a UI Control/View/Widget you will have to define a view/widget in the
layout file and assign it a unique ID as follows −

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


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView android:id="@+id/text_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I am a TextView" />
</LinearLayout>

Then finally create an instance of the Control object and capture it from the
layout, use the following −

TextView myText = (TextView) findViewById(R.id.text_id);

Android - Event Handling


Events are a useful way to collect data about a user's interaction with
interactive components of Applications. Like button presses or screen
touch etc. The Android framework maintains an event queue as first-in, first-out
(FIFO) basis. You can capture these events in your program and take
appropriate action as per requirements.

There are following three concepts related to Android Event Management −

 Event Listeners − An event listener is an interface in the View class that


contains a single callback method. These methods will be called by the Android
framework when the View to which the listener has been registered is triggered
by user interaction with the item in the UI.
 Event Listeners Registration − Event Registration is the process by which an
Event Handler gets registered with an Event Listener so that the handler is
called when the Event Listener fires the event.
 Event Handlers − When an event happens and we have registered an event
listener for the event, the event listener calls the Event Handlers, which is the
method that actually handles the event.

Event Listeners & Event Handlers

128 | P a g e
Event Handler Event Listener & Description

OnClickListener()
onClick() This is called when the user either clicks or touches or focuses
upon any widget like button, text, image etc. You will use
onClick() event handler to handle such event.

OnLongClickListener()
This is called when the user either clicks or touches or focuses
onLongClick() upon any widget like button, text, image etc. for one or more
seconds. You will use onLongClick() event handler to handle
such event.

OnFocusChangeListener()
onFocusChange() This is called when the widget looses its focus ie. user goes
away from the view item. You will use onFocusChange()
event handler to handle such event.

OnFocusChangeListener()
onKey() This is called when the user is focused on the item and presses
or releases a hardware key on the device. You will use
onKey() event handler to handle such event.

OnTouchListener()
onTouch() This is called when the user presses the key, releases the key,
or any movement gesture on the screen. You will use
onTouch() event handler to handle such event.

OnMenuItemClickListener()
onMenuItemClick() This is called when the user selects a menu item. You will use
onMenuItemClick() event handler to handle such event.

onCreateContextMenu( onCreateContextMenuItemListener()
) This is called when the context menu is being built(as the
result of a sustained "long click)
There are many more event listeners available as a part of View class like
OnHoverListener, OnDragListener etc which may be needed for your application.
So I recommend to refer official documentation for Android application
development in case you are going to develop a sophisticated apps.

Event Listeners Registration


Event Registration is the process by which an Event Handler gets registered with
an Event Listener so that the handler is called when the Event Listener fires the
event. Though there are several tricky ways to register your event listener for

129 | P a g e
any event, but I'm going to list down only top 3 ways, out of which you can use
any of them based on the situation.

 Using an Anonymous Inner Class


 Activity class implements the Listener interface.
 Using Layout file activity_main.xml to specify event handler directly.

Below section will provide you detailed examples on all the three scenarios −

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

Touch Mode
Users can interact with their devices by using hardware keys or buttons or
touching the screen.Touching the screen puts the device into touch mode. The
user can then interact with it by touching the on-screen virtual buttons, images,
etc.You can check if the device is in touch mode by calling the View class’s
isInTouchMode() method.

Focus
A view or widget is usually highlighted or displays a flashing cursor when it’s in
focus. This indicates that it’s ready to accept input from the user.

 isFocusable() − it returns true or false


 isFocusableInTouchMode() − checks to see if the view is focusable in touch
mode. (A view may be focusable when using a hardware key but not when the
device is in touch mode)
android:foucsUp="@=id/button_l"

onTouchEvent()
public boolean onTouchEvent(motionEvent event){
switch(event.getAction()){
case TOUCH_DOWN:
Toast.makeText(this,"you have clicked down Touch
button",Toast.LENTH_LONG).show();
break();

case TOUCH_UP:

130 | P a g e
Toast.makeText(this,"you have clicked up touch
button",Toast.LENTH_LONG).show();
break;

case TOUCH_MOVE:
Toast.makeText(this,"you have clicked move touch
button"Toast.LENTH_LONG).show();
break;
}
return super.onTouchEvent(event) ;
}

Event Handling Examples

Event Listeners Registration Using an Anonymous


Inner Class
Here you will create an anonymous implementation of the listener and will be
useful if each class is applied to a single control only and you have advantage to
pass arguments to event handler. In this approach event handler methods can
access private data of Activity. No reference is needed to call to Activity.

But if you applied the handler to more than one control, you would have to cut
and paste the code for the handler and if the code for the handler is long, it
makes the code harder to maintain.

Following are the simple steps to show how we will make use of separate
Listener class to register and capture click event. Similar way you can
implement your listener for any other required event type.

Ste
Description
p

You will use Android studio IDE to create an Android application and name it
1 as myapplication under a package com.example.myapplication as explained in
the Hello World Example chapter.

Modify src/MainActivity.java file to add click event listeners and handlers for the two
2
buttons defined.

Modify the detault content of res/layout/activity_main.xml file to include Android UI


3
controls.

131 | P a g e
No need to declare default string constants.Android studio takes care default
4
constants.

Run the application to launch Android emulator and verify the result of the changes
5
done in the aplication.

Following is the content of the modified main activity


file src/com.example.myapplication/MainActivity.java. This file can include
each of the fundamental lifecycle methods.
package com.example.myapplication;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {


private ProgressDialog progress;
Button b1,b2;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progress = new ProgressDialog(this);

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

@Override
public void onClick(View v) {
TextView txtView = (TextView)
findViewById(R.id.textView);
txtView.setTextSize(25);
}
});

b2.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
TextView txtView = (TextView)
findViewById(R.id.textView);
txtView.setTextSize(55);

132 | P a g e
}
});
}
}
Following will be the content of res/layout/activity_main.xml file −
Here abc indicates about tutorialspoint logo

<?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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Event Handling "
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp"/>

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point "
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_above="@+id/imageButton"
android:layout_centerHorizontal="true"
android:layout_marginBottom="40dp" />

<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/abc"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />

<Button
android:layout_width="wrap_content"

133 | P a g e
android:layout_height="wrap_content"
android:text="Small font"
android:id="@+id/button"
android:layout_below="@+id/imageButton"
android:layout_centerHorizontal="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Font"
android:id="@+id/button2"
android:layout_below="@+id/button"
android:layout_alignRight="@+id/button"
android:layout_alignEnd="@+id/button" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="@+id/textView"
android:layout_below="@+id/button2"
android:layout_centerHorizontal="true"
android:textSize="25dp" />

</RelativeLayout>
Following will be the content of res/values/strings.xml to define two new
constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">myapplication</string>
</resources>
Following is the default content of AndroidManifest.xml −
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapplication" >

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name="com.example.myapplication.MainActivity"
android:label="@string/app_name" >

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

134 | P a g e
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>

</activity>

</application>
</manifest>
Let's try to run your myapplication application. I assume you had created
your AVD while doing environment setup. To run the app from Android Studio,
open one of your project's activity files and click Run icon from the toolbar.
Android Studio installs the app on your AVD and starts it and if everything is fine
with your setup and application, it will display following Emulator window −

135 | P a g e
Now you try to click on two buttons, one by one and you will see that font of
the Hello World text will change, which happens because registered click event
handler method is being called against each click event.

Exercise
I will recommend to try writing different event handlers for different event types
and understand exact difference in different event types and their handling.
Events related to menu, spinner, pickers widgets are little different but they are
also based on the same concepts as explained above.

Android - Styles and Themes


style resource defines the format and look for a UI. A style can be applied to
an individual View (from within a layout file) or to an entire Activity or
application (from within the manifest file).

Defining Styles
A style is defined in an XML resource that is separate from the XML that
specifies the layout. This XML file resides under res/values/ directory of your
project and will have <resources> as the root node which is mandatory for the
style file. The name of the XML file is arbitrary, but it must use the .xml
extension.
You can define multiple styles per file using <style> tag but each style will
have its name that uniquely identifies the style. Android style attributes are set
using <item> tag as shown below −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="CustomFontStyle">
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:capitalize">characters</item>
<item name="android:typeface">monospace</item>
<item name="android:textSize">12pt</item>
<item name="android:textColor">#00FF00</item>/>
</style>
</resources>
The value for the <item> can be a keyword string, a hex color, a reference to
another resource type, or other value depending on the style property.

Using Styles

136 | P a g e
Once your style is defined, you can use it in your XML Layout file
using style attribute as follows −
<?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" >

<TextView
android:id="@+id/text_id"
style="@style/CustomFontStyle"
android:text="@string/hello_world" />

</LinearLayout>
To understand the concept related to Android Style, you can check Style Demo
Example.

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

Style Inheritance
Android supports style Inheritance in very much similar way as cascading style
sheet in web design. You can use this to inherit properties from an existing style
and then define only the properties that you want to change or add.

To implement a custom theme create or edit


MyAndroidApp/res/values/themes.xml and add the following −

<resources>
...
<style name="MyCustomTheme" parent="android:style/Theme">
<item name="android:textColorPrimary">#ffff0000</item>
</style>
...
</resources>

In your AndroidManifest.xml apply the theme to the activities you want to style

<activity
android:name="com.myapp.MyActivity"
...
android:theme="@style/MyCustomTheme"

137 | P a g e
/>

Your new theme will be applied to your activity, and text is now bright red.

Applying Colors to Theme Attributes


Your color resource can then be applied to some theme attributes, such as the
window background and the primary text color, by adding <item> elements to
your custom theme. These attributes are defined in your styles.xml file. For
example, to apply the custom color to the window background, add the
following two <item> elements to your custom theme, defined in
MyAndroidApp/res/values/styles.xml file −

138 | P a g e
<resources>
...
<style name="MyCustomTheme" ...>
<item
name="android:windowBackground">@color/my_custom_color</item>
<item
name="android:colorBackgroundCacheHint">@color/my_custom_color</ite
m>
</style>
...
</resources>

Using a Custom Nine-Patch With Buttons

139 | P a g e
A nine-patch drawable is a special kind of image which can be scaled in width
and height while maintaining its visual integrity. Nine-patches are the most
common way to specify the appearance of Android buttons, though any
drawable type can be used.

a Sample of Nine-Patch button


Steps to create Nine-Patch Buttons
 Save this bitmap as /res/drawable/my_nine_patch.9.png
 Define a new style
 Apply the new button style to the buttonStyle attribute of your custom theme
Define a new Style
<resources>
...
<style name="MyCustomButton" parent="android:Widget.Button">
<item
name="android:background">@drawable/my_nine_patch</item>
</style>
...
</resources>
Apply the theme
<resources>
...
<style name="MyCustomTheme" parent=...>
...
<item
name="android:buttonStyle">@style/MyCustomButton</item>
</style>
...
</resources>

140 | P a g e
Android Themes
Hope you understood the concept of Style, so now let's try to understand what is
a Theme. A theme is nothing but an Android style applied to an entire Activity
or application, rather than an individual View.
Thus, when a style is applied as a theme, every View in the Activity or
application will apply each style property that it supports. For example, you can
apply the same CustomFontStyle style as a theme for an Activity and then all
text inside that Activity will have green monospace font.
To set a theme for all the activities of your application, open
the AndroidManifest.xml file and edit the <application> tag to include
the android:theme attribute with the style name. For example −
<application android:theme="@style/CustomFontStyle">

141 | P a g e
But if you want a theme applied to just one Activity in your application, then add
the android:theme attribute to the <activity> tag only. For example −

<activity android:theme="@style/CustomFontStyle">
There are number of default themes defined by Android which you can use
directly or inherit them using parent attribute as follows −
<style name="CustomTheme" parent="android:Theme.Light">
...
</style>
To understand the concept related to Android Theme, you can check Theme
Demo Example.

Styling the colour palette


The layout design can implementable based on them based colours, for example
as following design is designed based on them colour(blue)

Above layout has designed based on style.xml file,Which has placed


at res/values/
<resource>

142 | P a g e
<style name="AppTheme" parent="android:Theme.Material">
<item name ="android:color/primary">@color/primary</item>
<item name
="android:color/primaryDark">@color/primary_dark</item>
<item name
="android:colorAccent/primary">@color/accent</item>
</style>
<resource>

Default Styles & Themes


The Android platform provides a large collection of styles and themes that you
can use in your applications. You can find a reference of all available styles in
the R.style class. To use the styles listed here, replace all underscores in the
style name with a period. For example, you can apply the Theme_NoTitleBar
theme with "@android:style/Theme.NoTitleBar". You can see the following
source code for Android styles and themes −
 Android Styles (styles.xml)
 Android Themes (themes.xml)

Android - Custom Components


Implementing own components in pre built-in components with extending
subclass with own defined class

Android offers a great list of pre-built widgets like Button, TextView, EditText,
ListView, CheckBox, RadioButton, Gallery, Spinner, AutoCompleteTextView etc.
which you can use directly in your Android application development, but there
may be a situation when you are not satisfied with existing functionality of any
of the available widgets. Android provides you with means of creating your own
custom components which you can customized to suit your needs.

If you only need to make small adjustments to an existing widget or layout, you
can simply subclass the widget or layout and override its methods which will
give you precise control over the appearance and function of a screen element.

This tutorial explains you how to create custom Views and use them in your
application using simple and easy steps.

143 | P a g e
Example of Custom Components in Custom View
hierarchy

Creating a Simple Custom Component


Ste
Description
p

You will use Android studio IDE to create an Android application and name it
1 as myapplication under a package com.example.tutorialspoint7.myapplication as
explained in the Hello World Example chapter.

Create an XML res/values/attrs.xml file to define new attributes along with their data
2
type.

3 Create src/mainactivity.java file and add the code to define your custom component

Modify res/layout/activity_main.xml file and add the code to create Colour compound
4
view instance along with few default attributes and new attributes.

Run the application to launch Android emulator and verify the result of the changes
5
done in the application.

144 | P a g e
Create the following attributes file called attrs.xml in your res/values folder.

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


<resources>
<declare-styleable name="TimeView">
<declare-styleable name="TimeView">
<attr name="title" format="string" />
<attr name="setColor" format="boolean"/>
</declare-styleable>
</declare-styleable>
</resources>

Change the layout file used by the activity to the following.

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


<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:custom="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<com.example.tutorialspoint7.myapplication.TimeView
android:id="@+id/timeView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#fff"
android:textSize="40sp"
custom:title="my time view"
custom:setColor="true" />

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/simple"
android:layout_below="@id/timeView"
android:layout_marginTop="10dp" />
</RelativeLayout>

Create the following java file called timeview for your compound view.

package com.example.tutorialspoint7.myapplication;
/**
* Created by TutorialsPoint7 on 9/14/2016.
*/
import java.text.SimpleDateFormat;

145 | P a g e
import java.util.Calendar;

import android.content.Context;
import android.content.res.TypedArray;

import android.graphics.Color;
import android.util.AttributeSet;
import android.widget.TextView;

public class TimeView extends TextView {


private String titleText;
private boolean color;

public TimeView(Context context) {


super(context);
setTimeView();
}

public TimeView(Context context, AttributeSet attrs) {


super(context, attrs);
// retrieved values correspond to the positions of the
attributes
TypedArray typedArray =
context.obtainStyledAttributes(attrs,
R.styleable.TimeView);
int count = typedArray.getIndexCount();
try{

for (int i = 0; i < count; ++i) {

int attr = typedArray.getIndex(i);


// the attr corresponds to the title attribute
if(attr == R.styleable.TimeView_title) {

// set the text from the layout


titleText = typedArray.getString(attr);
setTimeView();
} else if(attr == R.styleable.TimeView_setColor) {
// set the color of the attr "setColor"
color = typedArray.getBoolean(attr, false);
decorateText();
}
}
}

// the recycle() will be executed obligatorily


finally {
// for reuse
typedArray.recycle();

146 | P a g e
}
}

public TimeView(Context context, AttributeSet attrs, int


defStyle) {
super(context, attrs, defStyle);
setTimeView();
}

private void setTimeView() {


// has the format hour.minuits am/pm
SimpleDateFormat dateFormat = new SimpleDateFormat("hh.mm
aa");
String time =
dateFormat.format(Calendar.getInstance().getTime());

if(this.titleText != null )
setText(this.titleText+" "+time);
else
setText(time);
}

private void decorateText() {


// when we set setColor attribute to true in the XML layout
if(this.color == true){
// set the characteristics and the color of the shadow
setShadowLayer(4, 2, 2, Color.rgb(250, 00, 250));
setBackgroundColor(Color.CYAN);
} else {
setBackgroundColor(Color.RED);
}
}
}

Change your Main activity java file to the following code and run your
application.

package com.example.tutorialspoint7.myapplication;

import android.os.Bundle;
import android.widget.TextView;
import android.app.Activity;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

147 | P a g e
setContentView(R.layout.activity_main);

TextView simpleText = (TextView) findViewById(R.id.simple);


simpleText.setText("That is a simple TextView");
}
}

The running application should look like the following screen shot.

148 | P a g e
Android - Drag and Drop
Android drag/drop framework allows your users to move data from one View to
another View in the current layout using a graphical drag and drop gesture. As
of API 11 drag and drop of view onto other views or view groups is
supported.The framework includes following three important components to
support drag & drop functionality −
 Drag event class.
 Drag listeners.
 Helper methods and classes.

The Drag/Drop Process


There are basically four steps or states in the drag and drop process −

 Started − This event occurs when you start dragging an item in a layout, your
application calls startDrag() method to tell the system to start a drag. The
arguments inside startDrag() method provide the data to be dragged, metadata
for this data, and a callback for drawing the drag shadow.
The system first responds by calling back to your application to get a drag
shadow. It then displays the drag shadow on the device.
Next, the system sends a drag event with action
type ACTION_DRAG_STARTED to the registered drag event listeners for all the
View objects in the current layout.
To continue to receive drag events, including a possible drop event, a drag
event listener must return true, If the drag event listener returns false, then it
will not receive drag events for the current operation until the system sends a
drag event with action type ACTION_DRAG_ENDED.
 Continuing − The user continues the drag. System sends
ACTION_DRAG_ENTERED action followed by ACTION_DRAG_LOCATION action to
the registered drag event listener for the View where dragging point enters. The
listener may choose to alter its View object's appearance in response to the
event or can react by highlighting its View.
The drag event listener receives a ACTION_DRAG_EXITED action after the user
has moved the drag shadow outside the bounding box of the View.
 Dropped − The user releases the dragged item within the bounding box of a
View. The system sends the View object's listener a drag event with action type
ACTION_DROP.
 Ended − Just after the action type ACTION_DROP, the system sends out a drag
event with action type ACTION_DRAG_ENDED to indicate that the drag operation
is over.

The DragEvent Class


The DragEvent represents an event that is sent out by the system at various
times during a drag and drop operation. This class provides few Constants and
important methods which we use during Drag/Drop process.

149 | P a g e
Constants
Following are all constants integers available as a part of DragEvent class.

Sr.N
Constants & Description
o.

1 ACTION_DRAG_STARTED
Signals the start of a drag and drop operation.

2 ACTION_DRAG_ENTERED
Signals to a View that the drag point has entered the bounding box of the View.

ACTION_DRAG_LOCATION
3 Sent to a View after ACTION_DRAG_ENTERED if the drag shadow is still
within the View object's bounding box.

ACTION_DRAG_EXITED
4 Signals that the user has moved the drag shadow outside the bounding box of
the View.

ACTION_DROP
5 Signals to a View that the user has released the drag shadow, and the drag point
is within the bounding box of the View.

6 ACTION_DRAG_ENDED
Signals to a View that the drag and drop operation has concluded.

Methods
Following are few important and most frequently used methods available as a
part of DragEvent class.

Sr.N
Constants & Description
o.

1 int getAction()
Inspect the action value of this event..

2 ClipData getClipData()
Returns the ClipData object sent to the system as part of the call to startDrag().

3 ClipDescription getClipDescription()
Returns the ClipDescription object contained in the ClipData.

150 | P a g e
4 boolean getResult()
Returns an indication of the result of the drag and drop operation.

5 float getX()
Gets the X coordinate of the drag point.

6 float getY()
Gets the Y coordinate of the drag point.

7 String toString()
Returns a string representation of this DragEvent object.

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

Listening for Drag Event


If you want any of your views within a Layout should respond Drag event then
your view either implements View.OnDragListener or
setup onDragEvent(DragEvent) callback method. When the system calls the
method or listener, it passes to them a DragEvent object explained above. You
can have both a listener and a callback method for View object. If this occurs,
the system first calls the listener and then defined callback as long as listener
returns true.
The combination of the onDragEvent(DragEvent) method
and View.OnDragListener is analogous to the combination of
the onTouchEvent() and View.OnTouchListener used with touch events in
old versions of Android.

Starting a Drag Event


You start with creating a ClipData and ClipData.Item for the data being
moved. As part of the ClipData object, supply metadata that is stored in
a ClipDescription object within the ClipData. For a drag and drop operation
that does not represent data movement, you may want to use null instead of an
actual object.
Next either you can extend extend View.DragShadowBuilder to create a drag
shadow for dragging the view or simply you can
use View.DragShadowBuilder(View) to create a default drag shadow that's the
same size as the View argument passed to it, with the touch point centered in
the drag shadow.

Example
151 | P a g e
Following example shows the functionality of a simple Drag & Drop
using View.setOnLongClickListener(), View.setOnTouchListener()and Vie
w.OnDragEventListener().
Ste
Description
p

You will use Android studio IDE to create an Android application and name it as My
1
Application under a package com.example.saira_000.myapplication.

Modify src/MainActivity.java file and add the code to define event listeners as well as a
2
call back methods for the logo image used in the example.

Copy image abc.png in res/drawable-* folders. You can use images with different
3
resolution in case you want to provide them for different devices.

Modify layout XML file res/layout/activity_main.xml to define default view of the logo
4
images.

Run the application to launch Android emulator and verify the result of the changes
5
done in the application.

Following is the content of the modified main activity


file src/MainActivity.java. This file can include each of the fundamental
lifecycle methods.
package com.example.saira_000.myapplication;

import android.app.Activity;

import android.content.ClipData;
import android.content.ClipDescription;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;

import android.view.DragEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;

import android.widget.ImageView;
import android.widget.RelativeLayout;

152 | P a g e
public class MainActivity extends Activity {
ImageView img;
String msg;
private android.widget.RelativeLayout.LayoutParams layoutParams;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img=(ImageView)findViewById(R.id.imageView);

img.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
ClipData.Item item = new
ClipData.Item((CharSequence)v.getTag());
String[] mimeTypes =
{ClipDescription.MIMETYPE_TEXT_PLAIN};

ClipData dragData = new


ClipData(v.getTag().toString(),mimeTypes, item);
View.DragShadowBuilder myShadow = new
View.DragShadowBuilder(img);

v.startDrag(dragData,myShadow,null,0);
return true;
}
});

img.setOnDragListener(new View.OnDragListener() {
@Override
public boolean onDrag(View v, DragEvent event) {
switch(event.getAction()) {
case DragEvent.ACTION_DRAG_STARTED:
layoutParams =
(RelativeLayout.LayoutParams)v.getLayoutParams();
Log.d(msg, "Action is
DragEvent.ACTION_DRAG_STARTED");

// Do nothing
break;

case DragEvent.ACTION_DRAG_ENTERED:
Log.d(msg, "Action is
DragEvent.ACTION_DRAG_ENTERED");
int x_cord = (int) event.getX();
int y_cord = (int) event.getY();
break;

153 | P a g e
case DragEvent.ACTION_DRAG_EXITED :
Log.d(msg, "Action is
DragEvent.ACTION_DRAG_EXITED");
x_cord = (int) event.getX();
y_cord = (int) event.getY();
layoutParams.leftMargin = x_cord;
layoutParams.topMargin = y_cord;
v.setLayoutParams(layoutParams);
break;

case DragEvent.ACTION_DRAG_LOCATION :
Log.d(msg, "Action is
DragEvent.ACTION_DRAG_LOCATION");
x_cord = (int) event.getX();
y_cord = (int) event.getY();
break;

case DragEvent.ACTION_DRAG_ENDED :
Log.d(msg, "Action is DragEvent.ACTION_DRAG_ENDED");

// Do nothing
break;

case DragEvent.ACTION_DROP:
Log.d(msg, "ACTION_DROP event");

// Do nothing
break;
default: break;
}
return true;
}
});

img.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
ClipData data = ClipData.newPlainText("", "");
View.DragShadowBuilder shadowBuilder = new
View.DragShadowBuilder(img);

img.startDrag(data, shadowBuilder, img, 0);


img.setVisibility(View.INVISIBLE);
return true;
} else {
return false;
}
}
});

154 | P a g e
}
}
Following will be the content of res/layout/activity_main.xml file −
In the following code abc indicates the logo of tutorialspoint.com

<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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Drag and Drop Example"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials Point"
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:textSize="30dp"
android:textColor="#ff14be3c" />>

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView2"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2"
android:layout_alignLeft="@+id/textView2"
android:layout_alignStart="@+id/textView2" />

</RelativeLayout>
Following will be the content of res/values/strings.xml to define two new
constants −

155 | P a g e
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">My Application</string>
</resources>
Following is the default content of AndroidManifest.xml −
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.saira_000.myapplication" >

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name=".MainActivity"
android:label="@string/app_name" >

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

</activity>

</application>
</manifest>
Let's try to run your My Application application. I assume you had created
your AVD while doing environment setup. To run the app from Android Studio,
open one of your project's activity files and click Run icon from the toolbar.
Android studio installs the app on your AVD and starts it and if everything is fine
with your setup and application, it will display following Emulator window −

156 | P a g e
Now do long click on the displayed TutorialsPoint logo and you will see that logo
image moves a little after 1 seconds long click from its place, its the time when
you should start dragging the image. You can drag it around the screen and
drop it at a new location.

157 | P a g e
Android - Notifications
A notification is a message you can display to the user outside of your
application's normal UI. When you tell the system to issue a notification, it first
appears as an icon in the notification area. To see the details of the notification,
the user opens the notification drawer. Both the notification area and the
notification drawer are system-controlled areas that the user can view at any
time.
Android Toast class provides a handy way to show users alerts but problem is
that these alerts are not persistent which means alert flashes on the screen for
a few seconds and then disappears.

To see the details of the notification, you will have to select the icon which will
display notification drawer having detail about the notification. While working

158 | P a g e
with emulator with virtual device, you will have to click and drag down the
status bar to expand it which will give you detail as follows. This will be just 64
dp tall and called normal view.

Above expanded form can have a Big View which will have additional detail
about the notification. You can add upto six additional lines in the notification.
The following screen shot shows such notification.

Create and Send Notifications

159 | P a g e
You have simple way to create a notification. Follow the following steps in your
application to create a notification −

Step 1 - Create Notification Builder


As a first step is to create a notification builder
using NotificationCompat.Builder.build(). You will use Notification Builder to set
various Notification properties like its small and large icons, title, priority etc.
NotificationCompat.Builder mBuilder = new
NotificationCompat.Builder(this)

Step 2 - Setting Notification Properties


Once you have Builder object, you can set its Notification properties using
Builder object as per your requirement. But this is mandatory to set at least
following −
 A small icon, set by setSmallIcon()
 A title, set by setContentTitle()
 Detail text, set by setContentText()
mBuilder.setSmallIcon(R.drawable.notification_icon);
mBuilder.setContentTitle("Notification Alert, Click Me!");
mBuilder.setContentText("Hi, This is Android Notification
Detail!");

You have plenty of optional properties which you can set for your notification. To
learn more about them, see the reference documentation for
NotificationCompat.Builder.

Step 3 - Attach Actions


This is an optional part and required if you want to attach an action with the
notification. An action allows users to go directly from the notification to
an Activity in your application, where they can look at one or more events or do
further work.
The action is defined by a PendingIntent containing an Intent that starts an
Activity in your application. To associate the PendingIntent with a gesture, call
the appropriate method of NotificationCompat.Builder. For example, if you want
to start Activity when the user clicks the notification text in the notification
drawer, you add the PendingIntent by calling setContentIntent().

A PendingIntent object helps you to perform an action on your applications


behalf, often at a later time, without caring of whether or not your application is
running.

We take help of stack builder object which will contain an artificial back stack for
the started Activity. This ensures that navigating backward from the Activity
leads out of your application to the Home screen.

160 | P a g e
Intent resultIntent = new Intent(this, ResultActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(ResultActivity.class);

// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);

Step 4 - Issue the notification


Finally, you pass the Notification object to the system by calling
NotificationManager.notify() to send your notification. Make sure you
call NotificationCompat.Builder.build() method on builder object before
notifying it. This method combines all of the options that have been set and
return a new Notification object.
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);

// notificationID allows you to update the notification later on.


mNotificationManager.notify(notificationID, mBuilder.build());

The NotificationCompat.Builder Class


The NotificationCompat.Builder class allows easier control over all the flags, as
well as help constructing the typical notification layouts. Following are few
important and most frequently used methods available as a part of
NotificationCompat.Builder class.

Sr.N
Constants & Description
o.

Notification build()
1 Combine all of the options that have been set and return a new Notification
object.

NotificationCompat.Builder setAutoCancel (boolean


2 autoCancel)
Setting this flag will make it so the notification is automatically canceled when
the user clicks it in the panel.

3 NotificationCompat.Builder setContent (RemoteViews

161 | P a g e
views)
Supply a custom RemoteViews to use instead of the standard one.

NotificationCompat.Builder setContentInfo
4 (CharSequence info)
Set the large text at the right-hand side of the notification.

NotificationCompat.Builder setContentIntent
5 (PendingIntent intent)
Supply a PendingIntent to send when the notification is clicked.

NotificationCompat.Builder setContentText
6 (CharSequence text)
Set the text (second row) of the notification, in a standard notification.

NotificationCompat.Builder setContentTitle
7 (CharSequence title)
Set the text (first row) of the notification, in a standard notification.

8 NotificationCompat.Builder setDefaults (int defaults)


Set the default notification options that will be used.

9 NotificationCompat.Builder setLargeIcon (Bitmap icon)


Set the large icon that is shown in the ticker and notification.

10 NotificationCompat.Builder setNumber (int number)


Set the large number at the right-hand side of the notification.

NotificationCompat.Builder setOngoing (boolean


11 ongoing)
Set whether this is an ongoing notification.

12 NotificationCompat.Builder setSmallIcon (int icon)


Set the small icon to use in the notification layouts.

NotificationCompat.Builder setStyle
13 (NotificationCompat.Style style)
Add a rich notification style to be applied at build time.

NotificationCompat.Builder setTicker (CharSequence


14 tickerText)
Set the text that is displayed in the status bar when the notification first arrives.

15 NotificationCompat.Builder setVibrate (long[] pattern)


Set the vibration pattern to use.

16 NotificationCompat.Builder setWhen (long when)

162 | P a g e
Set the time that the event occurred. Notifications in the panel are sorted by
this time.

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

Example
Following example shows the functionality of a Android notification using
a NotificationCompat.Builder Class which has been introduced in Android
4.1.
Ste
Description
p

You will use Android studio IDE to create an Android application and name it
1
as tutorialspoint under a package com.example.notificationdemo.

Modify src/MainActivity.java file and add the code to notify(""), if user click on the
2
button,it will call android notification service.

Create a new Java file src/NotificationView.java, which will be used to display new
3 layout as a part of new activity which will be started when user will click any of the
notifications

Modify layout XML file res/layout/activity_main.xml to add Notification button in


4
relative layout.

Create a new layout XML file res/layout/notification.xml. This will be used as layout file
5
for new activity which will start when user will click any of the notifications.

No need to change default string constants. Android studio takes care of default string
6
constants

Run the application to launch Android emulator and verify the result of the changes
7
done in the application.

Following is the content of the modified main activity


file src/com.example.notificationdemo/MainActivity.java. This file can
include each of the fundamental lifecycle methods.

163 | P a g e
package com.example.notificationdemo;

import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {


Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

b1 = (Button)findViewById(R.id.button);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
addNotification();
}
});
}

private void addNotification() {


NotificationCompat.Builder builder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.abc)
.setContentTitle("Notifications Example")
.setContentText("This is a test notification");

Intent notificationIntent = new Intent(this,


MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this,
0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);

// Add as notification
NotificationManager manager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, builder.build());
}
}
Following will be the content of res/layout/notification.xml file −

164 | P a g e
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<TextView
android:layout_width="fill_parent"
android:layout_height="400dp"
android:text="Hi, Your Detailed notification view goes
here...." />
</LinearLayout>
Following is the content of the modified main activity
file src/com.example.notificationdemo/NotificationView.java.
package com.example.notificationdemo;

import android.os.Bundle;
import android.app.Activity;

public class NotificationView extends Activity{


@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.notification);
}
}
Following will be the content of res/layout/activity_main.xml file −
<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="MainActivity">

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Notification Example"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />

165 | P a g e
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point "
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="48dp" />

<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/abc"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true"
android:layout_marginTop="42dp" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Notification"
android:id="@+id/button"
android:layout_marginTop="62dp"
android:layout_below="@+id/imageButton"
android:layout_centerHorizontal="true" />

</RelativeLayout>
Following will be the content of res/values/strings.xml to define two new
constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="action_settings">Settings</string>
<string name="app_name">tutorialspoint </string>
</resources>
Following is the default content of AndroidManifest.xml −
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.notificationdemo" >

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

166 | P a g e
<activity
android:name="com.example.notificationdemo.MainActivity"
android:label="@string/app_name" >

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

</activity>

<activity android:name=".NotificationView"
android:label="Details of notification"
android:parentActivityName=".MainActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity"/>
</activity>

</application>
</manifest>
Let's try to run your tutorialspoint application. I assume you had created
your AVD while doing environment set-up. To run the APP from Android Studio,
open one of your project's activity files and click Run icon from the toolbar.
Android Studio installs the app on your AVD and starts it and if everything is fine
with your setup and application, it will display following Emulator window −

167 | P a g e
Now click button, you will see at the top a message "New Message Alert!" will
display momentarily and after that you will have following screen having a small
icon at the top left corner.

Now lets expand the view, long click on the small icon, after a second it will
display date information and this is the time when you should drag status bar
down without releasing mouse. You will see status bar will expand and you will
get following screen −

168 | P a g e
Big View Notification
The following code snippet demonstrates how to alter the notification created in
the previous snippet to use the Inbox big view style. I'm going to update
displayNotification() modification method to show this functionality −

protected void displayNotification() {


Log.i("Start", "notification");

/* Invoking the default notification service */


NotificationCompat.Builder mBuilder = new
NotificationCompat.Builder(this);

mBuilder.setContentTitle("New Message");
mBuilder.setContentText("You've received new message.");
mBuilder.setTicker("New Message Alert!");
mBuilder.setSmallIcon(R.drawable.woman);

/* Increase notification number every time a new notification


arrives */
mBuilder.setNumber(++numMessages);

/* Add Big View Specific Configuration */


NotificationCompat.InboxStyle inboxStyle = new
NotificationCompat.InboxStyle();

String[] events = new String[6];


events[0] = new String("This is first line....");
events[1] = new String("This is second line...");
events[2] = new String("This is third line...");
events[3] = new String("This is 4th line...");
events[4] = new String("This is 5th line...");
events[5] = new String("This is 6th line...");

169 | P a g e
// Sets a title for the Inbox style big view
inboxStyle.setBigContentTitle("Big Title Details:");

// Moves events into the big view


for (int i=0; i < events.length; i++) {
inboxStyle.addLine(events[i]);
}

mBuilder.setStyle(inboxStyle);

/* Creates an explicit intent for an Activity in your app */


Intent resultIntent = new Intent(this, NotificationView.class);

TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);


stackBuilder.addParentStack(NotificationView.class);

/* Adds the Intent that starts the Activity to the top of the
stack */
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent
=stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT)
;

mBuilder.setContentIntent(resultPendingIntent);
mNotificationManager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);

/* notificationID allows you to update the notification later


on. */
mNotificationManager.notify(notificationID, mBuilder.build());
}

Now if you will try to run your application then you will find following result in
expanded form of the view −

Android - Location Based Services


Android location APIs make it easy for you to build location-aware applications,
without needing to focus on the details of the underlying location technology.
This becomes possible with the help of Google Play services, which facilitates
adding location awareness to your app with automated location tracking,
geofencing, and activity recognition.

This tutorial shows you how to use Location Services in your APP to get the
current location, get periodic location updates, look up addresses etc.

170 | P a g e
The Location Object
The Location object represents a geographic location which can consist of a
latitude, longitude, time stamp, and other information such as bearing, altitude
and velocity. There are following important methods which you can use with
Location object to get location specific information −
Sr.No. Method & Description

float distanceTo(Location dest)


1 Returns the approximate distance in meters between this location and the
given location.

2 float getAccuracy()
Get the estimated accuracy of this location, in meters.

3 double getAltitude()
Get the altitude if available, in meters above sea level.

4 float getBearing()
Get the bearing, in degrees.

5 double getLatitude()
Get the latitude, in degrees.

6 double getLongitude()
Get the longitude, in degrees.

7 float getSpeed()
Get the speed if it is available, in meters/second over ground.

8 boolean hasAccuracy()
True if this location has an accuracy.

9 boolean hasAltitude()
True if this location has an altitude.

10 boolean hasBearing()
True if this location has a bearing.

11 boolean hasSpeed()
True if this location has a speed.

12 void reset()
Clears the contents of the location.

13 void setAccuracy(float accuracy)

171 | P a g e
Set the estimated accuracy of this location, meters.

14 void setAltitude(double altitude)


Set the altitude, in meters above sea level.

15 void setBearing(float bearing)


Set the bearing, in degrees.

16 void setLatitude(double latitude)


Set the latitude, in degrees.

17 void setLongitude(double longitude)


Set the longitude, in degrees.

18 void setSpeed(float speed)


Set the speed, in meters/second over ground.

String toString()
19 Returns a string containing a concise, human-readable description of this
object.

Get the Current Location


To get the current location, create a location client which
is LocationClient object, connect it to Location Services
using connect() method, and then call its getLastLocation() method. This
method returns the most recent location in the form of Location object that
contains latitude and longitude coordinates and other information as explained
above. To have location based functionality in your activity, you will have to
implement two interfaces −
 GooglePlayServicesClient.ConnectionCallbacks
 GooglePlayServicesClient.OnConnectionFailedListener

These interfaces provide following important callback methods, which you need
to implement in your activity class −

Sr.No. Callback Methods & Description

abstract void onConnected(Bundle connectionHint)


1 This callback method is called when location service is connected to the
location client successfully. You will use connect() method to connect to
the location client.

2 abstract void onDisconnected()


This callback method is called when the client is disconnected. You will

172 | P a g e
use disconnect() method to disconnect from the location client.

abstract void onConnectionFailed(ConnectionResult


3 result)
This callback method is called when there was an error connecting the client
to the service.
You should create the location client in onCreate() method of your activity
class, then connect it in onStart(), so that Location Services maintains the
current location while your activity is fully visible. You should disconnect the
client in onStop() method, so that when your app is not visible, Location
Services is not maintaining the current location. This helps in saving battery
power up-to a large extent.

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

Get the Updated Location


If you are willing to have location updates, then apart from above mentioned
interfaces, you will need to implement LocationListener interface as well. This
interface provide following callback method, which you need to implement in
your activity class −
Sr.No. Callback Method & Description

abstract void onLocationChanged(Location location)


1 This callback method is used for receiving notifications from the
LocationClient when the location has changed.

Location Quality of Service


The LocationRequest object is used to request a quality of service (QoS) for
location updates from the LocationClient. There are following useful setter
methods which you can use to handle QoS. There are equivalent getter methods
available which you can check in Android official documentation.
Sr.No. Method & Description

1 setExpirationDuration(long millis)
Set the duration of this request, in milliseconds.

2 setExpirationTime(long millis)

173 | P a g e
Set the request expiration time, in millisecond since boot.

3 setFastestInterval(long millis)
Explicitly set the fastest interval for location updates, in milliseconds.

4 setInterval(long millis)
Set the desired interval for active location updates, in milliseconds.

5 setNumUpdates(int numUpdates)
Set the number of location updates.

6 setPriority(int priority)
Set the priority of the request.
Now for example, if your application wants high accuracy location it should
create a location request with setPriority(int) set to
PRIORITY_HIGH_ACCURACY and setInterval(long) to 5 seconds. You can also
use bigger interval and/or other priorities like PRIORITY_LOW_POWER for to
request "city" level accuracy or PRIORITY_BALANCED_POWER_ACCURACY for
"block" level accuracy.
Activities should strongly consider removing all location request when entering
the background (for example at onPause()), or at least swap the request to a
larger interval and lower quality to save power consumption.

Displaying a Location Address


Once you have Location object, you can
use Geocoder.getFromLocation() method to get an address for a given
latitude and longitude. This method is synchronous, and may take a long time to
do its work, so you should call the method from the doInBackground() method
of an AsyncTask class.
The AsyncTask must be subclassed to be used and the subclass will
override doInBackground(Params...) method to perform a task in the
background and onPostExecute(Result) method is invoked on the UI thread
after the background computation finishes and at the time to display the result.
There is one more important method available in AyncTask which
is execute(Params... params), this method executes the task with the
specified parameters.

Example
Following example shows you in practical how to to use Location Services in
your app to get the current location and its equivalent addresses etc.

174 | P a g e
To experiment with this example, you will need actual Mobile device equipped
with latest Android OS, otherwise you will have to struggle with emulator which
may not work.

Create Android Application


Ste
Description
p

You will use Android studio IDE to create an Android application and name it
1
as Tutorialspoint under a package com.example.tutorialspoint7.myapplication.

2 add src/GPSTracker.java file and add required code.

Modify src/MainActivity.java file and add required code as shown below to take care
3
of getting current location and its equivalent address.

Modify layout XML file res/layout/activity_main.xml to add all GUI components which
4
include three buttons and two text views to show location/address.

5 Modify res/values/strings.xml to define required constant values

6 Modify AndroidManifest.xml as shown below

Run the application to launch Android emulator and verify the result of the changes
7
done in the application.

Following is the content of the modified main activity file MainActivity.java.


package com.example.tutorialspoint7.myapplication;

import android.Manifest;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.test.mock.MockPackageManager;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

Button btnShowLocation;
private static final int REQUEST_CODE_PERMISSION = 2;

175 | P a g e
String mPermission = Manifest.permission.ACCESS_FINE_LOCATION;

// GPSTracker class
GPSTracker gps;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

try {
if (ActivityCompat.checkSelfPermission(this, mPermission)
!= MockPackageManager.PERMISSION_GRANTED) {

ActivityCompat.requestPermissions(this, new String[]


{mPermission},
REQUEST_CODE_PERMISSION);

// If any permission above not allowed by user, this


condition will
execute every time, else your else part will work
}
} catch (Exception e) {
e.printStackTrace();
}

btnShowLocation = (Button) findViewById(R.id.button);

// show location button click event


btnShowLocation.setOnClickListener(new View.OnClickListener()
{

@Override
public void onClick(View arg0) {
// create class object
gps = new GPSTracker(MainActivity.this);

// check if GPS enabled


if(gps.canGetLocation()){

double latitude = gps.getLatitude();


double longitude = gps.getLongitude();

// \n is for new line


Toast.makeText(getApplicationContext(), "Your
Location is - \nLat: "
+ latitude + "\nLong: " + longitude,
Toast.LENGTH_LONG).show();
}else{

176 | P a g e
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}

}
});
}
}
Following is the content of the modified main activity file GPSTracker.java.
package com.example.tutorialspoint7.myapplication;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;

public class GPSTracker extends Service implements LocationListener


{

private final Context mContext;

// flag for GPS status


boolean isGPSEnabled = false;

// flag for network status


boolean isNetworkEnabled = false;

// flag for GPS status


boolean canGetLocation = false;

Location location; // location


double latitude; // latitude
double longitude; // longitude

// The minimum distance to change Updates in meters


private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
// 10 meters

177 | P a g e
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
// 1 minute

// Declaring a Location Manager


protected LocationManager locationManager;

public GPSTracker(Context context) {


this.mContext = context;
getLocation();
}

public Location getLocation() {


try {
locationManager = (LocationManager)
mContext.getSystemService(LOCATION_SERVICE);

// getting GPS status


isGPSEnabled =
locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

// getting network status


isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

if (!isGPSEnabled && !isNetworkEnabled) {


// no network provider is enabled
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_
PROVIDER);

if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}

178 | P a g e
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

Log.d("GPS Enabled", "GPS Enabled");


if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_P
ROVIDER);

if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}

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

return location;
}

/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */

public void stopUsingGPS(){


if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}

/**
* Function to get latitude
* */

public double getLatitude(){


if(location != null){
latitude = location.getLatitude();
}

179 | P a g e
// return latitude
return latitude;
}

/**
* Function to get longitude
* */

public double getLongitude(){


if(location != null){
longitude = location.getLongitude();
}

// return longitude
return longitude;
}

/**
* Function to check GPS/wifi enabled
* @return boolean
* */

public boolean canGetLocation() {


return this.canGetLocation;
}

/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */

public void showSettingsAlert(){


AlertDialog.Builder alertDialog = new
AlertDialog.Builder(mContext);

// Setting Dialog Title


alertDialog.setTitle("GPS is settings");

// Setting Dialog Message


alertDialog.setMessage("GPS is not enabled. Do you want to go
to settings menu?");

// On pressing Settings button


alertDialog.setPositiveButton("Settings", new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new
Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);

180 | P a g e
mContext.startActivity(intent);
}
});

// on pressing cancel button


alertDialog.setNegativeButton("Cancel", new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});

// Showing Alert Message


alertDialog.show();
}

@Override
public void onLocationChanged(Location location) {
}

@Override
public void onProviderDisabled(String provider) {
}

@Override
public void onProviderEnabled(String provider) {
}

@Override
public void onStatusChanged(String provider, int status, Bundle
extras) {
}

@Override
public IBinder onBind(Intent arg0) {
return null;
}
}
Following will be the content of res/layout/activity_main.xml file −
<?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" >

<Button

181 | P a g e
android:id = "@+id/button"
android:layout_width = "fill_parent"
android:layout_height = "wrap_content"
android:text = "getlocation"/>

</LinearLayout>
Following will be the content of res/values/strings.xml to define two new
constants −
<?xml version = "1.0" encoding = "utf-8"?>
<resources>
<string name = "app_name">Tutorialspoint</string>
</resources>
Following is the default content of AndroidManifest.xml −
<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android =
"http://schemas.android.com/apk/res/android"
package = "com.example.tutorialspoint7.myapplication">
<uses-permission android:name =
"android.permission.ACCESS_FINE_LOCATION" />
<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>
Let's try to run your Tutorialspoint application. I assume that, you have
connected your actual Android Mobile device with your computer. To run the
app from Android Studio, open one of your project's activity files and click Run
icon from the toolbar. Before starting your application, Android studio installer
will display following window to select an option where you want to run your
Android application.

182 | P a g e
Now to see location select Get Location Button which will display location
information as follows −

183 | P a g e
Android - Sending Email
Email is messages distributed by electronic means from one system user to
one or more recipients via a network.

Before starting Email Activity, You must know Email functionality with intent,
Intent is carrying data from one component to another component with-in the
application or outside the application.

To send an email from your application, you don’t have to implement an email
client from the beginning, but you can use an existing one like the default Email

184 | P a g e
app provided from Android, Gmail, Outlook, K-9 Mail etc. For this purpose, we
need to write an Activity that launches an email client, using an implicit Intent
with the right action and data. In this example, we are going to send an email
from our app by using an Intent object that launches existing email clients.

Following section explains different parts of our Intent object required to send an
email.

Intent Object - Action to send Email


You will use ACTION_SEND action to launch an email client installed on your
Android device. Following is simple syntax to create an intent with
ACTION_SEND action.
Intent emailIntent = new Intent(Intent.ACTION_SEND);

Intent Object - Data/Type to send Email


To send an email you need to specify mailto: as URI using setData() method
and data type will be to text/plain using setType() method as follows −
emailIntent.setData(Uri.parse("mailto:"));
emailIntent.setType("text/plain");

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

Intent Object - Extra to send Email


Android has built-in support to add TO, SUBJECT, CC, TEXT etc. fields which can
be attached to the intent before sending the intent to a target email client. You
can use following extra fields in your email −

Sr.No. Extra Data & Description

1 EXTRA_BCC
A String[] holding e-mail addresses that should be blind carbon copied.

2 EXTRA_CC
A String[] holding e-mail addresses that should be carbon copied.

3 EXTRA_EMAIL
A String[] holding e-mail addresses that should be delivered to.

185 | P a g e
EXTRA_HTML_TEXT
4 A constant String that is associated with the Intent, used with
ACTION_SEND to supply an alternative to EXTRA_TEXT as HTML
formatted text.

5 EXTRA_SUBJECT
A constant string holding the desired subject line of a message.

EXTRA_TEXT
6 A constant CharSequence that is associated with the Intent, used with
ACTION_SEND to supply the literal data to be sent.

EXTRA_TITLE
7 A CharSequence dialog title to provide to the user when used with a
ACTION_CHOOSER.

Here is an example showing you how to assign extra data to your intent −

emailIntent.putExtra(Intent.EXTRA_EMAIL , new String[]{"Recipient"});


emailIntent.putExtra(Intent.EXTRA_SUBJECT, "subject");
emailIntent.putExtra(Intent.EXTRA_TEXT , "Message Body");

The out-put of above code is as below shown an image

186 | P a g e
Email Example

Example
Following example shows you in practical how to use Intent object to launch
Email client to send an Email to the given recipients.

To Email experiment with this example, you will need actual Mobile device
equipped with latest Android OS, otherwise you might get struggle with
emulator which may not work properly. Second you will need to have an Email
client like GMail(By default every android version having Gmail client App) or
K9mail installed on your device.

Ste
Description
p

You will use Android studio to create an Android application and name it
1
as Tutorialspoint under a package com.example.tutorialspoint.

2 Modify src/MainActivity.java file and add required code to take care of sending email.

Modify layout XML file res/layout/activity_main.xml add any GUI component if


3
required. I'm adding a simple button to launch Email Client.

4 Modify res/values/strings.xml to define required constant values

5 Modify AndroidManifest.xml as shown below

Run the application to launch Android emulator and verify the result of the changes
6
done in the application.

Following is the content of the modified main activity


file src/com.example.Tutorialspoint/MainActivity.java.
package com.example.tutorialspoint;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;

187 | P a g e
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Button startBtn = (Button) findViewById(R.id.sendEmail);


startBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendEmail();
}
});
}

protected void sendEmail() {


Log.i("Send email", "");
String[] TO = {""};
String[] CC = {""};
Intent emailIntent = new Intent(Intent.ACTION_SEND);

emailIntent.setData(Uri.parse("mailto:"));
emailIntent.setType("text/plain");
emailIntent.putExtra(Intent.EXTRA_EMAIL, TO);
emailIntent.putExtra(Intent.EXTRA_CC, CC);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Your subject");
emailIntent.putExtra(Intent.EXTRA_TEXT, "Email message goes
here");

try {
startActivity(Intent.createChooser(emailIntent, "Send
mail..."));
finish();
Log.i("Finished sending email...", "");
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(MainActivity.this, "There is no email
client installed.", Toast.LENGTH_SHORT).show();
}
}
}
Following will be the content of res/layout/activity_main.xml file −
Here abc indicates about tutorialspoint logo

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"

188 | P a g e
android:orientation="vertical" >

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sending Mail Example"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point "
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_above="@+id/imageButton"
android:layout_alignRight="@+id/imageButton"
android:layout_alignEnd="@+id/imageButton" />

<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/abc"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />

<Button
android:id="@+id/sendEmail"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/compose_email"/>

</LinearLayout>
Following will be the content of res/values/strings.xml to define two new
constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Tutorialspoint</string>
<string name="compose_email">Compose Email</string>
</resources>
Following is the default content of AndroidManifest.xml −
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"

189 | P a g e
package="com.example.Tutorialspoint" >

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name="com.example.tutorialspoint.MainActivity"
android:label="@string/app_name" >

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

</activity>

</application>
</manifest>
Let's try to run your tutorialspoint application. I assume you have connected
your actual Android Mobile device with your computer. To run the app from
Android Studio, open one of your project's activity files and click Run icon from
the toolbar. Before starting your application, Android studio installer will display
following window to select an option where you want to run your Android
application.Select your mobile device as an option and then check your mobile
device which will display following screen −

190 | P a g e
Now use Compose Email button to list down all the installed email clients.
From the list, you can choose one of email clients to send your email. I'm going
to use Gmail client to send my email which will have all the provided defaults
fields available as shown below. Here From: will be default email ID you have
registered for your Android device.

191 | P a g e
You can modify either of the given default fields and finally use send email
button to send your email to the mentioned recipients.

Android - Sending SMS


n Android, you can use SmsManager API or devices Built-in SMS application to
send SMS's. In this tutorial, we shows you two basic examples to send SMS
message −

SmsManager API

SmsManager smsManager = SmsManager.getDefault();

192 | P a g e
smsManager.sendTextMessage("phoneNo", null, "sms message", null, null);

Built-in SMS application

Intent sendIntent = new Intent(Intent.ACTION_VIEW);


sendIntent.putExtra("sms_body", "default content");
sendIntent.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent);

Of course, both need SEND_SMS permission.

<uses-permission android:name="android.permission.SEND_SMS" />

Apart from the above method, there are few other important functions available
in SmsManager class. These methods are listed below −

Sr.No
Method & Description
.

ArrayList<String> divideMessage(String text)


1 This method divides a message text into several fragments, none bigger than
the maximum SMS message size.

static SmsManager getDefault()


2
This method is used to get the default instance of the SmsManager

void sendDataMessage(String destinationAddress,


String scAddress, short destinationPort, byte[] data,
3 PendingIntent sentIntent, PendingIntent
deliveryIntent)
This method is used to send a data based SMS to a specific application port.

void sendMultipartTextMessage(String
destinationAddress, String scAddress,
ArrayList<String> parts, ArrayList<PendingIntent>
4
sentIntents, ArrayList<PendingIntent>
deliveryIntents)
Send a multi-part text based SMS.

void sendTextMessage(String destinationAddress,


String scAddress, String text, PendingIntent
5
sentIntent, PendingIntent deliveryIntent)
Send a text based SMS.

193 | P a g e
Example
Following example shows you in practical how to use SmsManager object to
send an SMS to the given mobile number.

To experiment with this example, you will need actual Mobile device equipped
with latest Android OS, otherwise you will have to struggle with emulator which
may not work.

Ste
Description
p

You will use Android Studio IDE to create an Android application and name it
1
as tutorialspoint under a package com.example.tutorialspoint.

Modify src/MainActivity.java file and add required code to take care of sending
2
sms.

Modify layout XML file res/layout/activity_main.xml add any GUI component


3 if required. I'm adding a simple GUI to take mobile number and SMS text to be
sent and a simple button to send SMS.

No need to define default string constants at res/values/strings.xml. Android


4
studio takes care of default constants.

5 Modify AndroidManifest.xml as shown below

Run the application to launch Android emulator and verify the result of the
6
changes done in the application.

Following is the content of the modified main activity


file src/com.example.tutorialspoint/MainActivity.java.

package com.example.tutorialspoint;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.app.Activity;

import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.telephony.SmsManager;

import android.util.Log;
import android.view.Menu;
import android.view.View;

194 | P a g e
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {


private static final int MY_PERMISSIONS_REQUEST_SEND_SMS =0 ;
Button sendBtn;
EditText txtphoneNo;
EditText txtMessage;
String phoneNo;
String message;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

sendBtn = (Button) findViewById(R.id.btnSendSMS);


txtphoneNo = (EditText) findViewById(R.id.editText);
txtMessage = (EditText) findViewById(R.id.editText2);

sendBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendSMSMessage();
}
});
}

protected void sendSMSMessage() {


phoneNo = txtphoneNo.getText().toString();
message = txtMessage.getText().toString();

if (ContextCompat.checkSelfPermission(this,
Manifest.permission.SEND_SMS)
!= PackageManager.PERMISSION_GRANTED) {
if
(ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.SEND_SMS)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.SEND_SMS},
MY_PERMISSIONS_REQUEST_SEND_SMS);
}
}
}

@Override

195 | P a g e
public void onRequestPermissionsResult(int requestCode,String
permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_SEND_SMS: {
if (grantResults.length > 0
&& grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null,
message, null, null);
Toast.makeText(getApplicationContext(), "SMS
sent.",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again.",
Toast.LENGTH_LONG).show();
return;
}
}
}

}
}

Following will be the content of res/layout/activity_main.xml file −

Here abc indicates about tutorialspoint logo


<?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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="MainActivity">

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sending SMS Example"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />

196 | P a g e
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point "
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_below="@+id/textView1"
android:layout_alignRight="@+id/imageButton"
android:layout_alignEnd="@+id/imageButton" />

<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/abc"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:hint="Enter Phone Number"
android:phoneNumber="true"
android:textColorHint="@color/abc_primary_text_material_dark"
android:layout_below="@+id/imageButton"
android:layout_centerHorizontal="true" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText2"
android:layout_below="@+id/editText"
android:layout_alignLeft="@+id/editText"
android:layout_alignStart="@+id/editText"
android:textColorHint="@color/abc_primary_text_material_dark"
android:layout_alignRight="@+id/imageButton"
android:layout_alignEnd="@+id/imageButton"
android:hint="Enter SMS" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send Sms"
android:id="@+id/btnSendSMS"
android:layout_below="@+id/editText2"
android:layout_centerHorizontal="true"

197 | P a g e
android:layout_marginTop="48dp" />

</RelativeLayout>

Following will be the content of res/values/strings.xml to define two new


constants −

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


<resources>
<string name="app_name">tutorialspoint</string>
</resources>

Following is the default content of AndroidManifest.xml −

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


<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tutorialspoint" >

<uses-permission android:name="android.permission.SEND_SMS" />

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name="com.example.tutorialspoint.MainActivity"
android:label="@string/app_name" >

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

</activity>

</application>
</manifest>

Let's try to run your tutorialspoint application. I assume you have connected
your actual Android Mobile device with your computer. To run the app from
Android studio, open one of your project's activity files and click Run icon from
the toolbar. Before starting your application, Android studio installer will display

198 | P a g e
following window to select an option where you want to run your Android
application.

Now you can enter a desired mobile number and a text message to be sent on
that number. Finally click on Send SMS button to send your SMS. Make sure
your GSM/CDMA connection is working fine to deliver your SMS to its recipient.

You can take a number of SMS separated by comma and then inside your
program you will have to parse them into an array string and finally you can use
a loop to send message to all the given numbers. That's how you can write your
own SMS client. Next section will show you how to use existing SMS client to
send SMS.

Using Built-in Intent to send SMS


You can use Android Intent to send SMS by calling built-in SMS functionality of
the Android. Following section explains different parts of our Intent object
required to send an SMS.

199 | P a g e
Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

Intent Object - Action to send SMS


You will use ACTION_VIEW action to launch an SMS client installed on your
Android device. Following is simple syntax to create an intent with ACTION_VIEW
action.

Intent smsIntent = new Intent(Intent.ACTION_VIEW);

Intent Object - Data/Type to send SMS


To send an SMS you need to specify smsto: as URI using setData() method and
data type will be to vnd.android-dir/mms-sms using setType() method as
follows −

smsIntent.setData(Uri.parse("smsto:"));
smsIntent.setType("vnd.android-dir/mms-sms");

Intent Object - Extra to send SMS


Android has built-in support to add phone number and text message to send an
SMS as follows −

smsIntent.putExtra("address" , new String("0123456789;3393993300"));


smsIntent.putExtra("sms_body" , "Test SMS to Angilla");
Here address and sms_body are case sensitive and should be specified in small
characters only. You can specify more than one number in single string but
separated by semi-colon (;).

Example
Following example shows you in practical how to use Intent object to launch
SMS client to send an SMS to the given recipients.

To experiment with this example, you will need actual Mobile device equipped
with latest Android OS, otherwise you will have to struggle with emulator which
may not work.

Ste
Description
p

200 | P a g e
You will use Android studio IDE to create an Android application and name it
1
as tutorialspoint under a package com.example.tutorialspoint.

Modify src/MainActivity.java file and add required code to take care of sending
2
SMS.

Modify layout XML file res/layout/activity_main.xml add any GUI component


3
if required. I'm adding a simple button to launch SMS Client.

No need to define default constants.Android studio takes care of default


4
constants.

5 Modify AndroidManifest.xml as shown below

Run the application to launch Android emulator and verify the result of the
6
changes done in the application.

Following is the content of the modified main activity


file src/com.example.tutorialspoint/MainActivity.java.

package com.example.tutorialspoint;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Button startBtn = (Button) findViewById(R.id.button);


startBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendSMS();
}
});
}

protected void sendSMS() {

201 | P a g e
Log.i("Send SMS", "");
Intent smsIntent = new Intent(Intent.ACTION_VIEW);

smsIntent.setData(Uri.parse("smsto:"));
smsIntent.setType("vnd.android-dir/mms-sms");
smsIntent.putExtra("address" , new String ("01234"));
smsIntent.putExtra("sms_body" , "Test ");

try {
startActivity(smsIntent);
finish();
Log.i("Finished sending SMS...", "");
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(MainActivity.this,
"SMS faild, please try again later.",
Toast.LENGTH_SHORT).show();
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it
is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

Following will be the content of res/layout/activity_main.xml file −

Here abc indicates about tutorialspoint logo


<?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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Drag and Drop Example"
android:id="@+id/textView"

202 | P a g e
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials Point "
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:textSize="30dp"
android:textColor="#ff14be3c" />

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_marginTop="48dp"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Compose SMS"
android:id="@+id/button"
android:layout_below="@+id/imageView"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2"
android:layout_marginTop="54dp"
android:layout_alignLeft="@+id/imageView"
android:layout_alignStart="@+id/imageView" />

</RelativeLayout>

Following will be the content of res/values/strings.xml to define two new


constants −

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


<resources>
<string name="app_name">tutorialspoint</string>
</resources>

Following is the default content of AndroidManifest.xml −

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

203 | P a g e
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tutorialspoint" >

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name="com.example.tutorialspoint.MainActivity"
android:label="@string/app_name" >

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

</activity>

</application>
</manifest>

Let's try to run your tutorialspoint application. I assume you have connected
your actual Android Mobile device with your computer. To run the app from
Android studio, open one of your project's activity files and click Run icon from
the toolbar. Before starting your application, Android studio will display following
window to select an option where you want to run your Android application.

204 | P a g e
Select your mobile device as an option and then check your mobile device which
will display following screen −

205 | P a g e
Now use Compose SMS button to launch Android built-in SMS clients which is
shown below −

206 | P a g e
You can modify either of the given default fields and finally use send SMS button
to send your SMS to the mentioned recipient.

207 | P a g e
Android - Phone Calls
Android provides Built-in applications for phone calls, in some occasions we may
need to make a phone call through our application. This could easily be done by
using implicit Intent with appropriate actions. Also, we can use
PhoneStateListener and TelephonyManager classes, in order to monitor the
changes in some telephony states on the device.

This chapter lists down all the simple steps to create an application which can
be used to make a Phone Call. You can use Android Intent to make phone call by
calling built-in Phone Call functionality of the Android. Following section explains
different parts of our Intent object required to make a call.

Intent Object - Action to make Phone Call


You will use ACTION_CALL action to trigger built-in phone call functionality
available in Android device. Following is simple syntax to create an intent with
ACTION_CALL action

Intent phoneIntent = new Intent(Intent.ACTION_CALL);

You can use ACTION_DIAL action instead of ACTION_CALL, in that case you will
have option to modify hardcoded phone number before making a call instead of
making a direct call.

Intent Object - Data/Type to make Phone Call


To make a phone call at a given number 91-000-000-0000, you need to
specify tel: as URI using setData() method as follows −

phoneIntent.setData(Uri.parse("tel:91-000-000-0000"));

The interesting point is that, to make a phone call, you do not need to specify
any extra data or data type.

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

Example

208 | P a g e
Following example shows you in practical how to use Android Intent to make
phone call to the given mobile number.

To experiment with this example, you will need actual Mobile device equipped
with latest Android OS, otherwise you will have to struggle with emulator which
may not work.

Ste
Description
p

You will use Android studio IDE to create an Android application and name it
1
as My Application under a package com.example.saira_000.myapplication.

Modify src/MainActivity.java file and add required code to take care of making
2
a call.

Modify layout XML file res/layout/activity_main.xml add any GUI component


3
if required. I'm adding a simple button to Call 91-000-000-0000 number

No need to define default string constants.Android studio takes care of default


4
constants.

5 Modify AndroidManifest.xml as shown below

Run the application to launch Android emulator and verify the result of the
6
changes done in the application.

Following is the content of the modified main activity


file src/MainActivity.java.

package com.example.saira_000.myapplication;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {


private Button button;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

209 | P a g e
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.buttonCall);

button.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:0377778888"));

if
(ActivityCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.CALL_PHONE) !=
PackageManager.PERMISSION_GRANTED) {
return;
}
startActivity(callIntent);
}
});

}
}

Following will be the content of res/layout/activity_main.xml file −

<?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" >

<Button
android:id="@+id/buttonCall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="call 0377778888" />

</LinearLayout>

Following will be the content of res/values/strings.xml to define two new


constants −

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


<resources>
<string name="app_name">My Application</string>
</resources>

Following is the default content of AndroidManifest.xml −

210 | P a g e
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.saira_000.myapplication" >

<uses-permission android:name="android.permission.CALL_PHONE" />

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity

android:name="com.example.saira_000.myapplication.MainActivity"
android:label="@string/app_name" >

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

</activity>

</application>
</manifest>

Let's try to run your My Application application. I assume you have connected
your actual Android Mobile device with your computer. To run the app from
Android studio, open one of your project's activity files and click Run icon from
the toolbar.Select your mobile device as an option and then check your mobile
device which will display following screen −

211 | P a g e
Now use Call button to make phone call as shown below −

212 | P a g e
Publishing Android Application
Android application publishing is a process that makes your Android applications
available to users. Infect, publishing is the last phase of the Android application
development process.

213 | P a g e
Android development life cycle
Once you developed and fully tested your Android Application, you can start
selling or distributing free using Google Play (A famous Android marketplace).
You can also release your applications by sending them directly to users or by
letting users download them from your own website.

You can check a detailed publishing process at Android official website, but this
tutorial will take you through simple steps to launch your application on Google
Play. Here is a simplified check list which will help you in launching your Android
application −

Ste
Activity
p

Regression Testing Before you publish your application, you need to make sure
that its meeting the basic quality expectations for all Android apps, on all of the
1
devices that you are targeting. So perform all the required testing on different devices
including phone and tablets.

2 Application Rating When you will publish your application at Google Play, you
will have to specify a content rating for your app, which informs Google Play users of
its maturity level. Currently available ratings are (a) Everyone (b) Low maturity (c)

214 | P a g e
Medium maturity (d) High maturity.

Targeted Regions Google Play lets you control what countries and territories
3 where your application will be sold. Accordingly you must take care of setting up time
zone, localization or any other specific requirement as per the targeted region.

Application Size Currently, the maximum size for an APK published on Google
Play is 50 MB. If your app exceeds that size, or if you want to offer a secondary
4
download, you can use APK Expansion Files, which Google Play will host for free on its
server infrastructure and automatically handle the download to devices.

SDK and Screen Compatibility It is important to make sure that your app is
5 designed to run properly on the Android platform versions and device screen sizes that
you want to target.

Application Pricing Deciding whether you app will be free or paid is important
6 because, on Google Play, free app's must remain free. If you want to sell your
application then you will have to specify its price in different currencies.

Promotional Content It is a good marketing practice to supply a variety of high-


7 quality graphic assets to showcase your app or brand. After you publish, these appear
on your product details page, in store listings and search results, and elsewhere.

Build and Upload release-ready APK The release-ready APK is what you
you will upload to the Developer Console and distribute to users. You can check
8
complete detail on how to create a release-ready version of your app: Preparing
for Release.

Finalize Application Detail Google Play gives you a variety of ways to


promote your app and engage with users on your product details page, from colourful
9 graphics, screen shots, and videos to localized descriptions, release details, and links to
your other apps. So you can decorate your application page and provide as much as
clear crisp detail you can provide.

Export Android Application Process

215 | P a g e
Apk development process
Before exporting the apps, you must some of tools

 Dx tools(Dalvik executable tools ): It going to convert .class file to .dex file. it


has useful for memory optimization and reduce the boot-up speed time
 AAPT(Android assistance packaging tool):it has useful to convert .Dex
file to.Apk
 APK(Android packaging kit): The final stage of deployment process is called
as .apk.

You will need to export your application as an APK (Android Package) file before
you upload it Google Play marketplace.

To export an application, just open that application project in Android studio and
select Build → Generate Signed APK from your Android studio and follow the
simple steps to export your application −

216 | P a g e
Next select, Generate Signed APK option as shown in the above screen shot
and then click it so that you get following screen where you will choose Create
new keystore to store your application.

Enter your key store path,key store password,key alias and key password to
protect your application and click on Next button once again. It will display
following screen to let you create an application −

217 | P a g e
Once you filled up all the information,like app destination,build type and flavours
click finish button While creating an application it will show as below

Finally, it will generate your Android Application as APK formate File which will
be uploaded at Google Play marketplace.

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

Google Play Registration


The most important step is to register with Google Play using Google Play
Marketplace. You can use your existing google ID if you have any otherwise you
can create a new Google ID and then register with the marketplace. You will
have following screen to accept terms and condition.

218 | P a g e
You can use Continue to payment button to proceed to make a payment of
$25 as a registration fee and finally to complete your account detail.
Once you are a registered user at Google Play, you can upload release-ready
APK for your application and finally you will complete application detail using
application detail page as mentioned in step 9 of the above mentioned checklist.

Signing Your App Manually


You do not need Android Studio to sign your app. You can sign your app from
the command line using standard tools from the Android SDK and the JDK. To
sign an app in release mode from the command line −

 Generate a private key using keytool


$ keytool -genkey -v -keystore my-release-key.keystore
-alias alias_name -keyalg RSA -keysize 2048 -validity 10000
 Compile your app in release mode to obtain an unsigned APK
 Sign your app with your private key using jarsigner
$ jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1
-keystore my-release-key.keystore my_application.apk alias_name
 Verify that your APK is signed. For example −
$ jarsigner -verify -verbose -certs my_application.apk
 Align the final APK package using zipalign.
$ zipalign -v 4 your_project_name-unaligned.apk
your_project_name.apk

219 | P a g e
Some of App markets


Google play


Amazon AppStore

220 | P a g e
F-Droid


Samsung Galaxy AppStore

Android - Alert Dialog


A Dialog is small window that prompts the user to a decision or enter additional
information.

Some times in your application, if you wanted to ask the user about taking a
decision between yes or no in response of any particular action taken by the
user, by remaining in the same activity and without changing the screen, you
can use Alert Dialog.

In order to make an alert dialog, you need to make an object of


AlertDialogBuilder which an inner class of AlertDialog. Its syntax is given below

AlertDialog.Builder alertDialogBuilder = new


AlertDialog.Builder(this);

Now you have to set the positive (yes) or negative (no) button using the object
of the AlertDialogBuilder class. Its syntax is

alertDialogBuilder.setPositiveButton(CharSequence text,
DialogInterface.OnClickListener listener)
alertDialogBuilder.setNegativeButton(CharSequence text,
DialogInterface.OnClickListener listener)

Apart from this , you can use other functions provided by the builder class to
customize the alert dialog. These are listed below

Sr.N
Method type & description
o

221 | P a g e
setIcon(Drawable icon)
1
This method set the icon of the alert dialog box.

setCancelable(boolean cancel able)


2
This method sets the property that the dialog can be cancelled or not

setMessage(CharSequence message)
3
This method sets the message to be displayed in the alert dialog

setMultiChoiceItems(CharSequence[] items, boolean[]


checkedItems,
4 DialogInterface.OnMultiChoiceClickListener listener)
This method sets list of items to be displayed in the dialog as the content. The
selected option will be notified by the listener

5 setOnCancelListener(DialogInterface.OnCancelListener
onCancelListener)
This method Sets the callback that will be called if the dialog is cancelled.

setTitle(CharSequence title)
6
This method set the title to be appear in the dialog

After creating and setting the dialog builder , you will create an alert dialog by
calling the create() method of the builder class. Its syntax is

AlertDialog alertDialog = alertDialogBuilder.create();


alertDialog.show();

This will create the alert dialog and will show it on the screen.

Dialog fragment
Before enter into an example we should need to know dialog fragment.Dialog
fragment is a fragment which can show fragment in dialog box

public class DialogFragment extends DialogFragment {


@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new
AlertDialog.Builder(getActivity());
builder.setPositiveButton(R.string.fire, new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {

222 | P a g e
toast.makeText(this,"enter a text
here",Toast.LENTH_SHORT).show();
}
})
.setNegativeButton(R.string.cancel, new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
});
// Create the AlertDialog object and return it
return builder.create();
}
}
}

List dialog
It has used to show list of items in a dialog box.For suppose, user need to select
a list of items or else need to click a item from multiple list of items.At this
situation we can use list dialog.

public Dialog onCreateDialog(Bundle savedInstanceState) {


AlertDialog.Builder builder = new
AlertDialog.Builder(getActivity());
builder.setTitle(Pick a Color)

.setItems(R.array.colors_array, new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
}
});
return builder.create();
}

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

Single-choice list dialog


It has used to add single choice list to Dialog box.We can check or uncheck as
per user choice.

public Dialog onCreateDialog(Bundle savedInstanceState) {

223 | P a g e
mSelectedItems = new ArrayList();
AlertDialog.Builder builder = new
AlertDialog.Builder(getActivity());

builder.setTitle("This is list choice dialog box");


.setMultiChoiceItems(R.array.toppings, null,
new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {

if (isChecked) {
// If the user checked the item, add it to the selected
items
mSelectedItems.add(which);
}

else if (mSelectedItems.contains(which)) {
// Else, if the item is already in the array, remove it
mSelectedItems.remove(Integer.valueOf(which));
}
}
})

// Set the action buttons


.setPositiveButton(R.string.ok, new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
// User clicked OK, so save the mSelectedItems results
somewhere
// or return them to the component that opened the dialog
...
}
})

.setNegativeButton(R.string.cancel, new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
...
}
});
return builder.create();
}

Example

224 | P a g e
The following example demonstrates the use of AlertDialog in android.

To experiment with this example , you need to run this on an emulator or an


actual device.

Ste
Description
ps

You will use Android studio to create an Android application and name it as
1
My Application under a package com.example.sairamkrishna.myapplication.

2 Modify src/MainActivity.java file to add alert dialog code to launch the dialog.

Modify layout XML file res/layout/activity_main.xml add any GUI component


3
if required.

No need to change default string constants. Android studio takes care of default
4
strings at values/string.xml

Run the application and choose a running android device and install the
5
application on it and verify the results.

Here is the modified code of src/MainActivity.java

package com.example.sairamkrishna.myapplication;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

public void open(View view){


AlertDialog.Builder alertDialogBuilder = new
AlertDialog.Builder(this);
alertDialogBuilder.setMessage("Are you sure,
You wanted to make decision");
alertDialogBuilder.setPositiveButton("yes",
new DialogInterface.OnClickListener() {

225 | P a g e
@Override
public void onClick(DialogInterface arg0, int arg1) {
Toast.makeText(MainActivity.this,"You clicked yes
button",Toast.LENGTH_LONG).show();
}
});

alertDialogBuilder.setNegativeButton("No",new
DialogInterface.OnClickListener() {
Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});

AlertDialog alertDialog = alertDialogBuilder.create();


alertDialog.show();
}
}

Here is the modified code of res/layout/activity_main.xml

In the below code abc indicates the logo of tutorialspoint.com


<?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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Alert Dialog"
android:id="@+id/textView"
android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorialspoint"

226 | P a g e
android:id="@+id/textView2"
android:textColor="#ff3eff0f"
android:textSize="35dp"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true" />

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView2"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2"
android:layout_alignLeft="@+id/textView"
android:layout_alignStart="@+id/textView" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Alert dialog"
android:id="@+id/button"
android:layout_below="@+id/imageView"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2"
android:layout_marginTop="42dp"
android:onClick="open"
android:layout_alignLeft="@+id/imageView"
android:layout_alignStart="@+id/imageView" />

</RelativeLayout>

Here is ofStrings.xml

<resources>
<string name="app_name">My Application</string>
</resources>

Here is the default code of AndroidManifest.xml

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


<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"

227 | P a g e
android:theme="@style/AppTheme" >

<activity

android:name="com.example.sairamkrishna.myapplication.MainActivity"
android:label="@string/app_name" >

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

</activity>

</application>
</manifest>

Let's try to run your application. I assume you have connected your actual
Android Mobile device with your computer. To run the app from Android studio,
open one of your project's activity files and click Run icon from the toolbar.
Before starting your application, ]Android studio will display following window to
select an option where you want to run your Android application.

228 | P a g e
Select your an option and then click on it. For suppose, if you have clicked on
yes button, then result would as follows

229 | P a g e
if you click on no button it will call finish() and it will close your application.

230 | P a g e
Android - Animations
Animation is the process of creating motion and shape change

Animation in android is possible from many ways. In this chapter we will discuss
one easy and widely used way of making animation called tweened animation.

Tween Animation
Tween Animation takes some parameters such as start value , end value, size ,
time duration , rotation angle e.t.c and perform the required animation on that
object. It can be applied to any type of object. So in order to use this , android
has provided us a class called Animation.

In order to perform animation in android , we are going to call a static function


loadAnimation() of the class AnimationUtils. We are going to receive the result in
an instance of Animation Object. Its syntax is as follows −

Animation animation =
AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.myanimation);

Note the second parameter. It is the name of the our animation xml file. You
have to create a new folder called anim under res directory and make an xml
file under anim folder.

This animation class has many useful functions which are listed below −

Sr.No Method & Description

start()
1
This method starts the animation.

setDuration(long duration)
2
This method sets the duration of an animation.

getDuration()
3
This method gets the duration which is set by above method

end()
4
This method ends the animation.

cancel()
5
This method cancels the animation.

231 | P a g e
In order to apply this animation to an object , we will just call the
startAnimation() method of the object. Its syntax is −

ImageView image1 = (ImageView)findViewById(R.id.imageView1);


image.startAnimation(animation);

Example
The following example demonstrates the use of Animation in android. You would
be able to choose different type of animation from the menu and the selected
animation will be applied on an imageView on the screen.

To experiment with this example , you need to run this on an emulator or an


actual device.

Ste
Description
ps

You will use Android studio IDE to create an Android application and name it as My
1
Application under a package com.example.sairamkrishna.myapplication.

2 Modify src/MainActivity.java file to add animation code

Modify layout XML file res/layout/activity_main.xml add any GUI component if


3
required.

Create a new folder under res directory and call it anim. Confim it by visiting
4
res/anim

Right click on anim and click on new and select Android XML file You have to
5
create different files that are listed below.

Create files myanimation.xml,clockwise.xml,fade.xml,move.xml,blink.xml,slide.xml


6
and add the XML code.

No need to change default string constants. Android studio takes care of default
7
constants at values/string.xml.

Run the application and choose a running android device and install the application
8
on it and verify the results.

Here is the modified code of MainActivity.java.

package com.example.sairamkrishna.myapplication;

import android.app.Activity;

232 | P a g e
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

public void clockwise(View view){


ImageView image = (ImageView)findViewById(R.id.imageView);
Animation animation =
AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.myanimation);
image.startAnimation(animation);
}

public void zoom(View view){


ImageView image = (ImageView)findViewById(R.id.imageView);
Animation animation1 =
AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.clockwise);
image.startAnimation(animation1);
}

public void fade(View view){


ImageView image = (ImageView)findViewById(R.id.imageView);
Animation animation1 =
AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.fade);
image.startAnimation(animation1);
}

public void blink(View view){


ImageView image = (ImageView)findViewById(R.id.imageView);
Animation animation1 =
AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.blink);
image.startAnimation(animation1);
}

public void move(View view){


ImageView image = (ImageView)findViewById(R.id.imageView);
Animation animation1 =

233 | P a g e
AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.move);
image.startAnimation(animation1);
}

public void slide(View view){


ImageView image = (ImageView)findViewById(R.id.imageView);
Animation animation1 =
AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.slide);
image.startAnimation(animation1);
}
}

Here is the modified code of res/layout/activity_main.xml.

Here abc indicates about logo of tutorialspoint


<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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Alert Dialog"
android:id="@+id/textView"
android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorialspoint"
android:id="@+id/textView2"
android:textColor="#ff3eff0f"
android:textSize="35dp"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true" />

<ImageView

234 | P a g e
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView2"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2"
android:layout_alignLeft="@+id/textView"
android:layout_alignStart="@+id/textView"/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="zoom"
android:id="@+id/button"
android:layout_below="@+id/imageView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="40dp"
android:onClick="clockwise"/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="clockwise"
android:id="@+id/button2"
android:layout_alignTop="@+id/button"
android:layout_centerHorizontal="true"
android:onClick="zoom"/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="fade"
android:id="@+id/button3"
android:layout_alignTop="@+id/button2"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:onClick="fade"/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="blink"
android:onClick="blink"
android:id="@+id/button4"
android:layout_below="@+id/button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />

235 | P a g e
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="move"
android:onClick="move"
android:id="@+id/button5"
android:layout_below="@+id/button2"
android:layout_alignRight="@+id/button2"
android:layout_alignEnd="@+id/button2"
android:layout_alignLeft="@+id/button2"
android:layout_alignStart="@+id/button2" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="slide"
android:onClick="slide"
android:id="@+id/button6"
android:layout_below="@+id/button3"
android:layout_toRightOf="@+id/textView"
android:layout_toEndOf="@+id/textView" />

</RelativeLayout>

Here is the code of res/anim/myanimation.xml.

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


<set xmlns:android="http://schemas.android.com/apk/res/android">

<scale
xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXScale="0.5"
android:toXScale="3.0"
android:fromYScale="0.5"
android:toYScale="3.0"
android:duration="5000"
android:pivotX="50%"
android:pivotY="50%" >
</scale>

<scale
xmlns:android="http://schemas.android.com/apk/res/android"
android:startOffset="5000"
android:fromXScale="3.0"
android:toXScale="0.5"
android:fromYScale="3.0"
android:toYScale="0.5"

236 | P a g e
android:duration="5000"
android:pivotX="50%"
android:pivotY="50%" >
</scale>

</set>

Here is the code of res/anim/clockwise.xml.

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


<set xmlns:android="http://schemas.android.com/apk/res/android">

<rotate
xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="0"
android:toDegrees="360"
android:pivotX="50%"
android:pivotY="50%"
android:duration="5000" >
</rotate>

<rotate
xmlns:android="http://schemas.android.com/apk/res/android"
android:startOffset="5000"
android:fromDegrees="360"
android:toDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:duration="5000" >
</rotate>

</set>

Here is the code of res/anim/fade.xml.

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


<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/accelerate_interpolator" >

<alpha
android:fromAlpha="0"
android:toAlpha="1"
android:duration="2000" >
</alpha>

<alpha
android:startOffset="2000"
android:fromAlpha="1"

237 | P a g e
android:toAlpha="0"
android:duration="2000" >
</alpha>

</set>

Here is the code of res/anim/blink.xml.

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


<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha android:fromAlpha="0.0"
android:toAlpha="1.0"
android:interpolator="@android:anim/accelerate_interpolator"
android:duration="600"
android:repeatMode="reverse"
android:repeatCount="infinite"/>
</set>

Here is the code of res/anim/move.xml.

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


<set
xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/linear_interpolator"
android:fillAfter="true">

<translate
android:fromXDelta="0%p"
android:toXDelta="75%p"
android:duration="800" />
</set>

Here is the code of res/anim/slide.xml

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


<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true" >

<scale
android:duration="500"
android:fromXScale="1.0"
android:fromYScale="1.0"
android:interpolator="@android:anim/linear_interpolator"
android:toXScale="1.0"
android:toYScale="0.0" />
</set>

238 | P a g e
Here is the modified code of res/values/string.xml.

<resources>
<string name="app_name">My Application</string>
</resources>

Here is the default code of AndroidManifest.xml.

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


<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name="com.example.animation.MainActivity"
android:label="@string/app_name" >

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

</activity>

</application>
</manifest>

Let's try to run your application. I assume you have connected your actual
Android Mobile device with your computer. To run the app from Android studio,
open one of your project's activity files and click Run icon from the toolbar.
Android studio will display following images

239 | P a g e
Select zoom button, it will display following screen −

240 | P a g e
Now select slide button, it will display following screen

241 | P a g e
Now select move button, it will display following screen

242 | P a g e
Now the clockwise button, it will display following screen

243 | P a g e
Now Fade button, it will display following screen

244 | P a g e
Note − If you run it in emulator , you may not experience smooth animation
effect. You have to run it in your android mobile in order to experience the
smooth animation.

245 | P a g e
Android - Audio Capture
Android has a built in microphone through which you can capture audio and
store it , or play it in your phone. There are many ways to do that but the most
common way is through MediaRecorder class.

Android provides MediaRecorder class to record audio or video. In order to use


MediaRecorder class ,you will first create an instance of MediaRecorder class. Its
syntax is given below.

MediaRecorder myAudioRecorder = new MediaRecorder();

Now you will set the source , output and encoding format and output file. Their
syntax is given below.

myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GP
P);
myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myAudioRecorder.setOutputFile(outputFile);

After specifying the audio source and format and its output file, we can then call
the two basic methods prepare and start to start recording the audio.

myAudioRecorder.prepare();
myAudioRecorder.start();

Apart from these methods , there are other methods listed in the MediaRecorder
class that allows you more control over audio and video recording.

Sr.N
Method & description
o

setAudioSource()
1
This method specifies the source of audio to be recorded

setVideoSource()
2
This method specifies the source of video to be recorded

setOutputFormat()
3
This method specifies the audio format in which audio to be stored

setAudioEncoder()
4
This method specifies the audio encoder to be used

246 | P a g e
setOutputFile()
5 This method configures the path to the file into which the recorded audio is to
be stored

stop()
6
This method stops the recording process.

release()
7
This method should be called when the recorder instance is needed.

Example
This example provides demonstration of MediaRecorder class to capture audio
and then MediaPlayer class to play that recorded audio.

To experiment with this example , you need to run this on an actual device.

Ste
Description
ps

You will use Android studio IDE to create an Android application and name it
1
as AudioCapture under a package com.example.sairamkrishna.myapplication.

2 Modify src/MainActivity.java file to add AudioCapture code

Modify layout XML file res/layout/activity_main.xml add any GUI component


3
if required.

4 Modify AndroidManifest.xml to add necessary permissions.

Run the application and choose a running android device and install the
5
application on it and verify the results.

Here is the content of src/MainActivity.java

package com.example.sairamkrishna.myapplication;

import android.media.MediaPlayer;
import android.media.MediaRecorder;

import android.os.Environment;
import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;

247 | P a g e
import android.widget.Button;
import android.widget.Toast;

import java.io.IOException;
import java.util.Random;

import static android.Manifest.permission.RECORD_AUDIO;


import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;

import android.support.v4.app.ActivityCompat;
import android.content.pm.PackageManager;
import android.support.v4.content.ContextCompat;

public class MainActivity extends AppCompatActivity {

Button buttonStart, buttonStop, buttonPlayLastRecordAudio,


buttonStopPlayingRecording ;
String AudioSavePathInDevice = null;
MediaRecorder mediaRecorder ;
Random random ;
String RandomAudioFileName = "ABCDEFGHIJKLMNOP";
public static final int RequestPermissionCode = 1;
MediaPlayer mediaPlayer ;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

buttonStart = (Button) findViewById(R.id.button);


buttonStop = (Button) findViewById(R.id.button2);
buttonPlayLastRecordAudio = (Button)
findViewById(R.id.button3);
buttonStopPlayingRecording =
(Button)findViewById(R.id.button4);

buttonStop.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(false);
buttonStopPlayingRecording.setEnabled(false);

random = new Random();

buttonStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

if(checkPermission()) {

248 | P a g e
AudioSavePathInDevice =

Environment.getExternalStorageDirectory().getAbsolutePath() + "/" +
CreateRandomAudioFileName(5) +
"AudioRecording.3gp";

MediaRecorderReady();

try {
mediaRecorder.prepare();
mediaRecorder.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

buttonStart.setEnabled(false);
buttonStop.setEnabled(true);

Toast.makeText(MainActivity.this, "Recording
started",
Toast.LENGTH_LONG).show();
} else {
requestPermission();
}

}
});

buttonStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mediaRecorder.stop();
buttonStop.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(true);
buttonStart.setEnabled(true);
buttonStopPlayingRecording.setEnabled(false);

Toast.makeText(MainActivity.this, "Recording
Completed",
Toast.LENGTH_LONG).show();
}
});

buttonPlayLastRecordAudio.setOnClickListener(new
View.OnClickListener() {

249 | P a g e
@Override
public void onClick(View view) throws
IllegalArgumentException,
SecurityException, IllegalStateException {

buttonStop.setEnabled(false);
buttonStart.setEnabled(false);
buttonStopPlayingRecording.setEnabled(true);

mediaPlayer = new MediaPlayer();


try {
mediaPlayer.setDataSource(AudioSavePathInDevice);
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}

mediaPlayer.start();
Toast.makeText(MainActivity.this, "Recording Playing",
Toast.LENGTH_LONG).show();
}
});

buttonStopPlayingRecording.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View view) {
buttonStop.setEnabled(false);
buttonStart.setEnabled(true);
buttonStopPlayingRecording.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(true);

if(mediaPlayer != null){
mediaPlayer.stop();
mediaPlayer.release();
MediaRecorderReady();
}
}
});

public void MediaRecorderReady(){


mediaRecorder=new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);

mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP)
;

250 | P a g e
mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mediaRecorder.setOutputFile(AudioSavePathInDevice);
}

public String CreateRandomAudioFileName(int string){


StringBuilder stringBuilder = new StringBuilder( string );
int i = 0 ;
while(i < string ) {
stringBuilder.append(RandomAudioFileName.
charAt(random.nextInt(RandomAudioFileName.length())));

i++ ;
}
return stringBuilder.toString();
}

private void requestPermission() {


ActivityCompat.requestPermissions(MainActivity.this, new
String[]{WRITE_EXTERNAL_STORAGE, RECORD_AUDIO},
RequestPermissionCode);
}

@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case RequestPermissionCode:
if (grantResults.length> 0) {
boolean StoragePermission = grantResults[0] ==
PackageManager.PERMISSION_GRANTED;
boolean RecordPermission = grantResults[1] ==
PackageManager.PERMISSION_GRANTED;

if (StoragePermission && RecordPermission) {


Toast.makeText(MainActivity.this, "Permission
Granted",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this,"Permission
Denied",Toast.LENGTH_LONG).show();
}
}
break;
}
}

public boolean checkPermission() {

251 | P a g e
int result =
ContextCompat.checkSelfPermission(getApplicationContext(),
WRITE_EXTERNAL_STORAGE);
int result1 =
ContextCompat.checkSelfPermission(getApplicationContext(),
RECORD_AUDIO);
return result == PackageManager.PERMISSION_GRANTED &&
result1 == PackageManager.PERMISSION_GRANTED;
}
}

Here is the content of activity_main.xml

In the below code abc indicates the logo of tutorialspoint


<?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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin">

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:src="@drawable/abc"/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Record"
android:id="@+id/button"
android:layout_below="@+id/imageView"
android:layout_alignParentLeft="true"
android:layout_marginTop="37dp"
/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="STOP"
android:id="@+id/button2"

252 | P a g e
android:layout_alignTop="@+id/button"
android:layout_centerHorizontal="true"
/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Play"
android:id="@+id/button3"
android:layout_alignTop="@+id/button2"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="STOP PLAYING RECORDING "
android:id="@+id/button4"
android:layout_below="@+id/button2"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
/>
</RelativeLayout>

Here is the content of Strings.xml

<resources>
<string name="app_name">My Application</string>
</resources>

Here is the content of AndroidManifest.xml

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


<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >

<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"
/>
<uses-permission android:name="android.permission.STORAGE" />

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"

253 | P a g e
android:theme="@style/AppTheme" >

<activity

android:name="com.example.sairamkrishna.myapplication.MainActivity"
android:label="@string/app_name" >

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

</activity>

</application>
</manifest>

Let's try to run your application. I assume you have connected your actual
Android Mobile device with your computer. To run the app from Android studio,
open one of your project's activity files and click Run icon from the toolbar.
Before starting your application, Android studio will display following images.

Now by default you will see stop and play button disable. Just press the Record
button and your application will start recording the audio. It will display the
following screen.

254 | P a g e
Now just press stop button and it will save the recorded audio to external sd
card. When you click on stop button , the following screen would appear.

255 | P a g e
Now just press the play button and and recorded audio will just start playing on
the device. The following message appears when you click on play button.

256 | P a g e
Android - Audio Manager
You can easily control your ringer volume and ringer profile i-e:
(silent,vibrate,loud e.t.c) in android. Android provides AudioManager class that
provides access to these controls.

In order to use AndroidManager class, you have to first create an object of


AudioManager class by calling the getSystemService() method. Its syntax is
given below.

257 | P a g e
private AudioManager myAudioManager;
myAudioManager =
(AudioManager)getSystemService(Context.AUDIO_SERVICE);

Once you instantiate the object of AudioManager class, you can


use setRingerMode method to set the audio or ringer profile of your device. Its
syntax is given below.

myAudioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);

The method setRingerMode takes an integer number as a parameter. For each


mode , an integer number is assigned that will differentiate between different
modes. The possible modes are.

Sr.No Mode & Description

RINGER_MODE_VIBRATE
1
This Mode sets the device at vibrate mode.

RINGER_MODE_NORMAL
2
This Mode sets the device at normal(loud) mode.

RINGER_MODE_SILENT
3
This Mode sets the device at silent mode.

Once you have set the mode , you can call the getRingerMode() method to
get the set state of the system. Its syntax is given below.

int mod = myAudioManager.getRingerMode();

Apart from the getRingerMode method, there are other methods available in the
AudioManager class to control the volume and other modes. They are listed
below.

Sr.N
Method & description
o

adjustVolume(int direction, int flags)


1
This method adjusts the volume of the most relevant stream

getMode()
2
This method returns the current audio mode

getStreamMaxVolume(int streamType)
3
This method returns the maximum volume index for a particular stream

258 | P a g e
getStreamVolume(int streamType)
4
This method returns the current volume index for a particular stream

isMusicActive()
5
This method checks whether any music is active.

startBluetoothSco()
6
This method Start bluetooth SCO audio connection

stopBluetoothSco()
7
This method stop bluetooth SCO audio connection.

Example
The below example demonstrates the use of AudioManager class. It creates a
application that allows you to set different ringer modes for your device.

To experiment with this example , you need to run this on an actual device.

Ste
Description
ps

You will use Android studio IDE to create an Android application under a
1
package com.example.sairamkrishna.myapplication.

2 Modify src/MainActivity.java file to add AudioManager code

Modify layout XML file res/layout/activity_main.xml add any GUI component


3
if required.

4 Modify res/values/string.xml file and add necessary string components.

5 Modify AndroidManifest.xml to add necessary permissions.

Run the application and choose a running android device and install the
6
application on it and verify the results.

Here is the content of src/MainActivity.java

package com.example.sairamkrishna.myapplication;

import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.os.Bundle;

259 | P a g e
import android.view.View;

import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {


Button mode,ring,vibrate,silent;
private AudioManager myAudioManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

vibrate=(Button)findViewById(R.id.button3);
ring=(Button)findViewById(R.id.button2);

mode=(Button)findViewById(R.id.button);
silent=(Button)findViewById(R.id.button4);
myAudioManager =
(AudioManager)getSystemService(Context.AUDIO_SERVICE);

vibrate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

myAudioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
Toast.makeText(MainActivity.this,"Now in Vibrate Mode",
Toast.LENGTH_LONG).show();
}
});

ring.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

myAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
Toast.makeText(MainActivity.this,"Now in Ringing Mode",
Toast.LENGTH_LONG).show();
}
});

silent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

myAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
Toast.makeText(MainActivity.this,"Now in silent Mode",

260 | P a g e
Toast.LENGTH_LONG).show();
}
});

mode.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int mod=myAudioManager.getRingerMode();
if(mod==AudioManager.RINGER_MODE_VIBRATE){
Toast.makeText(MainActivity.this,"Now in Vibrate
Mode",
Toast.LENGTH_LONG).show();
} else if(mod==AudioManager.RINGER_MODE_NORMAL){
Toast.makeText(MainActivity.this,"Now in Ringing
Mode",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this,"Now in Vibrate
Mode",
Toast.LENGTH_LONG).show();
}
}
});
}
}

Here is the content of activity_main.xml

Here abc indicates the logo of tutorialspoint


<?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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Android Audio Recording"
android:id="@+id/textView"
android:textSize="30dp"
android:layout_alignParentTop="true"

261 | P a g e
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorialspoint"
android:id="@+id/textView2"
android:textColor="#ff3eff0f"
android:textSize="35dp"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true" />

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView2"
android:layout_alignLeft="@+id/textView2"
android:layout_alignStart="@+id/textView2"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Mode"
android:id="@+id/button"
android:layout_below="@+id/imageView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="59dp" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ring"
android:id="@+id/button2"
android:layout_alignTop="@+id/button"
android:layout_centerHorizontal="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="vibrate"
android:id="@+id/button3"
android:layout_alignTop="@+id/button2"
android:layout_alignRight="@+id/textView"

262 | P a g e
android:layout_alignEnd="@+id/textView" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Silent"
android:id="@+id/button4"
android:layout_below="@+id/button2"
android:layout_alignLeft="@+id/button2"
android:layout_alignStart="@+id/button2" />
</RelativeLayout>

Here is the content of Strings.xml

<resources>
<string name="app_name">My Application</string>
</resources>

Here is the content of AndroidManifest.xml

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


<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name="com.example.sairamkrishna.myapplication"
android:label="@string/app_name" >

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

</activity>

</application>
</manifest>

263 | P a g e
Let's try to run your application. I assume you have connected your actual
Android Mobile device with your computer. To run the app from Android Studio,
open one of your project's activity files and click Run icon from the tool bar.
Android studio will display Images

Now select silent button, you would get silent icon at Notification bar

264 | P a g e
Now just select the ring button and then press the current mode button to see
that if its status has been set.

Now press the Vibrate button and then press the current mode button to see
that if it is set or not.It will display the following screen.

265 | P a g e
266 | P a g e
Android - Auto Complete
I f you want to get suggestions , when you type in an editable text field , you
can do this via AutoCompleteTextView. It provides suggestions automatically
when the user is typing. The list of suggestions is displayed in a drop down
menu from which the user can choose an item to replace the content of the edit
box with.

In order to use AutoCompleteTextView you have to first create an


AutoCompletTextView Field in the xml. Its syntax is given below.

<AutoCompleteTextView
android:id="@+id/autoCompleteTextView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="65dp"
android:ems="10" >

After that, you have to get a reference of this textview in java. Its syntax is
given below.

private AutoCompleteTextView actv;


actv = (AutoCompleteTextView)
findViewById(R.id.autoCompleteTextView1);

The the next thing you need to do is to specify the list of suggestions items to
be displayed. You can specify the list items as a string array in java or in
strings.xml. Its syntax is given below.

String[] countries =
getResources().getStringArray(R.array.list_of_countries);
ArrayAdapter<String> adapter = new ArrayAdapter<String>
(this,android.R.layout.simple_list_item_1,countries);
actv.setAdapter(adapter);

The array adapter class is responsible for displaying the data as list in the
suggestion box of the text field. The setAdapter method is used to set the
adapter of the autoCompleteTextView. Apart from these methods, the other
methods of Auto Complete are listed below.

Sr.N
Method & description
o

267 | P a g e
getAdapter()
1
This method returns a filterable list adapter used for auto completion

getCompletionHint()
2 This method returns optional hint text displayed at the bottom of the the
matching list

getDropDownAnchor()
3 This method returns returns the id for the view that the auto-complete drop
down list is anchored to.

getListSelection()
4
This method returns the position of the dropdown view selection, if there is one

isPopupShowing()
5
This method indicates whether the popup menu is showing

setText(CharSequence text, boolean filter)


6
This method sets text except that it can disable filtering

showDropDown()
7
This method displays the drop down on screen.

Example
The below example demonstrates the use of AutoCompleteTextView class. It
crates a basic application that allows you to type in and it displays suggestions
on your device.

To experiment with this example , you need to run this on an actual device or in
an emulator.

Ste
Description
ps

You will use Android Studio to create an Android application under a package
1
package com.example.sairamkrishna.myapplication.

2 Modify src/MainActivity.java file to add AutoCompleteTextView code

Modify layout XML file res/layout/activity_main.xml add any GUI component


3
if required.

Run the application and choose a running android device and install the
4
application on it and verify the results.

268 | P a g e
Here is the content of src/MainActivity.java

package com.example.sairamkrishna.myapplication;

import android.app.Activity;
import android.content.Context;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;

import android.os.Bundle;
import android.os.Environment;

import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;

import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.MultiAutoCompleteTextView;
import android.widget.Toast;
import java.io.IOException;

public class MainActivity extends Activity {


AutoCompleteTextView text;
MultiAutoCompleteTextView text1;
String[] languages={"Android ","java","IOS","SQL","JDBC","Web
services"};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

text=(AutoCompleteTextView)findViewById(R.id.autoCompleteTextView1)
;

text1=(MultiAutoCompleteTextView)findViewById(R.id.multiAutoComplet
eTextView1);

ArrayAdapter adapter = new

269 | P a g e
ArrayAdapter(this,android.R.layout.simple_list_item_1,languages);

text.setAdapter(adapter);
text.setThreshold(1);

text1.setAdapter(adapter);
text1.setTokenizer(new
MultiAutoCompleteTextView.CommaTokenizer());
}
}

Here is the content of activity_main.xml

Here abc indicates about logo of tutorialspoint


<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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Android Auto Complete"
android:id="@+id/textView"
android:textSize="30dp"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorialspoint"
android:id="@+id/textView2"
android:textColor="#ff3eff0f"
android:textSize="35dp"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true" />

<ImageView

270 | P a g e
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/logo"
android:layout_below="@+id/textView2"
android:layout_alignLeft="@+id/textView2"
android:layout_alignStart="@+id/textView2"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2" />

<AutoCompleteTextView
android:id="@+id/autoCompleteTextView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:layout_below="@+id/imageView"
android:layout_alignLeft="@+id/imageView"
android:layout_alignStart="@+id/imageView"
android:layout_marginTop="72dp"
android:hint="AutoComplete TextView">
<requestFocus />
</AutoCompleteTextView>

<MultiAutoCompleteTextView
android:id="@+id/multiAutoCompleteTextView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:layout_below="@+id/autoCompleteTextView1"
android:layout_alignLeft="@+id/autoCompleteTextView1"
android:layout_alignStart="@+id/autoCompleteTextView1"
android:hint="Multi Auto Complete " />

</RelativeLayout>

Here is the content of Strings.xml

<resources>
<string name="app_name">My Application</string>
</resources>

Here is the content of AndroidManifest.xml

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


<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >

271 | P a g e
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity

android:name="com.example.sairamkrishna.myapplication.MainActivity"
android:label="@string/app_name" >

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

</activity>

</application>
</manifest>

Let's try to run your application. I assume you have connected your AVD while
doing environment setup. To run the app from Android Studio, open one of your
project's activity files and click Run icon from the toolbar. Android studio will
install this application in your AVD and your AVD will display following screen.

272 | P a g e
Now just type in the text view to see suggestions of the Languages. As i just
type one letter which are asa, and it shows me suggestion of language.

273 | P a g e
The multiAutoCompleteTextView demonstrates suggestions for not only a word
but for whole text. As after writing first word , when i start writing the second
word , it displays me the suggestions. This can be shown in the picture below.

274 | P a g e
275 | P a g e
Android - Best Practices
There are some practices that you can follow while developing android
application. These are suggested by the android itself and they keep on
improving with respect to time.

These best practices include interaction design features, performance, security


and privacy, compatibility, testing, distributing and monetizing tips. They are
narrowed down and are listed as below.

Best Practices - User input


Every text field is intended for a different job. For example, some text fields are
for text and some are for numbers. If it is for numbers then it is better to display
the numeric keypad when that textfield is focused. Its syntax is.

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:hint="User Name"
android:layout_below="@+id/imageView"
android:layout_alignLeft="@+id/imageView"
android:layout_alignStart="@+id/imageView"
android:numeric="integer" />

Other then that if your field is for password, then it must show a password hint,
so that the user can easily remember the password. It can be achieved as.

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText2"
android:layout_alignLeft="@+id/editText"
android:layout_alignStart="@+id/editText"
android:hint="Pass Word"
android:layout_below="@+id/editText"
android:layout_alignRight="@+id/editText"
android:layout_alignEnd="@+id/editText"
android:password="true" />

Best Practices - Background jobs

276 | P a g e
There are certain jobs in an application that are running in an application
background. Their job might be to fetch some thing from the internet , playing
music e.t.c. It is recommended that the long awaiting tasks should not be done
in the UI thread and rather in the background by services or AsyncTask.

AsyncTask Vs Services.
Both are used for doing background tasks , but the service is not affected by
most user interface life cycle events, so it continues to run in circumstances that
would shut down an AsyncTask.

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

Best Practices - Performance


Your application performance should be up-to the mark. But it should perform
differently not on the front end , but on the back end when it the device is
connected to a power source or charging. Charging could be of from USB and
from wire cable.

When your device is charging itself , it is recommended to update your


application settings if any, such as maximizing your refresh rate whenever the
device is connected. It can be done as this.

IntentFilter ifilter = new


IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, ifilter);

// Are we charging / charged? Full or charging.


int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS,
-1);

// How are we charging? From AC or USB.


int chargePlug =
batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);

Best Practices - Security and privacy


It is very important that your application should be secure and not only the
application , but the user data and the application data should also be secured.
The security can be increased by the following factors.

277 | P a g e
 Use internal storage rather then external for storing applications files
 Use content providers wherever possible
 Use SSl when connecting to the web
 Use appropriate permissions for accessing different functionalities of device

Example
The below example demonstrates some of the best practices you should follow
when developing android application. It crates a basic application that allows
you to specify how to use text fields and how to increase performance by
checking the charging status of the phone.

To experiment with this example , you need to run this on an actual device.

Ste
Description
ps

You will use Android studio IDE to create an Android application under a package
1
com.example.sairamkrishna.myapplication.

2 Modify src/MainActivity.java file to add the code

Modify layout XML file res/layout/activity_main.xml add any GUI component if


3
required.

Run the application and choose a running android device and install the application
4
on it and verify the results.

Here is the content of src/MainActivity.java


package com.example.sairamkrishna.myapplication;

import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {


EditText ed1,ed2;
Button b1;

278 | P a g e
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

ed1=(EditText)findViewById(R.id.editText);
ed2=(EditText)findViewById(R.id.editText2);
b1=(Button)findViewById(R.id.button);

b1.setOnClickListener(new View.OnClickListener() {
@Override

public void onClick(View v) {


IntentFilter ifilter = new
IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = registerReceiver(null, ifilter);

int status =
batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status ==
BatteryManager.BATTERY_STATUS_CHARGING ||
status == BatteryManager.BATTERY_STATUS_FULL;

int chargePlug =
batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED,-1);
boolean usbCharge = chargePlug ==
BatteryManager.BATTERY_PLUGGED_USB;
boolean acCharge = chargePlug ==
BatteryManager.BATTERY_PLUGGED_AC;

if(usbCharge){
Toast.makeText(getApplicationContext(),"Mobile is
charging on USB",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),"Mobile is
charging on AC",
Toast.LENGTH_LONG).show();
}
}
});
}

@Override
protected void onDestroy() {
super.onDestroy();
}
}

279 | P a g e
Here is the content of 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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView android:text="Bluetooth Example"


android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textview"
android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:id="@+id/textView"
android:layout_below="@+id/textview"
android:layout_centerHorizontal="true"
android:textColor="#ff7aff24"
android:textSize="35dp" />

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:hint="User Name"
android:layout_below="@+id/imageView"
android:layout_alignLeft="@+id/imageView"
android:layout_alignStart="@+id/imageView"

280 | P a g e
android:numeric="integer" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText2"
android:layout_alignLeft="@+id/editText"
android:layout_alignStart="@+id/editText"
android:hint="Pass Word"
android:layout_below="@+id/editText"
android:layout_alignRight="@+id/editText"
android:layout_alignEnd="@+id/editText"
android:password="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Check"
android:id="@+id/button"
android:layout_below="@+id/editText2"
android:layout_centerHorizontal="true" />

</RelativeLayout>
Here is the content of Strings.xml
<resources>
<string name="app_name">My Application</string>
</resources>
Here is the content of AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity

android:name="com.example.sairamkrishna.myapplication.MainActivity"
android:label="@string/app_name" >

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

281 | P a g e
</activity>

</application>
</manifest>

Let's try to run your application. I assume you have connected your actual
Android Mobile device with your computer. To run the app from Android studio,
open one of your project's activity files and click Run icon from the tool bar.
Android Studio will display following Images.

282 | P a g e
Above image shows an output of application

283 | P a g e
Now just type on the username field and you will see the built in android
suggestions from the dictionary will start coming up. This is shown Above.

284 | P a g e
Now you will see the password field. It would disappear as soon as you start
writing in the field. It is shown above.

In the end , just connect your device to AC cable or USB cable and press on
charging check button. In my case , i connect AC power,it shows the following
message.

285 | P a g e
286 | P a g e
Android - Bluetooth
Among many ways, Bluetooth is a way to send or receive data between two
different devices. Android platform includes support for the Bluetooth framework
that allows a device to wirelessly exchange data with other Bluetooth devices.

Android provides Bluetooth API to perform these different operations.

 Scan for other Bluetooth devices


 Get a list of paired devices
 Connect to other devices through service discovery

Android provides BluetoothAdapter class to communicate with Bluetooth. Create


an object of this calling by calling the static method getDefaultAdapter(). Its
syntax is given below.

private BluetoothAdapter BA;


BA = BluetoothAdapter.getDefaultAdapter();

In order to enable the Bluetooth of your device, call the intent with the following
Bluetooth constant ACTION_REQUEST_ENABLE. Its syntax is.

Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);


startActivityForResult(turnOn, 0);

Apart from this constant, there are other constants provided the API , that
supports different tasks. They are listed below.

Sr.N
Constant & description
o

1 ACTION_REQUEST_DISCOVERABLE
This constant is used for turn on discovering of bluetooth

2 ACTION_STATE_CHANGED
This constant will notify that Bluetooth state has been changed

ACTION_FOUND
3 This constant is used for receiving information about each device that is
discovered

Once you enable the Bluetooth , you can get a list of paired devices by calling
getBondedDevices() method. It returns a set of bluetooth devices. Its syntax is.

287 | P a g e
private Set<BluetoothDevice>pairedDevices;
pairedDevices = BA.getBondedDevices();

Apart form the parried Devices , there are other methods in the API that gives
more control over Blueetooth. They are listed below.

Sr.N
Method & description
o

1 enable()
This method enables the adapter if not enabled

2 isEnabled()
This method returns true if adapter is enabled

3 disable()
This method disables the adapter

4 getName()
This method returns the name of the Bluetooth adapter

5 setName(String name)
This method changes the Bluetooth name

6 getState()
This method returns the current state of the Bluetooth Adapter.

7 startDiscovery()
This method starts the discovery process of the Bluetooth for 120 seconds.

Example
This example provides demonstration of BluetoothAdapter class to manipulate
Bluetooth and show list of paired devices by the Bluetooth.

To experiment with this example , you need to run this on an actual device.

Ste
Description
ps

You will use Android studio to create an Android application a package


1
com.example.sairamkrishna.myapplication.

288 | P a g e
2 Modify src/MainActivity.java file to add the code

Modify layout XML file res/layout/activity_main.xml add any GUI component if


3
required.

4 Modify AndroidManifest.xml to add necessary permissions.

Run the application and choose a running android device and install the application
5
on it and verify the results.

Here is the content of src/MainActivity.java


package com.example.sairamkrishna.myapplication;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

import android.widget.Toast;
import java.util.ArrayList;
import java.util.Set;

public class MainActivity extends Activity {


Button b1,b2,b3,b4;
private BluetoothAdapter BA;
private Set<BluetoothDevice>pairedDevices;
ListView lv;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

b1 = (Button) findViewById(R.id.button);
b2=(Button)findViewById(R.id.button2);
b3=(Button)findViewById(R.id.button3);
b4=(Button)findViewById(R.id.button4);

BA = BluetoothAdapter.getDefaultAdapter();

289 | P a g e
lv = (ListView)findViewById(R.id.listView);
}

public void on(View v){


if (!BA.isEnabled()) {
Intent turnOn = new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);
Toast.makeText(getApplicationContext(), "Turned
on",Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Already on",
Toast.LENGTH_LONG).show();
}
}

public void off(View v){


BA.disable();
Toast.makeText(getApplicationContext(), "Turned off"
,Toast.LENGTH_LONG).show();
}

public void visible(View v){


Intent getVisible = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(getVisible, 0);
}

public void list(View v){


pairedDevices = BA.getBondedDevices();

ArrayList list = new ArrayList();

for(BluetoothDevice bt : pairedDevices)
list.add(bt.getName());
Toast.makeText(getApplicationContext(), "Showing Paired
Devices",Toast.LENGTH_SHORT).show();

final ArrayAdapter adapter = new


ArrayAdapter(this,android.R.layout.simple_list_item_1, list);

lv.setAdapter(adapter);
}
}
Here is the content of activity_main.xml
Here abc indicates about logo of tutorialspoint.

290 | P a g e
<?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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:transitionGroup="true">

<TextView android:text="Bluetooth Example"


android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textview"
android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:id="@+id/textView"
android:layout_below="@+id/textview"
android:layout_centerHorizontal="true"
android:textColor="#ff7aff24"
android:textSize="35dp" />

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:theme="@style/Base.TextAppearance.AppCompat" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Turn On"
android:id="@+id/button"
android:layout_below="@+id/imageView"
android:layout_toStartOf="@+id/imageView"
android:layout_toLeftOf="@+id/imageView"
android:clickable="true"

291 | P a g e
android:onClick="on" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get visible"
android:onClick="visible"
android:id="@+id/button2"
android:layout_alignBottom="@+id/button"
android:layout_centerHorizontal="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="List devices"
android:onClick="list"
android:id="@+id/button3"
android:layout_below="@+id/imageView"
android:layout_toRightOf="@+id/imageView"
android:layout_toEndOf="@+id/imageView" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="turn off"
android:onClick="off"
android:id="@+id/button4"
android:layout_below="@+id/button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />

<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/listView"
android:layout_alignParentBottom="true"
android:layout_alignLeft="@+id/button"
android:layout_alignStart="@+id/button"
android:layout_below="@+id/textView2" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Paired devices:"
android:id="@+id/textView2"
android:textColor="#ff34ff06"
android:textSize="25dp"
android:layout_below="@+id/button4"
android:layout_alignLeft="@+id/listView"

292 | P a g e
android:layout_alignStart="@+id/listView" />

</RelativeLayout>
Here is the content of Strings.xml
<resources>
<string name="app_name">My Application</string>
</resources>
Here is the content of AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission
android:name="android.permission.BLUETOOTH_ADMIN"/>

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name=".MainActivity"
android:label="@string/app_name" >

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

</activity>

</application>
</manifest>

Let's try to run your application. I assume you have connected your actual
Android Mobile device with your computer. To run the app from Android studio,
open one of your project's activity files and click Run icon from the tool bar.If
your Bluetooth will not be turned on then, it will ask your permission to enable
the Bluetooth.

293 | P a g e
Now just select the Get Visible button to turn on your visibility. The following
screen would appear asking your permission to turn on discovery for 120
seconds.

294 | P a g e
Now just select the List Devices option. It will list down the paired devices in the
list view. In my case , I have only one paired device. It is shown below.

295 | P a g e
Now just select the Turn off button to switch off the Bluetooth. Following
message would appear when you switch off the bluetooth indicating the
successful switching off of Bluetooth.

296 | P a g e
Android - Camera
These are the following two ways, in which you can use camera in your
application

 Using existing android camera application in our application


 Directly using Camera API provided by android in our application

297 | P a g e
Using existing android camera application in our
application
You will use MediaStore.ACTION_IMAGE_CAPTURE to launch an existing camera
application installed on your phone. Its syntax is given below

Intent intent = new


Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

Apart from the above, there are other available Intents provided by MediaStore.
They are listed as follows

Sr.N
Intent type and description
o

1 ACTION_IMAGE_CAPTURE_SECURE
It returns the image captured from the camera , when the device is secured

2 ACTION_VIDEO_CAPTURE
It calls the existing video application in android to capture video

3 EXTRA_SCREEN_ORIENTATION
It is used to set the orientation of the screen to vertical or landscape

4 EXTRA_FULL_SCREEN
It is used to control the user interface of the ViewImage

5 INTENT_ACTION_VIDEO_CAMERA
This intent is used to launch the camera in the video mode

6 EXTRA_SIZE_LIMIT
It is used to specify the size limit of video or image capture size
Now you will use the function startActivityForResult() to launch this activity and
wait for its result. Its syntax is given below
startActivityForResult(intent,0)
This method has been defined in the activity class. We are calling it from main
activity. There are methods defined in the activity class that does the same job ,
but used when you are not calling from the activity but from somewhere else.
They are listed below
Sr.N
Activity function description
o

1 startActivityForResult(Intent intent, int requestCode,

298 | P a g e
Bundle options)
It starts an activity , but can take extra bundle of options with it

startActivityFromChild(Activity child, Intent intent, int


2 requestCode)
It launch the activity when your activity is child of any other activity

startActivityFromChild(Activity child, Intent intent, int


3 requestCode, Bundle options)
It work same as above , but it can take extra values in the shape of bundle with
it

startActivityFromFragment(Fragment fragment, Intent


4 intent, int requestCode)
It launches activity from the fragment you are currently inside

startActivityFromFragment(Fragment fragment, Intent


5 intent, int requestCode, Bundle options)
It not only launches the activity from the fragment , but can take extra values
with it
No matter which function you used to launch the activity , they all return the
result. The result can be obtained by overriding the function onActivityResult.

Example
Here is an example that shows how to launch the existing camera application to
capture an image and display the result in the form of bitmap.

To experiment with this example , you need to run this on an actual device on
which camera is supported.

Ste
Description
ps

You will use Android studio IDE to create an Android application and name it as
1
Camera under a com.example.sairamkrishna.myapplication.

2 Modify src/MainActivity.java file to add intent code to launch the Camera.

3 Modify layout XML file res/layout/activity_main.xml

4 Add the Camera permission and run the application and choose a running android

299 | P a g e
device and install the application on it and verify the results.

Following is the content of the modified main activity


file src/MainActivity.java.
package com.example.sairamkrishna.myapplication;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;

import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;

import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

public class MainActivity extends AppCompatActivity {


public static final int MY_PERMISSIONS_REQUEST_CAMERA = 100;
public static final String ALLOW_KEY = "ALLOWED";
public static final String CAMERA_PREF = "camera_pref";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

if (ContextCompat.checkSelfPermission(this,
Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
if (getFromPref(this, ALLOW_KEY)) {
showSettingsAlert();
} else if (ContextCompat.checkSelfPermission(this,
Manifest.permission.CAMERA)

!= PackageManager.PERMISSION_GRANTED) {

// Should we show an explanation?


if
(ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.CAMERA)) {

300 | P a g e
showAlert();
} else {
// No explanation needed, we can request the
permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CAMERA},
MY_PERMISSIONS_REQUEST_CAMERA);
}
}
} else {
openCamera();
}

}
public static void saveToPreferences(Context context, String
key, Boolean allowed) {
SharedPreferences myPrefs =
context.getSharedPreferences(CAMERA_PREF,
Context.MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putBoolean(key, allowed);
prefsEditor.commit();
}

public static Boolean getFromPref(Context context, String key) {


SharedPreferences myPrefs =
context.getSharedPreferences(CAMERA_PREF,
Context.MODE_PRIVATE);
return (myPrefs.getBoolean(key, false));
}

private void showAlert() {


AlertDialog alertDialog = new
AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("App needs to access the Camera.");

alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "DONT
ALLOW",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
finish();
}
});

alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "ALLOW",
new DialogInterface.OnClickListener() {

301 | P a g e
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CAMERA},
MY_PERMISSIONS_REQUEST_CAMERA);
}
});
alertDialog.show();
}

private void showSettingsAlert() {


AlertDialog alertDialog = new
AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("App needs to access the Camera.");

alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "DONT
ALLOW",
new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which)


{
dialog.dismiss();
//finish();
}
});

alertDialog.setButton(AlertDialog.BUTTON_POSITIVE,
"SETTINGS",
new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which)


{
dialog.dismiss();
startInstalledAppDetailsActivity(MainActivity.this);
}
});

alertDialog.show();
}

@Override
public void onRequestPermissionsResult(int requestCode, String
permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_CAMERA: {
for (int i = 0, len = permissions.length; i < len; i++)
{
String permission = permissions[i];

302 | P a g e
if (grantResults[i] ==
PackageManager.PERMISSION_DENIED) {
boolean
showRationale =

ActivityCompat.shouldShowRequestPermissionRationale(
this, permission);

if (showRationale) {
showAlert();
} else if (!showRationale) {
// user denied flagging NEVER ASK AGAIN
// you can either enable some fall back,
// disable features of your app
// or open another dialog explaining
// again the permission and directing to
// the app setting
saveToPreferences(MainActivity.this,
ALLOW_KEY, true);
}
}
}
}

// other 'case' lines to check for other


// permissions this app might request
}
}

@Override
protected void onResume() {
super.onResume();
}

public static void startInstalledAppDetailsActivity(final


Activity context) {
if (context == null) {
return;
}

final Intent i = new Intent();


i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
i.addCategory(Intent.CATEGORY_DEFAULT);
i.setData(Uri.parse("package:" + context.getPackageName()));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
context.startActivity(i);
}

303 | P a g e
private void openCamera() {
Intent intent = new
Intent("android.media.action.IMAGE_CAPTURE");
startActivity(intent);
}
}
Following will be the content of res/layout/activity_main.xml file−
<?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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
</RelativeLayout>
Following will be the content of res/values/strings.xml to define one new
constants
<resources>
<string name="app_name">My Application</string>
</resources>
Following is the default content of AndroidManifest.xml −
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >
<uses-permission android:name="android.permission.CAMERA" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity

android:name="com.example.sairamkrishna.myapplication.MainActivity"
android:label="@string/app_name" >

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

304 | P a g e
</activity>

</application>
</manifest>

Let's try to run your application. I assume you have connected your actual
Android Mobile device with your computer. To run the app from android studio,
open one of your project's activity files and click Run icon from the tool bar.
Before starting your application, Android studio will display following window to
select an option where you want to run your Android application.

Select your mobile device as an option and then check your mobile device which
will open the camera and display following screen −

305 | P a g e
Android - Clipboard
Android provides the clipboard framework for copying and pasting different
types of data. The data could be text, images, binary stream data or other
complex data types.

Android provides the library of ClipboardManager and ClipData and


ClipData.item to use the copying and pasting framework.In order to use
clipboard framework, you need to put data into clip object, and then put that
object into system wide clipboard.

306 | P a g e
In order to use clipboard , you need to instantiate an object of ClipboardManager
by calling the getSystemService() method. Its syntax is given below −

ClipboardManager myClipboard;
myClipboard =
(ClipboardManager)getSystemService(CLIPBOARD_SERVICE);

Copying data
The next thing you need to do is to instantiate the ClipData object by calling the
respective type of data method of the ClipData class. In case of text data ,
the newPlainText method will be called. After that you have to set that data as
the clip of the Clipboard Manager object.Its syntax is given below −

ClipData myClip;
String text = "hello world";
myClip = ClipData.newPlainText("text", text);
myClipboard.setPrimaryClip(myClip);

The ClipData object can take these three form and following functions are used
to create those forms.

Sr.N
ClipData Form & Method
o

Text
newPlainText(label, text)
1
Returns a ClipData object whose single ClipData.Item object contains a text
string.

URI
2 newUri(resolver, label, URI)
Returns a ClipData object whose single ClipData.Item object contains a URI.

Intent
newIntent(label, intent)
3
Returns a ClipData object whose single ClipData.Item object contains an
Intent.

Pasting data
In order to paste the data, we will first get the clip by calling
the getPrimaryClip() method. And from that click we will get the item in

307 | P a g e
ClipData.Item object. And from the object we will get the data. Its syntax is
given below −

ClipData abc = myClipboard.getPrimaryClip();


ClipData.Item item = abc.getItemAt(0);
String text = item.getText().toString();

Apart from the these methods , there are other methods provided by the
ClipboardManager class for managing clipboard framework. These methods are
listed below −

Sr.N
Method & description
o

getPrimaryClip()
1
This method just returns the current primary clip on the clipboard

getPrimaryClipDescription()
2 This method returns a description of the current primary clip on the clipboard
but not a copy of its data.

hasPrimaryClip()
3
This method returns true if there is currently a primary clip on the clipboard

setPrimaryClip(ClipData clip)
4
This method sets the current primary clip on the clipboard

setText(CharSequence text)
5
This method can be directly used to copy text into the clipboard

getText()
6
This method can be directly used to get the copied text from the clipboard

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

Example
Here is an example demonstrating the use of ClipboardManager class. It creates
a basic copy paste application that allows you to copy the text and then paste it
via clipboard.

To experiment with this example , you can run this on an actual device or in an
emulator.

308 | P a g e
Ste
Description
ps

You will use Android studio IDE to create an Android application and under a
1
package com.example.sairamkrishna.myapplication.

2 Modify src/MainActivity.java file to add necessary code.

3 Modify the res/layout/activity_main to add respective XML components

Run the application and choose a running android device and install the
4
application on it and verify the results

Following is the content of the modified main activity


file src/MainActivity.java.

package com.example.sairamkrishna.myapplication;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.os.Bundle;

import android.support.v7.app.ActionBarActivity;
import android.view.View;

import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {


EditText ed1, ed2;
Button b1, b2;

private ClipboardManager myClipboard;


private ClipData myClip;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

ed1 = (EditText) findViewById(R.id.editText);


ed2 = (EditText) findViewById(R.id.editText2);

b1 = (Button) findViewById(R.id.button);
b2 = (Button) findViewById(R.id.button2);

309 | P a g e
myClipboard = (ClipboardManager)
getSystemService(CLIPBOARD_SERVICE);

b1.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
String text;
text = ed1.getText().toString();

myClip = ClipData.newPlainText("text", text);


myClipboard.setPrimaryClip(myClip);

Toast.makeText(getApplicationContext(), "Text Copied",


Toast.LENGTH_SHORT).show();
}
});

b2.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
ClipData abc = myClipboard.getPrimaryClip();
ClipData.Item item = abc.getItemAt(0);

String text = item.getText().toString();


ed2.setText(text);

Toast.makeText(getApplicationContext(), "Text Pasted",


Toast.LENGTH_SHORT).show();
}
});
}

Following is the modified content of the xml res/layout/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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"

310 | P a g e
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView android:text="Example"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textview"
android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:id="@+id/textView"
android:layout_below="@+id/textview"
android:layout_centerHorizontal="true"
android:textColor="#ff7aff24"
android:textSize="35dp" />

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:hint="Copy text"
android:layout_below="@+id/imageView"
android:layout_alignLeft="@+id/imageView"
android:layout_alignStart="@+id/imageView" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText2"
android:layout_alignLeft="@+id/editText"
android:layout_alignStart="@+id/editText"
android:hint="paste text"
android:layout_below="@+id/editText"
android:layout_alignRight="@+id/editText"

311 | P a g e
android:layout_alignEnd="@+id/editText" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Copy text"
android:id="@+id/button"
android:layout_below="@+id/editText2"
android:layout_alignLeft="@+id/editText2"
android:layout_alignStart="@+id/editText2" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Paste text"
android:id="@+id/button2"
android:layout_below="@+id/editText2"
android:layout_alignRight="@+id/editText2"
android:layout_alignEnd="@+id/editText2" />

</RelativeLayout>

Following is the content of the res/values/string.xml.

<resources>
<string name="app_name">My Application</string>
</resources>

Following is the content of AndroidManifest.xml file.

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


<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity

android:name="com.example.sairamkrishna.myapplication.MainActivity"
android:label="@string/app_name" >

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

312 | P a g e
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>

</activity>
</application>

</manifest>

Let's try to run our an application we just modified. I assume you had created
your AVD while doing environment setup. To run the app from Android studio,
open one of your project's activity files and click Run icon from the tool bar.
Android studio installer will display following images −

313 | P a g e
Now just enter any text in the Text to copy field and then select the copy text
button. The following notification will be displayed which is shown below −

314 | P a g e
Now just press the paste button, and you will see the text which is copied is now
pasted in the field of Copied Text. It is shown below −

315 | P a g e
316 | P a g e
Android - Custom Fonts
In android, you can define your own custom fonts for the strings in your
application. You just need to download the required font from the internet, and
then place it in assets/fonts folder.

After putting fonts in the assets folder under fonts folder, you can access it in
your java code through Typeface class. First , get the reference of the text view
in the code. Its syntax is given below −

TextView tx = (TextView)findViewById(R.id.textview1);

The next thing you need to do is to call static method of Typeface


class createFromAsset() to get your custom font from assets. Its syntax is
given below −

Typeface custom_font = Typeface.createFromAsset(getAssets(),


"fonts/font name.ttf");

The last thing you need to do is to set this custom font object to your TextView
Typeface property. You need to call setTypeface() method to do that. Its
syntax is given below −

tx.setTypeface(custom_font);

Apart from these Methods, there are other methods defined in the Typeface
class , that you can use to handle Fonts more effectively.

Sr.N
Method & description
o

create(String familyName, int style)


1
Create a Typeface object given a family name, and option style information

create(Typeface family, int style)


2 Create a Typeface object that best matches the specified existing Typeface and
the specified Style

createFromFile(String path)
3
Create a new Typeface from the specified font file

defaultFromStyle(int style)
4
Returns one of the default Typeface objects, based on the specified style

5 getStyle()

317 | P a g e
Returns the Typeface's intrinsic style attributes

Example
Here is an example demonstrating the use of Typeface to handle CustomFont. It
creates a basic application that displays a custom font that you specified in the
fonts file.

To experiment with this example, you can run this on an actual device or in an
emulator.

Ste
Description
ps

You will use Android studio IDE to create an Android application under a
1
package com.example.sairamkrishna.myapplication.

2 Download a font from internet and put it under assets/fonts folder.

3 Modify src/MainActivity.java file to add necessary code.

4 Modify the res/layout/activity_main to add respective XML components

Run the application and choose a running android device and install the
5
application on it and verify the results

Before entering to code part add fonts in assests folder from windows explorer.

Following is the content of the modified main activity file MainActivity.java.

package com.example.sairamkrishna.myapplication;

import android.graphics.Typeface;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.widget.TextView;

318 | P a g e
public class MainActivity extends ActionBarActivity {
TextView tv1,tv2;

protected void onCreate(Bundle savedInstanceState) {


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

tv1=(TextView)findViewById(R.id.textView3);
tv2=(TextView)findViewById(R.id.textView4);

Typeface face= Typeface.createFromAsset(getAssets(),


"font/font.ttf");
tv1.setTypeface(face);

Typeface face1= Typeface.createFromAsset(getAssets(),


"font/font1.ttf");
tv2.setTypeface(face1);
}
}

Following is the modified content of the xml 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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Typeface"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials Point"

319 | P a g e
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:textSize="35dp"
android:textColor="#ff16ff01" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials Point"
android:id="@+id/textView3"
android:layout_centerVertical="true"
android:textSize="45dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials Point"
android:id="@+id/textView4"
android:layout_below="@+id/textView3"
android:layout_alignLeft="@+id/textView3"
android:layout_alignStart="@+id/textView3"
android:layout_marginTop="73dp"
android:textSize="45dp" />

</RelativeLayout>

Following is the content of the res/values/string.xml.

<resources>
<string name="app_name">My Application</string>
</resources>

Following is the content of AndroidManifest.xml file.

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


<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"

320 | P a g e
android:theme="@style/AppTheme" >

<activity
android:name=".MainActivity"
android:label="@string/app_name" >

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

</activity>

</application>
</manifest>

Let's try to run our Custom Font application we just modified. I assume you had
created your AVD while doing environment setup. To run the app from Android
studio, open one of your project's activity files and click Run icon from the
toolbar.Android studio installs the app on your AVD and starts it and if
everything is fine with your setup and application, it will display following
Emulator window −

321 | P a g e
As you can see that the text that appeared on the AVD has not a default android
font, rather it has the custom font that you specified in the fonts folder.

Note − You need to take care of the size and the character supported by the
font , when using custom fonts.

Android - Data Backup


Android allows you to backup your application data to remote "cloud" storage, in
order to provide a restore point for the application data and settings. You can

322 | P a g e
only backup your application data. In order to access the other applications
data, you need to root your phone.

In order to make a data backup application, you need to register your


application with google backup service. This has been explained in the example.
After registering , you have to specify its key in the AndroidManifest.XML

<application
android:allowBackup="true"
android:backupAgent="MyBackupPlace">

<meta-data
android:name="com.google.android.backup.api_key"
android:value="AEdPqrEAAAAIErlxFByGgNz2ywBeQb6TsmLpp5Ksh1PW-
ZSexg" />
</application>
Android provides BackUpAgentHelper class to handle all the operations of
data backup. In order to use this class , you have to extend your class with it. Its
syntax is given below −
public class MyBackUpPlace extends BackupAgentHelper {
}
The persistent data that you want to backup is in either of the two forms. Either
it could be SharedPrefrences or it could be File. Android supports both types of
backup in the respective classes
of SharedPreferencesBackupHelper and FileBackupHelper.
In order to use SharedPerefernceBackupHelper, you need to instantiate its
object with the name of your sharedPerefernces File. Its syntax is given below −
static final String File_Name_Of_Prefrences = "myPrefrences";
SharedPreferencesBackupHelper helper = new
SharedPreferencesBackupHelper(this, File_Name_Of_Prefrences);

The last thing you need to do is to call addHelper method by specifying the
backup key string , and the helper object. Its syntax is given below −

addHelper(PREFS_BACKUP_KEY, helper);

The addHelper method will automatically add a helper to a given data subset to
the agent's configuration.

Apart from these methods, there are other methods defined in the
BackupAgentHelper class. They are defined below −

Sr.N
Method & description
o

323 | P a g e
onBackup(ParcelFileDescriptor oldState,
1 BackupDataOutput data, ParcelFileDescriptor newState)
Run the backup process on each of the configured handlers

onRestore(BackupDataInput data, int appVersionCode,


2 ParcelFileDescriptor newState)
Run the restore process on each of the configured handlers

The methods of the SharedPreferencesBackUpHelper class are listed below.

Sr.N
Method & description
o

performBackup(ParcelFileDescriptor oldState,
1 BackupDataOutput data, ParcelFileDescriptor newState)
Backs up the configured SharedPreferences groups

restoreEntity(BackupDataInputStream data)
2 Restores one entity from the restore data stream to its proper shared preferences
file store

Example
The following example demonstrates the use of BackupAgentHelper class to
create backup of your application data.

To experiment with this example, you need to run this on an actual device or in
an emulator.

Ste
Description
ps

You will use Android studio to create an Android application and name it as Backup
1
under a package com.example.backup.

2 Register your application with Google backup service.

3 Modify the AndroidManifest to add respective necessary key and other components

4 Create backup agent class with the name you specify at AndroidManifest.XML

324 | P a g e
5 Run the application and verify the results

Register you android application with google backup service. In order to do


that , visit this link. You must agree to the terms of service, and then enter the
application package name. It is shown below −

Then click on Register with android backup service. It would give you your key,
along with your AndroidManifest code to copy. Just copy the key. It is shown
below −

Once you copy the key , you need to write it in your AndroidManifest.XML file. Its
code is given below −

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


<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.backup" >

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:backupAgent="MyBackUpPlace"
android:theme="@style/AppTheme" >

<activity
android:name="com.example.backup.MainActivity"
android:label="@string/app_name" >

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

325 | P a g e
</activity>

<meta-data
android:name="com.google.android.backup.api_key"

android:value="AEdPqrEAAAAIErlxFByGgNz2ywBeQb6TsmLpp5Ksh1PW-ZSexg"
/>

</application>
</manifest>

Here is the code of BackUpAgentHelper class. The name of the class should be
the same as you specified in the backupAgent tag under application in
AndroidManifest.XML

package com.example.backup;

import android.app.backup.BackupAgentHelper;
import android.app.backup.SharedPreferencesBackupHelper;

public class MyBackUpPlace extends BackupAgentHelper {


static final String File_Name_Of_Prefrences = "myPrefrences";
static final String PREFS_BACKUP_KEY = "backup";

@Override
public void onCreate() {
SharedPreferencesBackupHelper helper = new
SharedPreferencesBackupHelper(this,
File_Name_Of_Prefrences);
addHelper(PREFS_BACKUP_KEY, helper);
}
}

Test your BackupAgent


Once you've implemented your backup agent, you can test the backup and
restore functionality with the following procedure, using bmgr.

Install your application on a suitable Android system


image.
If using the emulator, create and use an AVD with Android 2.2 (API Level 8).

If using a device, the device must be running Android 2.2 or greater and have
Google Play built in.

326 | P a g e
Ensure data backup is enabled
If using the emulator, you can enable backup with the following command from
your SDK tools/ path −

adb shell bmgr enable true

If using a device, open the system Settings, select Privacy, then enable Back up
my data and Automatic restore.

Performing backup
For testing purposes, you can also make a request with the following bmgr
command −

adb shell bmgr backup your.package.name

Initiate a backup operation by typing the following command.

adb shell bmgr run

This forces the Backup Manager to perform all backup requests that are in its
queue.

Uninstall and reinstall your application


Uninstall the application with the following command −

adb uninstall your.package.name

Then reinstall the application and verify the results.

Android - Developer Tools


The android developer tools let you create interactive and powerful application
for android platform. The tools can be generally categorized into two types.

 SDK tools
 Platform tools

327 | P a g e
SDK tools
SDK tools are generally platform independent and are required no matter which
android platform you are working on. When you install the Android SDK into your
system, these tools get automatically installed. The list of SDK tools has been
given below −

Sr.N
Tool & description
o

android
1
This tool lets you manage AVDs, projects, and the installed components of the
SDK

ddms
2
This tool lets you debug Android applications

Draw 9-Patch
3
This tool allows you to easily create a NinePatch graphic using a WYSIWYG
editor

emulator
4
This tools let you test your applications without using a physical device

mksdcard
5
Helps you create a disk image (external sdcard storage) that you can use with
the emulator

proguard
6
Shrinks, optimizes, and obfuscates your code by removing unused code

sqlite3
7
Lets you access the SQLite data files created and used by Android applications

traceview
8
Provides a graphical viewer for execution logs saved by your application

Adb
9
Android Debug Bridge (adb) is a versatile command line tool that lets you
communicate with an emulator instance or connected Android-powered device.

328 | P a g e
We will discuss three important tools here that are android,ddms and sqlite3.

Android
Android is a development tool that lets you perform these tasks:

 Manage Android Virtual Devices (AVD)


 Create and update Android projects
 Update your sdk with new platform add-ons and documentation
android [global options] action [action options]

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

DDMS
DDMS stands for Dalvik debug monitor server, that provide many services on
the device. The service could include message formation, call spoofing,
capturing screenshot, exploring internal threads and file systems e.t.c

Running DDMS
From Android studio click on Tools>Android>Android device Monitor.

How it works
In android, each application runs in its own process and each process run in the
virtual machine. Each VM exposes a unique port, that a debugger can attach to.

When DDMS starts, it connects to adb. When a device is connected, a VM


monitoring service is created between adb and DDMS, which notifies DDMS
when a VM on the device is started or terminated.

Making SMS
Making sms to emulator.we need to call telnet client and server as shown below

329 | P a g e
Now click on send button, and you will see an sms notification in the emulator
window. It is shown below −

330 | P a g e
Making Call
In the DDMS, select the Emulator Control tab. In the emulator control tab , click
on voice and then start typing the incoming number. It is shown in the picture
below −

331 | P a g e
Now click on the call button to make a call to your emulator. It is shown below −

332 | P a g e
Now click on hangup in the Android studio window to terminate the call.

The fake sms and call can be viewed from the notification by just dragging the
notification window to the center using mouse. It is shown below −

333 | P a g e
Capturing ScreenShot
You can also capture screenshot of your emulator. For this look for the camera
icon on the right side under Devices tab. Just point your mouse over it and
select it.

334 | P a g e
As soon as you select it , it will start the screen capturing process and will
capture whatever screen of the emulator currently active. It is shown below −

The eclipse orientation can be changed using Ctrl + F11 key. Now you can save
the image or rotate it and then select done to exit the screen capture dialog.

Sqlite3
Sqlite3 is a command line program which is used to manage the SQLite
databases created by Android applications. The tool also allow us to execute the
SQL statements on the fly.

There are two way through which you can use SQlite , either from remote shell
or you can use locally.

Use Sqlite3 from a remote shell.


Enter a remote shell by entering the following command −

adb [-d|-e|-s {<serialNumber>}] shell

From a remote shell, start the sqlite3 tool by entering the following command −

sqlite3

335 | P a g e
Once you invoke sqlite3, you can issue sqlite3 commands in the shell. To exit
and return to the adb remote shell, enter exit or press CTRL+D.

Using Sqlite3 directly


Copy a database file from your device to your host machine.

adb pull <database-file-on-device>

Start the sqlite3 tool from the /tools directory, specifying the database file −

sqlite3 <database-file-on-host>

Platform tools
The platform tools are customized to support the features of the latest android
platform.

The platform tools are typically updated every time you install a new SDK
platform. Each update of the platform tools is backward compatible with older
platforms.

Some of the platform tools are listd below −

 Android Debug bridge (ADB)


 Android Interface definition language (AIDL)
 aapt, dexdump , and dex e.t.c

Android - Emulator
The Android SDK includes a virtual mobile device emulator that runs on your
computer. The emulator lets you prototype, develop and test Android
applications without using a physical device.

In this chapter we are going to explore different functionalities in the emulator


that are present in the real android device.

Creating AVD
If you want to emulate a real device, first crate an AVD with the same device
configurations as real device, then launch this AVD from AVD manager.

336 | P a g e
Changing Orientation
Usually by default when you launch the emulator, its orientation is vertical, but
you can change it orientation by pressing Ctrl+F11 key from keyboard.

First launch the emulator. It is shown in the picture below −

337 | P a g e
Once it is launched, press Ctrl+F11 key to change its orientation. It is shown
below −

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

Emulator Commands.
Apart from just orientation commands, there are other very useful commands of
emulator that you should keep in mind while using emulator. They are listed
below −

Sr.No Command & description

1 Home
Shifts to main screen

2 F2
Toggles context sensitive menu

3 F3
Bring out call log

4 F4
End call

5 F5
Search

338 | P a g e
6 F6
Toggle trackball mode

7 F7
Power button

8 F8
Toggle data network

9 Ctrl+F5
Ring Volume up

10 Ctrl+F6
Ring Volume down

Emulator - Sending SMS


You can emulate sending SMS to your emulator. There are two ways to do that.
You can do that from DDMS which can be found in Android studio, or from
Telnet.(Network utility found in windows).

Sending SMS through Telnet.

Telnet is not enabled by default in windows. You have to enable it to use it.
Once enabled you can go to command prompt and start telnet by typing telnet.

339 | P a g e
In order to send SMS , note down the AVD number which can be found on the
title bar of the emulator. It could be like this 5554 e.t.c. Once noted , type this
command in command prompt.

telnet localhost 5554

Press enter when you type the command. It is shown below in the figure.

You will see that you are now connected to your emulator. Now type this
command to send message.

sms send 1234 "hello"

Once you type this command , hit enter. Now look at the AVD. You will receive a
notification displaying that you got a new text message. It is shown below −

340 | P a g e
Emulator - Making Call
You can easily make phone calls to your emulator using telent client. You need
to connect to your emulator from telnet. It is discussed in the sending sms topic
above.

341 | P a g e
After that you will type this command in the telent window to make a call. Its
syntax is given below −

gsm call 1234

Once you type this command , hit enter. Now look at the AVD. You will receive a
call from the number your put in the command. It is shown below −

Emulator - Transferring files

342 | P a g e
You can easily transfer files into the emulator and vice versa. In order to do that,
you need to select the DDMS utility in Android studio. After that select the file
explorer tab. It is shown below −

Browse through the explorer and make new folder , view existing contents e.t.c.

Android - Facebook Integration


Once you enter it, you will be prompt for password. Give android as the
password and then copy the key that is given to you. It is shown in the image
below −

Registering your application


Now create a new facebook application at developers.facebook.com/apps and fill
all the information. It is shown below −

343 | P a g e
Now move to the native android app section and fill in your project and class
name and paste the hash that you copied in step 1. It is shown below −

If everything works fine, you will receive an application ID with the secret. Just
copy the application id and save it somewhere. It is shown in the image below −

Downloading SDK and integrating it


Download facebook sdk here. Import this into eclipse. Once imported, right click
on your facebook project and click on properties.Click on android, click on add
button and select facebook sdk as the project.Click ok.

Creating facebook login application


Once everything is complete , you can run the samples, that comes with SDK or
create your own application. In order to login, you need to
call openActiveSession method and implements its callback. Its syntax is
given below −
// start Facebook Login
Session.openActiveSession(this, true, new Session.StatusCallback()
{

// callback when session changes state

344 | P a g e
public void call(Session session, SessionState state, Exception
exception) {
if (session.isOpened()) {
// make request to;2 the /me API
Request.executeMeRequestAsync(session, new
Request.GraphUserCallback() {

// callback after Graph API response with user object


@Override
public void onCompleted(GraphUser user, Response
response) {
if (user != null) {
TextView welcome = (TextView)
findViewById(R.id.welcome);
welcome.setText("Hello " + user.getName() + "!");
}
}
});
}
}
}

Intent share
Intent share is used to share data between applications. In this strategy, we will
not handle the SDK stuff, but let the facebook application handles it. We will
simply call the facebook application and pass the data to share. This way, we
can share something on facebook.

Android provides intent library to share data between activities and applications.
In order to use it as share intent , we have to specify the type of the share intent
to ACTION_SEND. Its syntax is given below −
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);

Next thing you need to is to define the type of data to pass , and then pass the
data. Its syntax is given below −

shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, "Hello, from
tutorialspoint");
startActivity(Intent.createChooser(shareIntent, "Share your
thoughts"));

Apart from the these methods, there are other methods available that allows
intent handling. They are listed below −

345 | P a g e
Sr.N
Method & description
o

1 addCategory(String category)
This method add a new category to the intent.

2 createChooser(Intent target, CharSequence title)


Convenience function for creating a ACTION_CHOOSER Intent

getAction()
3 This method retrieve the general action to be performed, such as
ACTION_VIEW

getCategories()
4 This method return the set of all categories in the intent and the current scaling
event

5 putExtra(String name, int value)


This method add extended data to the intent.

toString()
6 This method returns a string containing a concise, human-readable description
of this object

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

Example
Here is an example demonstrating the use of IntentShare to share data on
facebook. It creates a basic application that allows you to share some text on
facebook.

To experiment with this example, you can run this on an actual device or in an
emulator.

Ste
Description
ps

You will use Android studio to create an Android application under a package
1
com.example.sairamkrishna.myapplication.

346 | P a g e
2 Modify src/MainActivity.java file to add necessary code.

3 Modify the res/layout/activity_main to add respective XML components.

Run the application and choose a running android device and install the application
4
on it and verify the results.

Following is the content of the modified main activity file MainActivity.java.


package com.example.sairamkrishna.myapplication;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import android.widget.Button;
import android.widget.ImageView;

import java.io.FileNotFoundException;
import java.io.InputStream;

public class MainActivity extends AppCompatActivity {


private ImageView img;

protected void onCreate(Bundle savedInstanceState) {


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

img=(ImageView)findViewById(R.id.imageView);
Button b1=(Button)findViewById(R.id.button);

b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
Uri screenshotUri = Uri.parse("android.
resource://comexample.sairamkrishna.myapplication/*");

try {
InputStream stream =
getContentResolver().openInputStream(screenshotUri);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

347 | P a g e
sharingIntent.setType("image/jpeg");
sharingIntent.putExtra(Intent.EXTRA_STREAM,
screenshotUri);
startActivity(Intent.createChooser(sharingIntent,
"Share image using"));
}
});
}
}
Following is the modified content of the xml res/layout/activity_main.xml.
In the below code abc indicates the logo of tutorialspoint.com

<?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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp"
android:text="Facebook share " />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials Point"
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:textSize="35dp"
android:textColor="#ff16ff01" />

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true"

348 | P a g e
android:src="@drawable/abc"/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Share"
android:id="@+id/button"
android:layout_marginTop="61dp"
android:layout_below="@+id/imageView"
android:layout_centerHorizontal="true" />

</RelativeLayout>
Following is the content of AndroidManifest.xml file.
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name=".MainActivity"
android:label="@string/app_name" >

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

</activity>
</application>
</manifest>

Let's try to run your Application. I assume you have connected your actual
Android Mobile device with your computer. To run the app from Android studio,
open one of your project's activity files and click Run icon from the toolbar.
Before starting your application, Android studio will display following window to
select an option where you want to run your Android application.

349 | P a g e
Select your mobile device as an option and then check your mobile device which
will display your default screen −

350 | P a g e
Now just tap on the button and you will see a list of share providers.

351 | P a g e
Now just select facebook from that list and then write any message. It is shown
in the image below −

352 | P a g e
Android - Gestures
Android provides special types of touch screen events such as pinch , double
tap, scrolls , long presses and flinch. These are all known as gestures.

Android provides GestureDetector class to receive motion events and tell us that
these events correspond to gestures or not. To use it , you need to create an
object of GestureDetector and then extend another class
with GestureDetector.SimpleOnGestureListener to act as a listener and
override some methods. Its syntax is given below −

353 | P a g e
GestureDetector myG;
myG = new GestureDetector(this,new Gesture());

class Gesture extends GestureDetector.SimpleOnGestureListener{


public boolean onSingleTapUp(MotionEvent ev) {
}

public void onLongPress(MotionEvent ev) {


}

public boolean onScroll(MotionEvent e1, MotionEvent e2, float


distanceX,
float distanceY) {
}

public boolean onFling(MotionEvent e1, MotionEvent e2, float


velocityX,
float velocityY) {
}
}

Handling Pinch Gesture


Android provides ScaleGestureDetector class to handle gestures like pinch
e.t.c. In order to use it, you need to instantiate an object of this class. Its syntax
is as follow −

ScaleGestureDetector SGD;
SGD = new ScaleGestureDetector(this,new ScaleListener());

The first parameter is the context and the second parameter is the event
listener. We have to define the event listener and override a
function OnTouchEvent to make it working. Its syntax is given below −

public boolean onTouchEvent(MotionEvent ev) {


SGD.onTouchEvent(ev);
return true;
}

private class ScaleListener extends


ScaleGestureDetector.SimpleOnScaleGestureListener {
@Override
public boolean onScale(ScaleGestureDetector detector) {
float scale = detector.getScaleFactor();
return true;
}
}

354 | P a g e
Apart from the pinch gestures , there are other methods available that notify
more about touch events. They are listed below −

Sr.N
Method & description
o

getEventTime()
1
This method get the event time of the current event being processed..

getFocusX()
2
This method get the X coordinate of the current gesture's focal point.

getFocusY()
3
This method get the Y coordinate of the current gesture's focal point.

getTimeDelta()
4 This method return the time difference in milliseconds between the previous
accepted scaling event and the current scaling event.

isInProgress()
5
This method returns true if a scale gesture is in progress..

onTouchEvent(MotionEvent event)
6
This method accepts MotionEvents and dispatches events when appropriate.

Example
Here is an example demonstrating the use of ScaleGestureDetector class. It
creates a basic application that allows you to zoom in and out through pinch.

To experiment with this example , you can run this on an actual device or in an
emulator with touch screen enabled.

Ste
Description
ps

You will use Android studio to create an Android application under a package
1
com.example.sairamkrishna.myapplication.

2 Modify src/MainActivity.java file to add necessary code.

3 Modify the res/layout/activity_main to add respective XML components

Run the application and choose a running android device and install the
4
application on it and verify the results

355 | P a g e
Following is the content of the modified main activity
file src/MainActivity.java.

package com.example.sairamkrishna.myapplication;

import android.app.Activity;
import android.graphics.Matrix;
import android.os.Bundle;

import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.widget.ImageView;

public class MainActivity extends Activity {


private ImageView iv;
private Matrix matrix = new Matrix();
private float scale = 1f;
private ScaleGestureDetector SGD;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

iv=(ImageView)findViewById(R.id.imageView);
SGD = new ScaleGestureDetector(this,new ScaleListener());
}

public boolean onTouchEvent(MotionEvent ev) {


SGD.onTouchEvent(ev);
return true;
}

private class ScaleListener extends ScaleGestureDetector.


SimpleOnScaleGestureListener {

@Override
public boolean onScale(ScaleGestureDetector detector) {
scale *= detector.getScaleFactor();
scale = Math.max(0.1f, Math.min(scale, 5.0f));
matrix.setScale(scale, scale);
iv.setImageMatrix(matrix);
return true;
}
}
}

Following is the modified content of the xml res/layout/activity_main.xml.

356 | P a g e
Here abc indicates the logo of tutorialspoint
<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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView android:text="Gestures
Example" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textview"
android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:id="@+id/textView"
android:layout_below="@+id/textview"
android:layout_centerHorizontal="true"
android:textColor="#ff7aff24"
android:textSize="35dp" />

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:scaleType="matrix"
android:layout_below="@+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />

</RelativeLayout>

Following is the content of the res/values/string.xml.

<resources>

357 | P a g e
<string name="app_name>My Application</string>
</resources>

Following is the content of AndroidManifest.xml file.

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


<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity

android:name="com.example.sairamkrishna.myapplicationMainActivity"
android:label="@string/app_name" >

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

</activity>

</application>
</manifest>

Let's try to run your application. I assume you have connected your actual
Android Mobile device with your computer. To run the app from Android studio,
open one of your project's activity files and click Run icon from the toolbar.The
sample output should be like this −

358 | P a g e
Now just place two fingers over android screen , and separate them a part and
you will see that the android image is zooming. It is shown in the image below −

359 | P a g e
360 | P a g e
Now again place two fingers over android screen, and try to close them and you
will see that the android image is now shrinking. It is shown in the image below

Android - Google Maps


Android allows us to integrate google maps in our application. You can show any
location on the map , or can show different routes on the map e.t.c. You can also
customize the map according to your choices.

Google Map - Layout file


Now you have to add the map fragment into xml layout file. Its syntax is given
below −

<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

Google Map - AndroidManifest file


The next thing you need to do is to add some permissions along with the Google
Map API key in the AndroidManifest.XML file. Its syntax is given below −

<!--Permissions-->

<uses-permission
android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission
android:name="com.google.android.providers.gsf.permission.
READ_GSERVICES" />
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<!--Google MAP API key-->

<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyDKymeBXNeiFWY5jRUejv6zItpmr2MVyQ0" />

361 | P a g e
Customizing Google Map
You can easily customize google map from its default view , and change it
according to your demand.

Adding Marker
You can place a maker with some text over it displaying your location on the
map. It can be done by via addMarker() method. Its syntax is given below −
final LatLng TutorialsPoint = new LatLng(21 , 57);
Marker TP = googleMap.addMarker(new MarkerOptions()
.position(TutorialsPoint).title("TutorialsPoint"));

Changing Map Type


You can also change the type of the MAP. There are four different types of map
and each give a different view of the map. These types are
Normal,Hybrid,Satellite and terrain. You can use them as below

googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);

Enable/Disable zoom
You can also enable or disable the zoom gestures in the map by calling
the setZoomControlsEnabled(boolean) method. Its syntax is given below −
googleMap.getUiSettings().setZoomGesturesEnabled(true);

Apart from these customization, there are other methods available in the
GoogleMap class , that helps you more customize the map. They are listed
below −

Sr.N
Method & description
o

1 addCircle(CircleOptions options)
This method add a circle to the map

2 addPolygon(PolygonOptions options)
This method add a polygon to the map

3 addTileOverlay(TileOverlayOptions options)
This method add tile overlay to the map

362 | P a g e
4 animateCamera(CameraUpdate update)
This method Moves the map according to the update with an animation

5 clear()
This method removes everything from the map.

6 getMyLocation()
This method returns the currently displayed user location.

moveCamera(CameraUpdate update)
7 This method repositions the camera according to the instructions defined in the
update

8 setTrafficEnabled(boolean enabled)
This method Toggles the traffic layer on or off.

9 snapshot(GoogleMap.SnapshotReadyCallback callback)
This method Takes a snapshot of the map

10 stopAnimation()
This method stops the camera animation if there is one in progress

Example
Here is an example demonstrating the use of GoogleMap class. It creates a basic
M application that allows you to navigate through the map.

To experiment with this example , you can run this on an actual device or in an
emulator.

Create a project with google maps activity as shown below −

363 | P a g e
It will open the following screen and copy the console url for API Key as shown
below −

Copy this and paste it to your browser. It will give the following screen −

364 | P a g e
Click on continue and click on Create API Key then it will show the following
screen

Here is the content of activity_main.xml.


<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"

tools:context="com.example.tutorialspoint7.myapplication.MapsActivi
ty" />
Here is the content of MapActivity.java.
In the below code we have given sample latitude and longitude details

package com.example.tutorialspoint7.myapplication;

import android.support.v4.app.FragmentActivity;

365 | P a g e
import android.os.Bundle;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements


OnMapReadyCallback {

private GoogleMap mMap;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the
map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}

/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be
used.
* This is where we can add markers or lines, add listeners or
move the camera.
* In this case, we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device.
* This method will only be triggered once the user has
installed
Google Play services and returned to the app.
*/

@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng TutorialsPoint = new LatLng(21, 57);
mMap.addMarker(new

MarkerOptions().position(TutorialsPoint).title("Tutorialspoint.com"
));

366 | P a g e
mMap.moveCamera(CameraUpdateFactory.newLatLng(TutorialsPoint));
}
}
Following is the content of AndroidManifest.xml file.
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tutorialspoint7.myapplication">

<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required
to use
Google Maps Android API v2, but you must specify either
coarse or fine
location permissions for the 'MyLocation' functionality.
-->

<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION" />
<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">

<!--
The API key for Google Maps-based APIs is defined as a
string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used
to sign the APK.
You need a different API key for each encryption key,
including the release key
that is used to sign the APK for publishing.
You can define the keys for the debug and
release targets in src/debug/ and src/release/.
-->

<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyAXhBdyKxUo_cb-EkSgWJQTdqR0QjLcqes" />

<activity
android:name=".MapsActivity"

367 | P a g e
android:label="@string/title_activity_maps">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

Output should be like this −

368 | P a g e
Android - Image Effects
Android allows you to manipulate images by adding different kinds of effects on
the images. You can easily apply image processing techniques to add certain
kinds of effects on images. The effects could be brightness,darkness, grayscale
conversion e.t.c.

Android provides Bitmap class to handle images. This can be found under
android.graphics.bitmap. There are many ways through which you can
instantiate bitmap. We are creating a bitmap of image from the imageView.

private Bitmap bmp;


private ImageView img;
img = (ImageView)findViewById(R.id.imageView1);
BitmapDrawable abmp = (BitmapDrawable)img.getDrawable();

Now we will create bitmap by calling getBitmap() function of BitmapDrawable


class. Its syntax is given below −

bmp = abmp.getBitmap();

An image is nothing but a two dimensional matrix. Same way you will handle a
bitmap. An image consist of pixels. So you will get pixels from this bitmap and
apply processing to it. Its syntax is as follows −

for(int i=0; i<bmp.getWidth(); i++){


for(int j=0; j<bmp.getHeight(); j++){
int p = bmp.getPixel(i, j);
}
}

The getWidth() and getHeight() functions returns the height and width of the
matrix. The getPixel() method returns the pixel at the specified index. Once you
got the pixel, you can easily manipulate it according to your needs.

Apart from these methods, there are other methods that helps us manipulate
images more better.

Sr.N
Method & description
o

369 | P a g e
copy(Bitmap.Config config, boolean isMutable)
1
This method copy this bitmap's pixels into the new bitmap

createBitmap(DisplayMetrics display, int width, int


2 height, Bitmap.Config config)
Returns a mutable bitmap with the specified width and height

createBitmap(int width, int height, Bitmap.Config


3 config)
Returns a mutable bitmap with the specified width and height

createBitmap(Bitmap src)
4
Returns an immutable bitmap from the source bitmap

extractAlpha()
5
Returns a new bitmap that captures the alpha values of the original

getConfig()
6
This mehtod eturn that config, otherwise return null

getDensity()
7
Returns the density for this bitmap

getRowBytes()
8
Return the number of bytes between rows in the bitmap's pixels

setPixel(int x, int y, int color)


9 Write the specified Color into the bitmap (assuming it is mutable) at the x,y
coordinate

setDensity(int density)
10
This method specifies the density for this bitmap

Example
The below example demonstrates some of the image effects on the bitmap. It
crates a basic application that allows you to convert the picture into grayscale
and much more.

To experiment with this example , you need to run this on an actual device.

Ste
Description
ps

1 You will use Android studio to create an Android application under a package

370 | P a g e
com.example.sairamkrishna.myapplication.

2 Modify src/MainActivity.java file to add necessary code.

3 Modify the res/layout/activity_main to add respective XML components

Run the application and choose a running android device and install the
4
application on it and verify the results

Following is the content of the modified MainActivity.java.

package com.example.sairamkrishna.myapplication;

import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.support.v7.app.ActionBarActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends ActionBarActivity {


Button b1, b2, b3;
ImageView im;

private Bitmap bmp;


private Bitmap operation;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

b1 = (Button) findViewById(R.id.button);
b2 = (Button) findViewById(R.id.button2);
b3 = (Button) findViewById(R.id.button3);
im = (ImageView) findViewById(R.id.imageView);

BitmapDrawable abmp = (BitmapDrawable) im.getDrawable();


bmp = abmp.getBitmap();
}

public void gray(View view) {


operation =
Bitmap.createBitmap(bmp.getWidth(),bmp.getHeight(),
bmp.getConfig());

371 | P a g e
double red = 0.33;
double green = 0.59;
double blue = 0.11;

for (int i = 0; i < bmp.getWidth(); i++) {


for (int j = 0; j < bmp.getHeight(); j++) {
int p = bmp.getPixel(i, j);
int r = Color.red(p);
int g = Color.green(p);
int b = Color.blue(p);

r = (int) red * r;
g = (int) green * g;
b = (int) blue * b;
operation.setPixel(i, j, Color.argb(Color.alpha(p), r,
g, b));
}
}
im.setImageBitmap(operation);
}

public void bright(View view){


operation= Bitmap.createBitmap(bmp.getWidth(),
bmp.getHeight(),bmp.getConfig());

for(int i=0; i<bmp.getWidth(); i++){


for(int j=0; j<bmp.getHeight(); j++){
int p = bmp.getPixel(i, j);
int r = Color.red(p);
int g = Color.green(p);
int b = Color.blue(p);
int alpha = Color.alpha(p);

r = 100 + r;
g = 100 + g;
b = 100 + b;
alpha = 100 + alpha;
operation.setPixel(i, j, Color.argb(alpha, r, g, b));
}
}
im.setImageBitmap(operation);
}

public void dark(View view){


operation=
Bitmap.createBitmap(bmp.getWidth(),bmp.getHeight(),bmp.getConfig())
;

for(int i=0; i<bmp.getWidth(); i++){

372 | P a g e
for(int j=0; j<bmp.getHeight(); j++){
int p = bmp.getPixel(i, j);
int r = Color.red(p);
int g = Color.green(p);
int b = Color.blue(p);
int alpha = Color.alpha(p);

r = r - 50;
g = g - 50;
b = b - 50;
alpha = alpha -50;
operation.setPixel(i, j, Color.argb(Color.alpha(p), r,
g, b));
}
}
im.setImageBitmap(operation);
}

public void gama(View view) {


operation =
Bitmap.createBitmap(bmp.getWidth(),bmp.getHeight(),bmp.getConfig())
;

for(int i=0; i<bmp.getWidth(); i++){


for(int j=0; j<bmp.getHeight(); j++){
int p = bmp.getPixel(i, j);
int r = Color.red(p);
int g = Color.green(p);
int b = Color.blue(p);
int alpha = Color.alpha(p);

r = r + 150;
g = 0;
b = 0;
alpha = 0;
operation.setPixel(i, j, Color.argb(Color.alpha(p), r,
g, b));
}
}
im.setImageBitmap(operation);
}

public void green(View view){


operation =
Bitmap.createBitmap(bmp.getWidth(),bmp.getHeight(),
bmp.getConfig());

for(int i=0; <bmp.getWidth(); i++){


for(int j=0; j<bmp.getHeight(); j++){

373 | P a g e
int p = bmp.getPixel(i, j);
int r = Color.red(p);
int g = Color.green(p);
int b = Color.blue(p);
int alpha = Color.alpha(p);

r = 0;
g = g+150;
b = 0;
alpha = 0;
operation.setPixel(i, j, Color.argb(Color.alpha(p), r,
g, b));
}
}
im.setImageBitmap(operation);
}

public void blue(View view){


operation =
Bitmap.createBitmap(bmp.getWidth(),bmp.getHeight(),
bmp.getConfig());

for(int i=0; i<bmp.getWidth(); i++){


for(int j=0; j<bmp.getHeight(); j++){
int p = bmp.getPixel(i, j);
int r = Color.red(p);
int g = Color.green(p);
int b = Color.blue(p);
int alpha = Color.alpha(p);

r = 0;
g = 0;
b = b+150;
alpha = 0;
operation.setPixel(i, j, Color.argb(Color.alpha(p), r,
g, b));
}
}
im.setImageBitmap(operation);
}
}

Following is the modified content of the xml res/layout/activity_main.xml.

Here abc indicates about logo of tutorialspoint.com


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

374 | P a g e
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp"
android:text="Image Effects" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials Point"
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:textSize="35dp"
android:textColor="#ff16ff01" />

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true"
android:src="@drawable/abc"/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Gray"
android:onClick="gray"
android:id="@+id/button"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="97dp" />

<Button
android:layout_width="wrap_content"

375 | P a g e
android:layout_height="wrap_content"
android:text="dark"
android:onClick="dark"
android:id="@+id/button2"
android:layout_alignBottom="@+id/button"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Bright"
android:onClick="bright"
android:id="@+id/button3"
android:layout_alignTop="@+id/button2"
android:layout_centerHorizontal="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Red"
android:onClick="gama"
android:id="@+id/button4"
android:layout_below="@+id/button3"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Green"
android:onClick="green"
android:id="@+id/button5"
android:layout_alignTop="@+id/button4"
android:layout_alignLeft="@+id/button3"
android:layout_alignStart="@+id/button3" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="blue"
android:onClick="blue"
android:id="@+id/button6"
android:layout_below="@+id/button2"
android:layout_toRightOf="@+id/textView"
android:layout_toEndOf="@+id/textView" />

</RelativeLayout>

376 | P a g e
Following is the content of AndroidManifest.xml file.

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


<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name=".MainActivity"
android:label="@string/app_name" >

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

</activity>

</application>
</manifest>

Let's try to run our application we just modified. I assume you had created
your AVD while doing environment setup. To run the app from Android studio,
open one of your project's activity files and click Run icon from the toolbar.
Android studio installs the app on your AVD and starts it and if everything is fine
with your setup and application, it will display following Emulator window −

377 | P a g e
Now if you will look at your device screen , you will see the an image of android
along with three buttons.

Now just select the Gray button that will convert your image into grayscale and
will update the UI. It is shown below −

378 | P a g e
Now tap on the bright button, that will add some value to each pixel of the
image and thus makes an illusion of brightness. It is shown below −

379 | P a g e
Now tap on the dark button, that will subtract some value to each pixel of the
image and thus makes an illusion of dark. It is shown below −

380 | P a g e
Now tap on the red button, that will subtract some value to each pixel of the
image and thus makes an illusion of dark. It is shown below −

381 | P a g e
Now tap on the green button, that will subtract some value to each pixel of the
image and thus makes an illusion of dark. It is shown below −

382 | P a g e
Now tap on the blue button, that will subtract some value to each pixel of the
image and thus makes an illusion of dark. It is shown below −

383 | P a g e
Android - Image Switcher
Sometimes you don't want an image to appear abruptly on the screen, rather
you want to apply some kind of animation to the image when it transitions from
one image to another. This is supported by android in the form of
ImageSwitcher.

An image switcher allows you to add some transitions on the images through
the way they appear on screen. In order to use image Switcher, you need to
define its XML component first. Its syntax is given below −

384 | P a g e
<ImageSwitcher
android:id="@+id/imageSwitcher1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" >
</ImageSwitcher>

Now we create an intance of ImageSwithcer in java file and get a reference of


this XML component. Its syntax is given below −

private ImageSwitcher imageSwitcher;


imageSwitcher = (ImageSwitcher)findViewById(R.id.imageSwitcher1);

The next thing we need to do implement the ViewFactory interface and


implement unimplemented method that returns an imageView. Its syntax is
below −

imageSwitcher.setImageResource(R.drawable.ic_launcher);
imageSwitcher.setFactory(new ViewFactory() {
public View makeView() {
ImageView myView = new ImageView(getApplicationContext());
return myView;
}
}

The last thing you need to do is to add Animation to the ImageSwitcher. You
need to define an object of Animation class through AnimationUtilities class by
calling a static method loadAnimation. Its syntax is given below −

Animation in =
AnimationUtils.loadAnimation(this,android.R.anim.slide_in_left);
imageSwitcher.setInAnimation(in);
imageSwitcher.setOutAnimation(out);

The method setInAnimaton sets the animation of the appearance of the object
on the screen whereas setOutAnimation does the opposite. The method
loadAnimation() creates an animation object.

Apart from these methods, there are other methods defined in the
ImageSwitcher class. They are defined below −

Sr.N
Method & description
o

385 | P a g e
setImageDrawable(Drawable drawable)
1
Sets an image with image switcher. The image is passed in the form of bitmap

setImageResource(int resid)
2 Sets an image with image switcher. The image is passed in the form of integer
id

setImageURI(Uri uri)
3
Sets an image with image switcher. THe image is passed in the form of URI

ImageSwitcher(Context context, AttributeSet attrs)


4 Returns an image switcher object with already setting some attributes passed in
the method

onInitializeAccessibilityEvent (AccessibilityEvent event)


5 Initializes an AccessibilityEvent with information about this View which is the
event source

onInitializeAccessibilityNodeInfo (AccessibilityNodeInfo
6 info)
Initializes an AccessibilityNodeInfo with information about this view

Example
The below example demonstrates some of the image switcher effects on the
bitmap. It crates a basic application that allows you to view the animation
effects on the images.

To experiment with this example , you need to run this on an actual device.

Ste
Description
ps

You will use Android studio IDE to create an Android application under a
1
package com.example.sairamkrishna.myapplication.

2 Modify src/MainActivity.java file to add necessary code.

3 Modify the res/layout/activity_main to add respective XML components

Run the application and choose a running android device and install the
4
application on it and verify the results

Following is the content of the modified main activity


file src/MainActivity.java.

386 | P a g e
In the below code tp and abc indicates the logo of tutorialspoint.com
package com.example.sairamkrishna.myapplication;

import android.app.Activity;
import android.app.ActionBar.LayoutParams;
import android.os.Bundle;
import android.view.View;

import android.widget.Button;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ViewSwitcher.ViewFactory;

public class MainActivity extends Activity {


private ImageSwitcher sw;
private Button b1,b2;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

b1 = (Button) findViewById(R.id.button);
b2 = (Button) findViewById(R.id.button2);

sw = (ImageSwitcher) findViewById(R.id.imageSwitcher);
sw.setFactory(new ViewFactory() {
@Override
public View makeView() {
ImageView myView = new
ImageView(getApplicationContext());
myView.setScaleType(ImageView.ScaleType.FIT_CENTER);
myView.setLayoutParams(new

ImageSwitcher.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
return myView;
}
});

b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "previous
Image",
Toast.LENGTH_LONG).show();
sw.setImageResource(R.drawable.abc);

387 | P a g e
}
});

b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Next Image",
Toast.LENGTH_LONG).show();
sw.setImageResource(R.drawable.tp);
}
});
}
}

Following is the modified content of the xml res/layout/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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView android:text="Gestures Example"


android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textview"
android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:id="@+id/textView"
android:layout_below="@+id/textview"
android:layout_centerHorizontal="true"
android:textColor="#ff7aff24"
android:textSize="35dp" />

<ImageSwitcher
android:layout_width="wrap_content"

388 | P a g e
android:layout_height="wrap_content"
android:id="@+id/imageSwitcher"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:layout_marginTop="168dp" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/left"
android:id="@+id/button"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/right"
android:id="@+id/button2"
android:layout_alignParentBottom="true"
android:layout_alignLeft="@+id/button"
android:layout_alignStart="@+id/button" />

</RelativeLayout>

Following is the content of Strings.xml file.

<resources>
<string name="app_name">My Application</string>
<string name="left"><![CDATA[<]]></string>
<string name="right"><![CDATA[>]]></string>
</resources>

Following is the content of AndroidManifest.xml file.

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


<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication"

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity

389 | P a g e
android:name="com.example.sairamkrishna.myapplication.MainActivity"
android:label="@string/app_name" >

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

</activity>

</application>
</manifest>

Let's try to run your application we just modified. I assume you had created
your AVD while doing environment setup. To run the app from Android studio,
open one of your project's activity files and click Run icon from the toolbar.
Android studio installs the app on your AVD and starts it and if everything is fine
with your setup and application, it will display following Emulator window −

390 | P a g e
Now if you will look at your device screen , you will see the two buttons.

Now just select the upper button that right arrow. An image would appear from
right and move towards left. It is shown below −

391 | P a g e
Now tap on the below button, that will bring back the previous image with some
transition. It is shown below −

392 | P a g e
Android - Internal Storage
Android provides many kinds of storage for applications to store their data.
These storage places are shared preferences, internal and external storage,
SQLite storage, and storage via network connection.

393 | P a g e
In this chapter we are going to look at the internal storage. Internal storage is
the storage of the private data on the device memory.

By default these files are private and are accessed by only your application and
get deleted , when user delete your application.

Writing file
In order to use internal storage to write some data in the file, call the
openFileOutput() method with the name of the file and the mode. The mode
could be private , public e.t.c. Its syntax is given below −

FileOutputStream fOut = openFileOutput("file name


here",MODE_WORLD_READABLE);

The method openFileOutput() returns an instance of FileOutputStream. So you


receive it in the object of FileInputStream. After that you can call write method
to write data on the file. Its syntax is given below −

String str = "data";


fOut.write(str.getBytes());
fOut.close();

Reading file
In order to read from the file you just created , call the openFileInput() method
with the name of the file. It returns an instance of FileInputStream. Its syntax is
given below −

FileInputStream fin = openFileInput(file);

After that, you can call read method to read one character at a time from the
file and then you can print it. Its syntax is given below −

int c;
String temp="";
while( (c = fin.read()) != -1){
temp = temp + Character.toString((char)c);
}

//string temp contains all the data of the file.


fin.close();

394 | P a g e
Apart from the the methods of write and close, there are other methods
provided by the FileOutputStream class for better writing files. These methods
are listed below −

Sr.N
Method & description
o

FileOutputStream(File file, boolean append)


1
This method constructs a new FileOutputStream that writes to file.

getChannel()
2 This method returns a write-only FileChannel that shares its position with this
stream

getFD()
3
This method returns the underlying file descriptor

write(byte[] buffer, int byteOffset, int byteCount)


4 This method Writes count bytes from the byte array buffer starting at position
offset to this stream

Apart from the the methods of read and close, there are other methods provided
by the FileInputStream class for better reading files. These methods are listed
below −

Sr.N
Method & description
o

available()
1 This method returns an estimated number of bytes that can be read or skipped
without blocking for more input

getChannel()
2 This method returns a read-only FileChannel that shares its position with this
stream

getFD()
3
This method returns the underlying file descriptor

read(byte[] buffer, int byteOffset, int byteCount)


4 This method reads at most length bytes from this stream and stores them in the
byte array b starting at offset

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

395 | P a g e
Example
Here is an example demonstrating the use of internal storage to store and read
files. It creates a basic storage application that allows you to read and write
from internal storage.

To experiment with this example, you can run this on an actual device or in an
emulator.

Ste
Description
ps

You will use Android Studio IDE to create an Android application under a
1
package com.example.sairamkrishna.myapplication.

2 Modify src/MainActivity.java file to add necessary code.

3 Modify the res/layout/activity_main to add respective XML components

Run the application and choose a running android device and install the
4
application on it and verify the results

Following is the content of the modified main activity


file src/MainActivity.java.

package com.example.sairamkrishna.myapplication;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class MainActivity extends Activity {


Button b1,b2;
TextView tv;
EditText ed1;

String data;
private String file = "mydata";

@Override

396 | P a g e
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

b1=(Button)findViewById(R.id.button);
b2=(Button)findViewById(R.id.button2);

ed1=(EditText)findViewById(R.id.editText);
tv=(TextView)findViewById(R.id.textView2);
b1.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
data=ed1.getText().toString();
try {
FileOutputStream fOut =
openFileOutput(file,MODE_WORLD_READABLE);
fOut.write(data.getBytes());
fOut.close();
Toast.makeText(getBaseContext(),"file
saved",Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});

b2.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
try {
FileInputStream fin = openFileInput(file);
int c;
String temp="";
while( (c = fin.read()) != -1){
temp = temp + Character.toString((char)c);
}
tv.setText(temp);
Toast.makeText(getBaseContext(),"file
read",Toast.LENGTH_SHORT).show();
}
catch(Exception e){
}
}
});
}

397 | P a g e
}

Following is the modified content of the xml res/layout/activity_main.xml.

In the following code abc indicates the logo of tutorialspoint.com


<?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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView android:text="Internal storage"


android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textview"
android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:id="@+id/textView"
android:layout_below="@+id/textview"
android:layout_centerHorizontal="true"
android:textColor="#ff7aff24"
android:textSize="35dp" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:id="@+id/button"
android:layout_alignParentBottom="true"
android:layout_alignLeft="@+id/textView"
android:layout_alignStart="@+id/textView" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"

398 | P a g e
android:hint="Enter Text"
android:focusable="true"
android:textColorHighlight="#ff7eff15"
android:textColorHint="#ffff25e6"
android:layout_below="@+id/imageView"
android:layout_alignRight="@+id/textView"
android:layout_alignEnd="@+id/textView"
android:layout_marginTop="42dp"
android:layout_alignLeft="@+id/imageView"
android:layout_alignStart="@+id/imageView" />

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="load"
android:id="@+id/button2"
android:layout_alignTop="@+id/button"
android:layout_alignRight="@+id/editText"
android:layout_alignEnd="@+id/editText" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Read"
android:id="@+id/textView2"
android:layout_below="@+id/editText"
android:layout_toLeftOf="@+id/button2"
android:layout_toStartOf="@+id/button2"
android:textColor="#ff5bff1f"
android:textSize="25dp" />

</RelativeLayout>

Following is the content of the res/values/string.xml.

<resources>
<string name="app_name">My Application</string>
</resources>

Following is the content of AndroidManifest.xml file.

399 | P a g e
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name=".MainActivity"
android:label="@string/app_name" >

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

</activity>

</application>
</manifest>

Let's try to run our Storage application we just modified. I assume you had
created your AVD while doing environment setup. To run the app from Android
studio, open one of your project's activity files and click Run icon from the tool
bar. Android studio installs the app on your AVD and starts it and if everything is
fine with your set-up and application, it will display following Emulator window −

400 | P a g e
Now what you need to do is to enter any text in the field. For example , i have
entered some text. Press the save button. The following notification would
appear in you AVD −

401 | P a g e
Now when you press the load button, the application will read the file , and
display the data. In case of our, following data would be returned −

402 | P a g e
Note you can actually view this file by switching to DDMS tab. In DDMS , select
file explorer and navigate this path.

tools>android>android device Monitor

This has also been shown in the image below.

403 | P a g e
Android - JetPlayer
The Android platform includes a JET engine that lets you add interactive
playback of JET audio content in your applications. Android provides JetPlayer
class to handle this stuff.

In order to Jet Content , you need to use the JetCreator tool that comes with
AndroidSDK. The usage of jetCreator has been discussed in the example. In
order to play the content created by JetCreator, you need JetPlayer class
supported by android.

In order to use JetPlayer , you need to instantiate an object of JetPlayer class. Its
syntax is given below −

JetPlayer jetPlayer = JetPlayer.getJetPlayer();

The next thing you need to do is to call loadJetFile method and pass in the path
of your Jet file. After that you have to add this into the Queue of JetPlayer. Its
syntax is given below −

jetPlayer.loadJetFile("/sdcard/level1.jet");
byte segmentId = 0;

404 | P a g e
// queue segment 5, repeat once, use General MIDI, transpose by -1
octave
jetPlayer.queueJetSegment(5, -1, 1, -1, 0, segmentId++);

The method queueJetSegment Queues the specified segment in the JET Queue.
The last thing you need to is to call the play method to start playing the music.
Its syntax is given below −

jetPlayer.play();

Apart from these methods, there are other methods defined in the JetPlayer
class. They are defined below −

Sr.N
Method & description
o

1 clearQueue()
Empties the segment queue, and clears all clips that are scheduled for playback

2 closeJetFile()
Closes the resource containing the JET content

3 getJetPlayer()
Factory method for the JetPlayer class

4 loadJetFile(String path)
Loads a .jet file from a given path

5 pause()
Pauses the playback of the JET segment queue

6 release()
Stops the current JET playback, and releases all associated native resources

Example
The following example demonstrates the use of JetCreator tool to create Jet
content. Once that content is created, you can play it through JetPlayer.

To experiment with this example , you need to run this on an actual device or in
an emulator.

Ste Description

405 | P a g e
ps

You will use Android studio IDE to create an Android application and name it as
1
JetPlayer under a package com.example.jetplayer.

2 Install Python and WxPython on your computer from internet.

3 Run the jet creator from command prompt

4 Create Jet content and then save it

5 Run the application and verify the results

Using JetCreator

Installing python
The first step that you need while using JetCreator is to install the python. The
python can be installed from its official website here or from any where else on
the internet.

Please keep in mind the version number of the python should either be 2.6 or
2.7 because this example follows that.

Once you download python install it. After installing you have to set path to the
python. Open your command prompt and type the following command.It is
shown in the image below −

Once path is set , you can verify it by typing python and hit enter. It is shown
below −

406 | P a g e
Installing WxPython
The next thing you need to do is to install the wxPython. It can be
downloaded here. Once downloaded , you will install it. It will be automatically
installed in the python directory.

Ruuning JetCreator
The next thing you need to is to move to the path where JetCreator is present. It
is in the tools,SDK folder of the android. It is shown below −

Once in the folder type this command and hit enter.

python JetCreator.py

It is shown in the figure below −

As soon as you hit enter, Jet Creator window will open. It would be something
like this.

407 | P a g e
Creating JetContent
In the above Jet Window, click on the import button. And select
JetCreator_demo_1 or 2 from the JetFolder from the demo content folder in the
Jet folder. It is shown in the image below:

Once you import the content , you will see the content in the JetCreator window.
It is shown below −

408 | P a g e
Now you can explore different options of JetCreator by visiting the JetCreator
link here. Finally in order to create .jet file , you need to save the content from
the file menu.

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

Verifying Results
Once you got the jet file, you can play it using jet player. The main code of
playing it has been given below −

JetPlayer jetPlayer = JetPlayer.getJetPlayer();


jetPlayer.loadJetFile("/sdcard/level1.jet");
byte segmentId = 0;

// queue segment 5, repeat once, use General MIDI, transpose by -1


octave
jetPlayer.queueJetSegment(5, -1, 1, -1, 0, segmentId++);
jetPlayer.play();

409 | P a g e
Android - JSON Parser
JSON stands for JavaScript Object Notation.It is an independent data exchange
format and is the best alternative for XML. This chapter explains how to parse
the JSON file and extract necessary information from it.

Android provides four different classes to manipulate JSON data. These classes
are JSONArray,JSONObject,JSONStringer and JSONTokenizer.

The first step is to identify the fields in the JSON data in which you are interested
in. For example. In the JSON given below we interested in getting temperature
only.

{
"sys":
{
"country":"GB",
"sunrise":1381107633,
"sunset":1381149604
},
"weather":[
{
"id":711,
"main":"Smoke",
"description":"smoke",
"icon":"50n"
}
],

"main":
{
"temp":304.15,
"pressure":1009,
}
}

JSON - Elements
An JSON file consist of many components. Here is the table defining the
components of an JSON file and their description −

Sr.N
Component & description
o

Array([)
1
In a JSON file , square bracket ([) represents a JSON array

410 | P a g e
Objects({)
2
In a JSON file, curly bracket ({) represents a JSON object

Key
3 A JSON object contains a key that is just a string. Pairs of key/value make up a
JSON object

Value
4
Each key has a value that could be string , integer or double e.t.c

JSON - Parsing
For parsing a JSON object, we will create an object of class JSONObject and
specify a string containing JSON data to it. Its syntax is −

String in;
JSONObject reader = new JSONObject(in);

The last step is to parse the JSON. A JSON file consist of different object with
different key/value pair e.t.c. So JSONObject has a separate function for parsing
each of the component of JSON file. Its syntax is given below −

JSONObject sys = reader.getJSONObject("sys");


country = sys.getString("country");

JSONObject main = reader.getJSONObject("main");


temperature = main.getString("temp");

The method getJSONObject returns the JSON object. The


method getString returns the string value of the specified key.

Apart from the these methods , there are other methods provided by this class
for better parsing JSON files. These methods are listed below −

Sr.N
Method & description
o

get(String name)
1
This method just Returns the value but in the form of Object type

getBoolean(String name)
2
This method returns the boolean value specified by the key

3 getDouble(String name)

411 | P a g e
This method returns the double value specified by the key

getInt(String name)
4
This method returns the integer value specified by the key

getLong(String name)
5
This method returns the long value specified by the key

length()
6
This method returns the number of name/value mappings in this object..

names()
7
This method returns an array containing the string names in this object.

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

Example
To experiment with this example , you can run this on an actual device or in an
emulator.

Ste
Description
ps

1 You will use Android studio to create an Android application.

2 Modify src/MainActivity.java file to add necessary code.

3 Modify the res/layout/activity_main to add respective XML components

4 Modify the res/values/string.xml to add necessary string components

Run the application and choose a running android device and install the
5
application on it and verify the results

Following is the content of the modified main activity


file src/MainActivity.java.

package com.example.tutorialspoint7.myapplication;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

412 | P a g e
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {

private String TAG = MainActivity.class.getSimpleName();


private ListView lv;

ArrayList<HashMap<String, String>> contactList;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

contactList = new ArrayList<>();


lv = (ListView) findViewById(R.id.list);

new GetContacts().execute();
}

private class GetContacts extends AsyncTask<Void, Void, Void> {


@Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(MainActivity.this,"Json Data is
downloading",Toast.LENGTH_LONG).show();

@Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "http://api.androidhive.info/contacts/";
String jsonStr = sh.makeServiceCall(url);

Log.e(TAG, "Response from url: " + jsonStr);


if (jsonStr != null) {

413 | P a g e
try {
JSONObject jsonObj = new JSONObject(jsonStr);

// Getting JSON Array node


JSONArray contacts =
jsonObj.getJSONArray("contacts");

// looping through All Contacts


for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String email = c.getString("email");
String address = c.getString("address");
String gender = c.getString("gender");

// Phone node is JSON Object


JSONObject phone = c.getJSONObject("phone");
String mobile = phone.getString("mobile");
String home = phone.getString("home");
String office = phone.getString("office");

// tmp hash map for single contact


HashMap<String, String> contact = new
HashMap<>();

// adding each child node to HashMap key => value


contact.put("id", id);
contact.put("name", name);
contact.put("email", email);
contact.put("mobile", mobile);

// adding contact to contact list


contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});

} else {

414 | P a g e
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat
for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}

return null;
}

@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ListAdapter adapter = new SimpleAdapter(MainActivity.this,
contactList,
R.layout.list_item, new String[]{ "email","mobile"},
new int[]{R.id.email, R.id.mobile});
lv.setAdapter(adapter);
}
}
}

Following is the modified content of the xml HttpHandler.java.

package com.example.tutorialspoint7.myapplication;

import android.util.Log;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

public class HttpHandler {

private static final String TAG =


HttpHandler.class.getSimpleName();

415 | P a g e
public HttpHandler() {
}

public String makeServiceCall(String reqUrl) {


String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection)
url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new
BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}

private String convertStreamToString(InputStream is) {


BufferedReader reader = new BufferedReader(new
InputStreamReader(is));
StringBuilder sb = new StringBuilder();

String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}

return sb.toString();
}
}

416 | P a g e
Following is the modified content of the xml res/layout/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="com.example.tutorialspoint7.myapplication.MainActivi
ty">

<ListView
android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</RelativeLayout>

Following is the modified content of the xml res/layout/list_item.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="wrap_content"
android:orientation="vertical"
android:padding="@dimen/activity_horizontal_margin">
<TextView
android:id="@+id/email"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textColor="@color/colorAccent" />

<TextView
android:id="@+id/mobile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d5d"
android:textStyle="bold" />
</LinearLayout>

Following is the content of AndroidManifest.xml file.

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


<manifest
xmlns:android="http://schemas.android.com/apk/res/android"

417 | P a g e
package="com.example.tutorialspoint7.myapplication">

<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>

Let's try to run our application we just modified. I assume you had created
your AVD while doing environment setup. To run the app from Android studio,
open one of your project's activity files and click Run icon from the toolbar.
Android studio installs the app on your AVD and starts it and if everything is fine
with your setup and application, it will display following Emulator window −

418 | P a g e
Above Example showing the data from string json,The data has contained
employer details as well as salary information.

Android - LinkedIn Integration


Android allows your application to connect to Linkedin and share data or any
kind of updates on Linkedin. This chapter is about integrating Linkedin into your
application.

419 | P a g e
There are two ways through which you can integrate Linkedin and share
something from your application. These ways are listed below.

 Linkedin SDK (Scribe)


 Intent Share

Integrating Linkedin SDK


This is the first way of connecting with Linkedin. You have to register your
application and then receive some Application Id , and then you have to
download the Linkedin SDK and add it to your project. The steps are listed
below.

Registering your application


Create a new Linkedin application
at https://www.linkedin.com/secure/developer. Click on add new application. It is
shown below −

Now fill in your application name , description and your website url. It is shown
below −

If everything works fine, you will receive an API key with the secret. Just copy
the API key and save it somewhere. It is shown in the image below −

420 | P a g e
Downloading SDK and integrating it
Download Linkedin sdk here. Copy the scribe-1.3.0.jar jar into your project libs
folder.

Posting updates on Linkedin application


Once everything is complete, you can run the Linkedin samples which can be
found here.

Intent share
Intent share is used to share data between applications. In this strategy, we will
not handle the SDK stuff, but let the Linkedin application handles it. We will
simply call the Linkedin application and pass the data to share. This way, we can
share something on Linkedin.

Android provides intent library to share data between activities and applications.
In order to use it as share intent, we have to specify the type of the share intent
to ACTION_SEND. Its syntax is given below −
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);

Next thing you need to is to define the type of data to pass , and then pass the
data. Its syntax is given below −

shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, "Hello, from
tutorialspoint");
startActivity(Intent.createChooser(shareIntent, "Share your
thoughts"));

Apart from the these methods , there are other methods available that allows
intent handling. They are listed below −

421 | P a g e
Sr.N
Method & description
o

1 addCategory(String category)
This method add a new category to the intent.

2 createChooser(Intent target, CharSequence title)


Convenience function for creating a ACTION_CHOOSER Intent

getAction()
3 This method retrieve the general action to be performed, such as
ACTION_VIEW

getCategories()
4 This method return the set of all categories in the intent.nt and the current
scaling event

5 putExtra(String name, int value)


This method add extended data to the intent.

toString()
6 This method returns a string containing a concise, human-readable description
of this object

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

Example
Here is an example demonstrating the use of IntentShare to share data on
Linkedin. It creates a basic application that allows you to share some text on
Linkedin.

To experiment with this example, you can run this on an actual device or in an
emulator.

Ste
Description
ps

You will use Android studio to create an Android application under a package
1
com.example.sairamkrishna.myapplication.

422 | P a g e
2 Modify src/MainActivity.java file to add necessary code.

3 Modify the res/layout/activity_main to add respective XML components

Run the application and choose a running android device and install the application
4
on it and verify the results

Following is the content of the modified main activity file MainActivity.java.


package com.example.sairamkrishna.myapplication;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.FileNotFoundException;
import java.io.InputStream;

public class MainActivity extends AppCompatActivity {


private ImageView img;

protected void onCreate(Bundle savedInstanceState) {


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

img = (ImageView) findViewById(R.id.imageView);


Button b1 = (Button) findViewById(R.id.button);

b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
Uri screenshotUri = Uri.parse("android.

resource://comexample.sairamkrishna.myapplication/*");

try {
InputStream stream =
getContentResolver().openInputStream(screenshotUri);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

sharingIntent.setType("image/jpeg");

423 | P a g e
sharingIntent.putExtra(Intent.EXTRA_STREAM,
screenshotUri);
startActivity(Intent.createChooser(sharingIntent,
"Share image using"));
}
});
}
}
Following is the modified content of the xml res/layout/activity_main.xml.
In the below code abc indicates the logo of tutorialspoint.com

<?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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp"
android:text="Linkedin Share" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials Point"
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:textSize="35dp"
android:textColor="#ff16ff01" />

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true"
android:src="@drawable/logo"/>

424 | P a g e
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Share"
android:id="@+id/button"
android:layout_marginTop="61dp"
android:layout_below="@+id/imageView"
android:layout_centerHorizontal="true" />

</RelativeLayout>
Following is the content of AndroidManifest.xml file.
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name=".MainActivity"
android:label="@string/app_name" >

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

</activity>

</application>
</manifest>

Let's try to run your application. I assume you have connected your actual
Android Mobile device with your computer. To run the app from Android studio,
open one of your project's activity files and click Run icon from the toolbar.
Before starting your application, Android studio will display following window to
select an option where you want to run your Android application.

425 | P a g e
Select your mobile device as an option and then check your mobile device which
will display your default screen −

426 | P a g e
Now just tap on the image logo and you will see a list of share providers.

427 | P a g e
Now just select Linkedin from that list and then write any message. It is shown
in the image below −

428 | P a g e
Now it shows updating information

429 | P a g e
Android - Loading Spinner
You can show progress of a task in android through loading progress bar. The
progress bar comes in two shapes. Loading bar and Loading Spinner. In this
chapter we will discuss spinner.

Spinner is used to display progress of those tasks whose total time of


completion is unknown. In order to use that, you just need to define it in the xml
like this.

<ProgressBar

430 | P a g e
android:id="@+id/progressBar1"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true" />

After defining it in xml, you have to get its reference in java file through
ProgressBar class. Its syntax is given below −

private ProgressBar spinner;


spinner = (ProgressBar)findViewById(R.id.progressBar1);

After that you can make its disappear , and bring it back when needed through
setVisibility Method. Its syntax is given below −

spinner.setVisibility(View.GONE);
spinner.setVisibility(View.VISIBLE);

Apart from these Methods, there are other methods defined in the ProgressBar
class , that you can use to handle spinner more effectively.

Sr.N
Method & description
o

isIndeterminate()
1
Indicate whether this progress bar is in indeterminate mode

postInvalidate()
2
Cause an invalidate to happen on a subsequent cycle through the event loop

setIndeterminate(boolean indeterminate)
3
Change the indeterminate mode for this progress bar

invalidateDrawable(Drawable dr)
4
Invalidates the specified Drawable

incrementSecondaryProgressBy(int diff)
5
Increase the progress bar's secondary progress by the specified amount

getProgressDrawable()
6
Get the drawable used to draw the progress bar in progress mode

Example

431 | P a g e
Here is an example demonstrating the use of ProgressBar to handle spinner. It
creates a basic application that allows you to turn on the spinner on clicking the
button.

To experiment with this example , you can run this on an actual device or in an
emulator.

Ste
Description
ps

You will use Android studio to create an Android application under a package
1
com.example.sairamkrishna.myapplication.

2 Modify src/MainActivity.java file to add necessary code.

3 Modify the res/layout/activity_main to add respective XML components

Need to create a xml file in drawable folder.it contains shape and rotate
4
information about the progress bar

Run the application and choose a running android device and install the
5
application on it and verify the results

Following is the content of the modified main activity


file src/MainActivity.java.

package com.example.sairamkrishna.myapplication;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;

public class MainActivity extends Activity {


Button b1;

private ProgressBar spinner;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

b1=(Button)findViewById(R.id.button);
spinner=(ProgressBar)findViewById(R.id.progressBar);
spinner.setVisibility(View.GONE);

432 | P a g e
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
spinner.setVisibility(View.VISIBLE);
}
});
}
}

Following is the modified content of the xml res/layout/activity_main.xml.

In the following code abc indicates the logo of tutorialspoint.com


<?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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView android:text="Progress Dialog"


android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textview"
android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:id="@+id/textView"
android:layout_below="@+id/textview"
android:layout_centerHorizontal="true"
android:textColor="#ff7aff24"
android:textSize="35dp" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="download"
android:id="@+id/button"

433 | P a g e
android:layout_below="@+id/imageView"
android:layout_centerHorizontal="true" />

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true" />

<ProgressBar
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/progressBar"
android:progressDrawable="@drawable/circular_progress_bar"
android:layout_below="@+id/button"
android:layout_alignRight="@+id/textView"
android:layout_alignEnd="@+id/textView"
android:layout_alignLeft="@+id/textview"
android:layout_alignStart="@+id/textview"
android:layout_alignParentBottom="true" />

</RelativeLayout>

Following is the content of the res/drawable/circular_progress_bar.xml.

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


<rotate
xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="90"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="360">

<shape
android:innerRadiusRatio="3"
android:shape="ring"
android:thicknessRatio="7.0">

<gradient
android:centerColor="#007DD6"
android:endColor="#007DD6"
android:startColor="#007DD6"
android:angle="0"
android:type="sweep"
android:useLevel="false" />

434 | P a g e
</shape>

</rotate>

Following is the content of AndroidManifest.xml file.

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


<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity

android:name="com.example.sairamkrishna.myapplication.MainActivity"
android:label="@string/app_name" >

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

</activity>

</application>
</manifest>

Let's try to run our application we just modified. I assume you had created
your AVD while doing environment setup. To run the app from Android studio,
open one of your project's activity files and click Run icon from the toolbar.
Android studio installs the app on your AVD and starts it and if everything is fine
with your setup and application, it will display following Emulator window −

435 | P a g e
Now click on the load spinner button to turn on the loading spinner. It is shown
in the image below −

436 | P a g e
Android - Localization
An android application can run on many devices in many different regions. In
order to make your application more interactive, your application should handle
text,numbers,files e.t.c in ways appropriate to the locales where your
application will be used.

The way of changing string into different languages is called as localization

437 | P a g e
In this chapter we will explain , how you can localize your application according
to different regions e.t.c. We will localize the strings used in the application, and
in the same way other things can be localized.

Localizing Strings
In order to localize the strings used in your application , make a new folder
under res with name of values-local where local would be the replaced with
the region.
For example, in the case of italy, the values-it folder would be made under res.
It is shown in the image below −

Once that folder is made, copy the strings.xmlfrom default folder to the folder
you have created. And change its contents. For example, i have changed the
value of hello_world string.

Italy, res/values-it/strings.xml
<;?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello_world">Ciao mondo!</string>
</resources>

Spanish, res/values-it/strings.xml
<;?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello_world">Hola Mundo!</string>
</resources>

French, res/values-it/strings.xml
<;?xml version="1.0" encoding="utf-8"?>
<resources>

438 | P a g e
<string name="hello_world">Bonjour le monde !</string>
</resources>

Apart from these languages, the region code of other languages have been
given in the table below −

Sr.No Language & code

1 Afrikanns
Code: af. Folder name: values-af

2 Arabic
Code: ar. Folder name: values-ar

3 Bengali
Code: bn. Folder name: values-bn

4 Czech
Code: cs. Folder name: values-cs

5 Chinese
Code: zh. Folder name: values-zh

6 German
Code: de. Folder name: values-de

7 French
Code: fr. Folder name: values-fr

8 Japanese
Code: ja. Folder name: values-ja

Example
To experiment with this example , you can run this on an actual device or in an
emulator.

Ste
Description
ps

You will use Android studio to create an Android application under a package
1
com.example.sairamkrishna.myapplication.

439 | P a g e
2 Modify the res/layout/activity_main to add respective XML components

3 Modify the res/values/string.xml to add necessary string components

Run the application and choose a running android device and install the application
4
on it and verify the results

Following is the modified content of the xml res/layout/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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView android:text="Wifi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textview"
android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:id="@+id/textView"
android:layout_below="@+id/textview"
android:layout_centerHorizontal="true"
android:textColor="#ff7aff24"
android:textSize="35dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hindi"
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:textColor="#ff59ff1a"

440 | P a g e
android:textSize="30dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/marathi"
android:id="@+id/textView3"
android:textSize="30dp"
android:textColor="#ff67ff1e"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/arabic"
android:id="@+id/textView4"
android:layout_below="@+id/textView3"
android:layout_centerHorizontal="true"
android:layout_marginTop="42dp"
android:textColor="#ff40ff08"
android:textSize="30dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/chinese"
android:id="@+id/textView5"
android:layout_below="@+id/textView4"
android:layout_alignLeft="@+id/textView3"
android:layout_alignStart="@+id/textView3"
android:layout_marginTop="42dp"
android:textSize="30dp"
android:textColor="#ff56ff12"
android:layout_alignRight="@+id/textView3"
android:layout_alignEnd="@+id/textView3" />

</RelativeLayout>
Following is the content of the res/values/string.xml.
<resources>
<string name="app_name">My Application</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
<string name="hindi">ట్యుటోరియల్స్ పాయింట్</string>
<string name="marathi">शिकवण्या बिंदू</string>
<string name="arabic">7‫<نقطة الدروس‬/string>
<string name="chinese">教程点</string>
</resources>

441 | P a g e
Let's try to run our application we just modified. I assume you had created
your AVD while doing environment setup. To run the app from Android studio,
open one of your project's activity files and click Run icon from the toolbar.
Android studio installs the app on your AVD and starts it and if everything is fine
with your setup and application, it will display following Emulator window −

442 | P a g e
Android - Login Screen
A login application is the screen asking your credentials to login to some
particular application. You might have seen it when logging into facebook,twitter
e.t.c

This chapter explains, how to create a login screen and how to manage security
when false attempts are made.

First you have to define two TextView asking username and password of the
user. The password TextView must have inputType set to password. Its syntax
is given below −

<EditText
android:id = "@+id/editText2"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:inputType = "textPassword" />

<EditText
android:id = "@+id/editText1"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
/>

Define a button with login text and set its onClick Property. After that define
the function mentioned in the onClick property in the java file.

<Button
android:id = "@+id/button1"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:onClick = "login"
android:text = "@string/Login"
/>

In the java file, inside the method of onClick get the username and passwords
text using getText() and toString() method and match it with the text
using equals() function.

EditText username = (EditText)findViewById(R.id.editText1);


EditText password = (EditText)findViewById(R.id.editText2);

public void login(View view){

443 | P a g e
if(username.getText().toString().equals("admin") &&
password.getText().toString().equals("admin")){

//correcct password
}else{
//wrong password
}

The last thing you need to do is to provide a security mechanism, so that


unwanted attempts should be avoided. For this initialize a variable and on each
false attempt, decrement it. And when it reaches to 0, disable the login button.

int counter = 3;
counter--;

if(counter==0){
//disble the button, close the application e.t.c
}

Example
Here is an example demonstrating a login application. It creates a basic
application that gives you only three attempts to login to an application.

To experiment with this example, you can run this on an actual device or in an
emulator.

Ste
Description
ps

You will use Android studio to create an Android application under a package
1
com.example.sairamkrishna.myapplication.

3 Modify src/MainActivity.java file to add necessary code.

4 Modify the res/layout/activity_main to add respective XML components

Run the application and choose a running android device and install the
5
application on it and verify the results

Following is the content of the modified main activity


file src/MainActivity.java.

package com.example.sairamkrishna.myapplication;

444 | P a g e
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;

import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {


Button b1,b2;
EditText ed1,ed2;

TextView tx1;
int counter = 3;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

b1 = (Button)findViewById(R.id.button);
ed1 = (EditText)findViewById(R.id.editText);
ed2 = (EditText)findViewById(R.id.editText2);

b2 = (Button)findViewById(R.id.button2);
tx1 = (TextView)findViewById(R.id.textView3);
tx1.setVisibility(View.GONE);

b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(ed1.getText().toString().equals("admin") &&
ed2.getText().toString().equals("admin")) {
Toast.makeText(getApplicationContext(),
"Redirecting...",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "Wrong
Credentials",Toast.LENGTH_SHORT).show();

tx1.setVisibility(View.VISIBLE);
tx1.setBackgroundColor(Color.RED);
counter--;
tx1.setText(Integer.toString(counter));

if (counter == 0) {
b1.setEnabled(false);

445 | P a g e
}
}
}
});

b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
}

Following is the modified content of the xml res/layout/activity_main.xml.

In the following code abc indicates about logo of tutorialspoint.com


<?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" android:paddingLeft=
"@dimen/activity_horizontal_margin"
android:paddingRight = "@dimen/activity_horizontal_margin"
android:paddingTop = "@dimen/activity_vertical_margin"
android:paddingBottom = "@dimen/activity_vertical_margin"
tools:context = ".MainActivity">

<TextView android:text = "Login"


android:layout_width="wrap_content"
android:layout_height = "wrap_content"
android:id = "@+id/textview"
android:textSize = "35dp"
android:layout_alignParentTop = "true"
android:layout_centerHorizontal = "true" />

<TextView
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "Tutorials point"
android:id = "@+id/textView"
android:layout_below = "@+id/textview"
android:layout_centerHorizontal = "true"
android:textColor = "#ff7aff24"
android:textSize = "35dp" />

<EditText

446 | P a g e
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:id = "@+id/editText"
android:hint = "Enter Name"
android:focusable = "true"
android:textColorHighlight = "#ff7eff15"
android:textColorHint = "#ffff25e6"
android:layout_marginTop = "46dp"
android:layout_below = "@+id/imageView"
android:layout_alignParentLeft = "true"
android:layout_alignParentStart = "true"
android:layout_alignParentRight = "true"
android:layout_alignParentEnd = "true" />

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:id="@+id/editText2"
android:layout_below="@+id/editText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignRight="@+id/editText"
android:layout_alignEnd="@+id/editText"
android:textColorHint="#ffff299f"
android:hint="Password" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Attempts Left:"
android:id="@+id/textView2"
android:layout_below="@+id/editText2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textSize="25dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"

447 | P a g e
android:text="New Text"
android:id="@+id/textView3"
android:layout_alignTop="@+id/textView2"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignBottom="@+id/textView2"
android:layout_toEndOf="@+id/textview"
android:textSize="25dp"
android:layout_toRightOf="@+id/textview" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="login"
android:id="@+id/button"
android:layout_alignParentBottom="true"
android:layout_toLeftOf="@+id/textview"
android:layout_toStartOf="@+id/textview" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cancel"
android:id="@+id/button2"
android:layout_alignParentBottom="true"
android:layout_toRightOf="@+id/textview"
android:layout_toEndOf="@+id/textview" />

</RelativeLayout>

Following is the content of the res/values/string.xml.

<resources>
<string name="app_name">My Application</string>
</resources>

Following is the content of AndroidManifest.xml file.

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


<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

448 | P a g e
<activity
android:name=".MainActivity"
android:label="@string/app_name" >

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

</activity>

</application>
</manifest>

Let's try to run our application we just modified. I assume you had created
your AVD while doing environment setup. To run the app from Android studio,
open one of your project's activity files and click Run icon from the toolbar.
Android studio installs the app on your AVD and starts it and if everything is fine
with your setup and application, it will display following Emulator window −

449 | P a g e
Type anything in the username and password field, and then press the login
button. I put abc in the username field and abc in the password field. I got failed
attempt. This is shown below −

450 | P a g e
Do this two more time, and you will see that you have 0 login attempts left and
your login button is disabled.

Now open the application again, and this time enter correct username as admin
and password as admin and click on login. You will be successfully login.

451 | P a g e
If user press on cancel button, it will close an application of login screen.

452 | P a g e
Android - MediaPlayer
Android provides many ways to control playback of audio/video files and
streams. One of this way is through a class called MediaPlayer.

Android is providing MediaPlayer class to access built-in mediaplayer services


like playing audio,video e.t.c. In order to use MediaPlayer, we have to call a
static Method create() of this class. This method returns an instance of
MediaPlayer class. Its syntax is as follows −

MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.song);

The second parameter is the name of the song that you want to play. You have
to make a new folder under your project with name raw and place the music file
into it.

Once you have created the Mediaplayer object you can call some methods to
start or stop the music. These methods are listed below.

mediaPlayer.start();
mediaPlayer.pause();

On call to start() method, the music will start playing from the beginning. If this
method is called again after the pause() method, the music would start playing
from where it is left and not from the beginning.

In order to start music from the beginning, you have to call reset() method. Its
syntax is given below.

mediaPlayer.reset();

Apart from the start and pause method, there are other methods provided by
this class for better dealing with audio/video files. These methods are listed
below −

Sr.N
Method & description
o

isPlaying()
1
This method just returns true/false indicating the song is playing or not

seekTo(position)
2 This method takes an integer, and move song to that particular position
millisecond

453 | P a g e
getCurrentPosition()
3
This method returns the current position of song in milliseconds

getDuration()
4
This method returns the total time duration of song in milliseconds

reset()
5
This method resets the media player

release()
6
This method releases any resource attached with MediaPlayer object

setVolume(float leftVolume, float rightVolume)


7
This method sets the up down volume for this player

setDataSource(FileDescriptor fd)
8
This method sets the data source of audio/video file

selectTrack(int index)
9 This method takes an integer, and select the track from the list on that
particular index

getTrackInfo()
10
This method returns an array of track information

Example
Here is an example demonstrating the use of MediaPlayer class. It creates a
basic media player that allows you to forward, backward, play and pause a song.

To experiment with this example, you need to run this on an actual device to
hear the audio sound.

Ste
Description
ps

You will use Android studio IDE to create an Android application under a
1
package com.example.sairamkrishna.myapplication.

2 Modify src/MainActivity.java file to add MediaPlayer code.

3 Modify the res/layout/activity_main to add respective XML components

Create a new folder under MediaPlayer with name as raw and place an mp3
4
music file in it with name as song.mp3

454 | P a g e
Run the application and choose a running android device and install the
5
application on it and verify the results

Following is the content of the modified main activity


file src/MainActivity.java.

package com.example.sairamkrishna.myapplication;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;

import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import java.util.concurrent.TimeUnit;

public class MainActivity extends Activity {


private Button b1,b2,b3,b4;
private ImageView iv;
private MediaPlayer mediaPlayer;

private double startTime = 0;


private double finalTime = 0;

private Handler myHandler = new Handler();;


private int forwardTime = 5000;
private int backwardTime = 5000;
private SeekBar seekbar;
private TextView tx1,tx2,tx3;

public static int oneTimeOnly = 0;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

b1 = (Button) findViewById(R.id.button);
b2 = (Button) findViewById(R.id.button2);
b3 = (Button)findViewById(R.id.button3);
b4 = (Button)findViewById(R.id.button4);
iv = (ImageView)findViewById(R.id.imageView);

455 | P a g e
tx1 = (TextView)findViewById(R.id.textView2);
tx2 = (TextView)findViewById(R.id.textView3);
tx3 = (TextView)findViewById(R.id.textView4);
tx3.setText("Song.mp3");

mediaPlayer = MediaPlayer.create(this, R.raw.song);


seekbar = (SeekBar)findViewById(R.id.seekBar);
seekbar.setClickable(false);
b2.setEnabled(false);

b3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Playing
sound",Toast.LENGTH_SHORT).show();
mediaPlayer.start();

finalTime = mediaPlayer.getDuration();
startTime = mediaPlayer.getCurrentPosition();

if (oneTimeOnly == 0) {
seekbar.setMax((int) finalTime);
oneTimeOnly = 1;
}

tx2.setText(String.format("%d min, %d sec",


TimeUnit.MILLISECONDS.toMinutes((long) finalTime),
TimeUnit.MILLISECONDS.toSeconds((long) finalTime) -

TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long)
finalTime)))
);

tx1.setText(String.format("%d min, %d sec",


TimeUnit.MILLISECONDS.toMinutes((long) startTime),
TimeUnit.MILLISECONDS.toSeconds((long) startTime) -

TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long)
startTime)))
);

seekbar.setProgress((int)startTime);
myHandler.postDelayed(UpdateSongTime,100);
b2.setEnabled(true);
b3.setEnabled(false);
}
});

456 | P a g e
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Pausing
sound",Toast.LENGTH_SHORT).show();
mediaPlayer.pause();
b2.setEnabled(false);
b3.setEnabled(true);
}
});

b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int temp = (int)startTime;

if((temp+forwardTime)<=finalTime){
startTime = startTime + forwardTime;
mediaPlayer.seekTo((int) startTime);
Toast.makeText(getApplicationContext(),"You have
Jumped forward 5
seconds",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(),"Cannot jump
forward 5
seconds",Toast.LENGTH_SHORT).show();
}
}
});

b4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int temp = (int)startTime;

if((temp-backwardTime)>0){
startTime = startTime - backwardTime;
mediaPlayer.seekTo((int) startTime);
Toast.makeText(getApplicationContext(),"You have
Jumped backward 5
seconds",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(),"Cannot jump
backward 5
seconds",Toast.LENGTH_SHORT).show();
}
}
});
}

457 | P a g e
private Runnable UpdateSongTime = new Runnable() {
public void run() {
startTime = mediaPlayer.getCurrentPosition();
tx1.setText(String.format("%d min, %d sec",
TimeUnit.MILLISECONDS.toMinutes((long) startTime),
TimeUnit.MILLISECONDS.toSeconds((long) startTime) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.
toMinutes((long) startTime)))
);
seekbar.setProgress((int)startTime);
myHandler.postDelayed(this, 100);
}
};
}

Following is the modified content of the xml res/layout/activity_main.xml.

In the below code abcindicates the logo of tutorialspoint.com


<?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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView android:text="Music Palyer"


android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textview"
android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:id="@+id/textView"
android:layout_below="@+id/textview"
android:layout_centerHorizontal="true"
android:textColor="#ff7aff24"
android:textSize="35dp" />

458 | P a g e
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:src="@drawable/abc"/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/forward"
android:id="@+id/button"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/pause"
android:id="@+id/button2"
android:layout_alignParentBottom="true"
android:layout_alignLeft="@+id/imageView"
android:layout_alignStart="@+id/imageView" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/back"
android:id="@+id/button3"
android:layout_alignTop="@+id/button2"
android:layout_toRightOf="@+id/button2"
android:layout_toEndOf="@+id/button2" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/rewind"
android:id="@+id/button4"
android:layout_alignTop="@+id/button3"
android:layout_toRightOf="@+id/button3"
android:layout_toEndOf="@+id/button3" />

<SeekBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/seekBar"

459 | P a g e
android:layout_alignLeft="@+id/textview"
android:layout_alignStart="@+id/textview"
android:layout_alignRight="@+id/textview"
android:layout_alignEnd="@+id/textview"
android:layout_above="@+id/button" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="@+id/textView2"
android:layout_above="@+id/seekBar"
android:layout_toLeftOf="@+id/textView"
android:layout_toStartOf="@+id/textView" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="@+id/textView3"
android:layout_above="@+id/seekBar"
android:layout_alignRight="@+id/button4"
android:layout_alignEnd="@+id/button4" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="@+id/textView4"
android:layout_alignBaseline="@+id/textView2"
android:layout_alignBottom="@+id/textView2"
android:layout_centerHorizontal="true" />

</RelativeLayout>

Following is the content of the res/values/string.xml.

<resources>
<string name="app_name">My Application</string>
<string name="back"><![CDATA[<]]></string>
<string name="rewind"><![CDATA[<<]]></string>
<string name="forward"><![CDATA[>>]]></string>
<string name="pause">||</string>
</resources>

460 | P a g e
Following is the content of AndroidManifest.xml file.

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


<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity

android:name="com.example.sairamkrishna.myapplication.MainActivity"
android:label="@string/app_name" >

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

</activity>

</application>
</manifest>

Let's try to run your application. I assume you have connected your actual
Android Mobile device with your computer. To run the app from Eclipse, open
one of your project's activity files and click Run icon from the toolbar. Before
starting your application, Android studio will display following screens

461 | P a g e
By default you would see the pause button disabled. Now press play button and
it would become disable and pause button become enable. It is shown in the
picture below −

Up till now, the music has been playing. Now press the pause button and see
the pause notification. This is shown below −

462 | P a g e
Now when you press the play button again, the song will not play from the
beginning but from where it was paused. Now press the fast forward or
backward button to jump the song forward or backward 5 seconds. A time came
when the song cannot be jump forward. At this point , the notification would
appear which would be something like this −

463 | P a g e
Your music would remain playing in the background while you are doing other
tasks in your mobile. In order to stop it , you have to exit this application from
background activities.

464 | P a g e
Above image shows when you pick rewind button.

465 | P a g e
Android - Multitouch
Multi-touch gesture happens when more than one finger touches the screen at
the same time. Android allows us to detect these gestures.

Android system generates the following touch events whenever multiple fingers
touches the screen at the same time.

Sr.N
Event & description
o

ACTION_DOWN
1
For the first pointer that touches the screen. This starts the gesture.

ACTION_POINTER_DOWN
2
For extra pointers that enter the screen beyond the first.

ACTION_MOVE
3
A change has happened during a press gesture.

ACTION_POINTER_UP
4
Sent when a non-primary pointer goes up.

ACTION_UP
5
Sent when the last pointer leaves the screen.

So in order to detect any of the above mention event , you need to


override onTouchEvent() method and check these events manually. Its syntax
is given below −

public boolean onTouchEvent(MotionEvent ev){


final int actionPeformed = ev.getAction();

switch(actionPeformed){
case MotionEvent.ACTION_DOWN:{
break;
}

case MotionEvent.ACTION_MOVE:{
break;
}
return true;
}
}

466 | P a g e
In these cases, you can perform any calculation you like. For example zooming ,
shrinking e.t.c. In order to get the co-ordinates of the X and Y axis, you can
call getX() and getY() method. Its syntax is given below −

final float x = ev.getX();


final float y = ev.getY();

Apart from these methods, there are other methods provided by this
MotionEvent class for better dealing with multitouch. These methods are listed
below −

Sr.N
Method & description
o

getAction()
1
This method returns the kind of action being performed

getPressure()
2
This method returns the current pressure of this event for the first index

getRawX()
3
This method returns the original raw X coordinate of this event

getRawY()
4
This method returns the original raw Y coordinate of this event

getSize()
5
This method returns the size for the first pointer index

getSource()
6
This method gets the source of the event

getXPrecision()
7
This method return the precision of the X coordinates being reported

getYPrecision()
8
This method return the precision of the Y coordinates being reported

Example
Here is an example demonstrating the use of Multitouch. It creates a basic
Multitouch gesture application that allows you to view the co-ordinates when
multitouch is performed.

To experiment with this example , you need to run this on an actual device.

467 | P a g e
Ste
Description
ps

You will use android studio to create an Android application under a package
1
com.example.sairamkrishna.myapplication.

2 Modify src/MainActivity.java file to add multitouch code.

3 Modify the res/layout/activity_main to add respective XML components.

Run the application and choose a running android device and install the
4
application on it and verify the results.

Following is the content of the modified main activity


file src/MainActivity.java.

package com.example.sairamkrishna.myapplication;

import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {


float xAxis = 0f;
float yAxis = 0f;

float lastXAxis = 0f;


float lastYAxis = 0f;

EditText ed1, ed2, ed3, ed4;


TextView tv1;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

ed1 = (EditText) findViewById(R.id.editText);


ed2 = (EditText) findViewById(R.id.editText2);
ed3 = (EditText) findViewById(R.id.editText3);
ed4 = (EditText) findViewById(R.id.editText4);

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

468 | P a g e
tv1.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
final int actionPeformed = event.getAction();

switch(actionPeformed){
case MotionEvent.ACTION_DOWN:{
final float x = event.getX();
final float y = event.getY();

lastXAxis = x;
lastYAxis = y;

ed1.setText(Float.toString(lastXAxis));
ed2.setText(Float.toString(lastYAxis));
break;
}

case MotionEvent.ACTION_MOVE:{
final float x = event.getX();
final float y = event.getY();

final float dx = x - lastXAxis;


final float dy = y - lastYAxis;

xAxis += dx;
yAxis += dy;

ed3.setText(Float.toString(xAxis));
ed4.setText(Float.toString(yAxis));
break;
}
}
return true;
}
});
}
}

Following is the modified content of the xml res/layout/activity_main.xml.

In the below code abcindicates the logo of tutorialspoint.com


<?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"

469 | P a g e
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:transitionGroup="true">

<TextView android:text="Multitouch example"


android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textview"
android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:id="@+id/textView"
android:layout_below="@+id/textview"
android:layout_centerHorizontal="true"
android:textColor="#ff7aff24"
android:textSize="35dp" />

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:theme="@style/Base.TextAppearance.AppCompat" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_below="@+id/imageView"
android:layout_alignRight="@+id/textview"
android:layout_alignEnd="@+id/textview"
android:hint="X-Axis"
android:layout_alignLeft="@+id/textview"
android:layout_alignStart="@+id/textview"
android:textColorHint="#ff69ff0e" />

<EditText
android:layout_width="wrap_content"

470 | P a g e
android:layout_height="wrap_content"
android:id="@+id/editText2"
android:layout_below="@+id/editText"
android:layout_alignLeft="@+id/editText"
android:layout_alignStart="@+id/editText"
android:textColorHint="#ff21ff11"
android:hint="Y-Axis"
android:layout_alignRight="@+id/editText"
android:layout_alignEnd="@+id/editText" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText3"
android:layout_below="@+id/editText2"
android:layout_alignLeft="@+id/editText2"
android:layout_alignStart="@+id/editText2"
android:hint="Move X"
android:textColorHint="#ff33ff20"
android:layout_alignRight="@+id/editText2"
android:layout_alignEnd="@+id/editText2" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText4"
android:layout_below="@+id/editText3"
android:layout_alignLeft="@+id/editText3"
android:layout_alignStart="@+id/editText3"
android:textColorHint="#ff31ff07"
android:hint="Move Y"
android:layout_alignRight="@+id/editText3"
android:layout_alignEnd="@+id/editText3" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Touch here"
android:id="@+id/textView2"
android:layout_alignParentBottom="true"
android:layout_alignLeft="@+id/imageView"
android:layout_alignStart="@+id/imageView"
android:focusable="true"
android:typeface="sans"
android:clickable="true"
android:textColor="#ff5480ff"
android:textSize="35dp" />

</RelativeLayout>

471 | P a g e
Following is the content of the res/values/string.xml.

<resources>
<string name="app_name">My Application</string>
</resources>

Following is the content of AndroidManifest.xml file.

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


<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name=".MainActivity"
android:label="@string/app_name" >

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

</activity>

</application>
</manifest>

Let's try to run your application. I assume you have connected your actual
Android Mobile device with your computer. To run the app from android studio,
open one of your project's activity files and click Run icon from the toolbar.
Before starting your application, Android studio will display following window to
select an option where you want to run your Android application.

472 | P a g e
Select your mobile device as an option and then check your mobile device which
will display your default screen −

473 | P a g e
By default you will see nothing in any field. Now just tap on the Touch here area
and see some data in the fields. It is shown below −

474 | P a g e
You will see that the data in the Move field is 0, because only a single touch
gesture has been performed. Now tap on the screen and start dragging your
finger. You will see the change in the data of the move field. It is shown below −

475 | P a g e
476 | P a g e
Android - Navigation
In this chapter, we will see that how you can provide navigation forward and
backward between an application. We will first look at how to provide up
navigation in an application.

Providing Up Navigation
The up navigation will allow our application to move to previous activity from
the next activity. It can be done like this.

To implement Up navigation, the first step is to declare which activity is the


appropriate parent for each activity. You can do it by
specifying parentActivityName attribute in an activity. Its syntax is given
below −

android:parentActivityName = "com.example.test.MainActivity"

After that you need to call setDisplayHomeAsUpEnabled method


of getActionBar() in the onCreate method of the activity. This will enable the
back button in the top action bar.

getActionBar().setDisplayHomeAsUpEnabled(true);

The last thing you need to do is to override onOptionsItemSelected method.


when the user presses it, your activity receives a call to
onOptionsItemSelected(). The ID for the action is android.R.id.home.Its syntax
is given below −

public boolean onOptionsItemSelected(MenuItem item) {

switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
}

Handling device back button


Since you have enabled your back button to navigate within your application,
you might want to put the application close function in the device back button.

It can be done by overriding onBackPressed and then


calling moveTaskToBack and finish method. Its syntax is given below −
477 | P a g e
@Override
public void onBackPressed() {
moveTaskToBack(true);
MainActivity2.this.finish();
}

Apart from this setDisplayHomeAsUpEnabled method, there are other methods


available in ActionBar API class. They are listed below −

Sr.N
Method & description
o

addTab(ActionBar.Tab tab, boolean setSelected)


1
This method adds a tab for use in tabbed navigation mode

getSelectedTab()
2 This method returns the currently selected tab if in tabbed navigation mode and
there is at least one tab present

hide()
3
This method hide the ActionBar if it is currently showing

removeAllTabs()
4
This method remove all tabs from the action bar and deselect the current tab

selectTab(ActionBar.Tab tab)
5
This method select the specified tab

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

Example
The below example demonstrates the use of Navigation. It crates a basic
application that allows you to navigate within your application.

To experiment with this example, you need to run this on an actual device or in
an emulator.

Ste
Description
ps

You will use Android studio to create an Android application under a package
1
com.example.sairamkrishna.myapplication.

478 | P a g e
2 Modify src/MainActivity.java file to add Activity code.

Create a new activity with the name of second_main.java and edit it to add
3
activity code.

Modify layout XML file res/layout/activity_main.xml add any GUI component


4
if required.

Modify layout XML file res/layout/second.xml add any GUI component if


5
required.

6 Modify AndroidManifest.xml to add necessary code.

Run the application and choose a running android device and install the
7
application on it and verify the results.

Here is the content of src/MainActivity.java.

package com.example.sairamkrishna.myapplication;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {


Button b1;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

b1 = (Button) findViewById(R.id.button);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent in=new
Intent(MainActivity.this,second_main.class);
startActivity(in);
}
});
}
}

Here is the content of src/second_main.java.

479 | P a g e
package com.example.sairamkrishna.myapplication;

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;

/**
* Created by Sairamkrishna on 4/6/2015.
*/

public class second_main extends Activity {


WebView wv;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity2);

wv = (WebView) findViewById(R.id.webView);
wv.setWebViewClient(new MyBrowser());
wv.getSettings().setLoadsImagesAutomatically(true);
wv.getSettings().setJavaScriptEnabled(true);
wv.loadUrl("https://www.tutorialspoint.com");
}

private class MyBrowser extends WebViewClient {


@Override
public boolean shouldOverrideUrlLoading(WebView view, String
url) {
view.loadUrl(url);
return true;
}
}
}

Here is the content of activity_main.xml.

In the below code abcindicates the logo of tutorialspoint.com


<?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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"

480 | P a g e
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:transitionGroup="true">

<TextView android:text="Navigation example"


android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textview"
android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:id="@+id/textView"
android:layout_below="@+id/textview"
android:layout_centerHorizontal="true"
android:textColor="#ff7aff24"
android:textSize="35dp" />

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:theme="@style/Base.TextAppearance.AppCompat" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="first page"
android:id="@+id/button"
android:layout_below="@+id/imageView"
android:layout_alignRight="@+id/textView"
android:layout_alignEnd="@+id/textView"
android:layout_marginTop="61dp"
android:layout_alignLeft="@+id/imageView"
android:layout_alignStart="@+id/imageView" />

</RelativeLayout>

Here is the content of activity_main_activity2.xml.

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

481 | P a g e
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1">

<WebView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/webView"
android:layout_gravity="center_horizontal"
android:layout_weight="1.03" />

</LinearLayout>

Here is the content of Strings.xml.

<resources>
<string name="app_name">My Application</string>
</resources>

Here is the content of AndroidManifest.xml.

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


<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >
<uses-permission
android:name="android.permission.INTERNET"></uses-permission>

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name=".MainActivity"
android:label="@string/app_name" >

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

</activity>

482 | P a g e
<activity android:name=".second_main"></activity>

</application>
</manifest>

Let's try to run your application. I assume you had created your AVD while
doing environment setup. To run the app from Android studio, open one of your
project's activity files and click Run icon from the toolbar. Android studio
installs the app on your AVD and starts it and if everything is fine with your
setup and application, it will display following Emulator window−

Now just press on button and the following screen will be shown to you.

483 | P a g e
Second activity contains webview, it has redirected to tutorialspoint.com as
shown below

484 | P a g e
Android - Network Connection
Android lets your application connect to the internet or any other local network
and allows you to perform network operations.

A device can have various types of network connections. This chapter focuses
on using either a Wi-Fi or a mobile network connection.

485 | P a g e
Checking Network Connection
Before you perform any network operations, you must first check that are you
connected to that network or internet e.t.c. For this android
provides ConnectivityManager class. You need to instantiate an object of this
class by calling getSystemService() method. Its syntax is given below −

ConnectivityManager check = (ConnectivityManager)


this.context.getSystemService(Context.CONNECTIVITY_SERVICE);

Once you instantiate the object of ConnectivityManager class, you can


use getAllNetworkInfo method to get the information of all the networks. This
method returns an array of NetworkInfo. So you have to receive it like this.

NetworkInfo[] info = check.getAllNetworkInfo();

The last thing you need to do is to check Connected State of the network. Its
syntax is given below −

for (int i = 0; i<info.length; i++){


if (info[i].getState() == NetworkInfo.State.CONNECTED){
Toast.makeText(context, "Internet is connected
Toast.LENGTH_SHORT).show();
}
}

Apart from this connected states, there are other states a network can achieve.
They are listed below −

Sr.No State

1 Connecting

2 Disconnected

3 Disconnecting

4 Suspended

5 Unknown

Performing Network Operations

486 | P a g e
After checking that you are connected to the internet, you can perform any
network operation. Here we are fetching the html of a website from a url.

Android provides HttpURLConnection and URL class to handle these


operations. You need to instantiate an object of URL class by providing the link
of website. Its syntax is as follows −

String link = "http://www.google.com";


URL url = new URL(link);

After that you need to call openConnection method of url class and receive it
in a HttpURLConnection object. After that you need to call the connect method
of HttpURLConnection class.

HttpURLConnection conn = (HttpURLConnection) url.openConnection();


conn.connect();

And the last thing you need to do is to fetch the HTML from the website. For this
you will use InputStream and BufferedReader class. Its syntax is given below

InputStream is = conn.getInputStream();
BufferedReader reader = new BufferedReader(new
InputStreamReader(is, "UTF-8"));
String webPage = "",data="";

while ((data = reader.readLine()) != null){


webPage += data + "\n";
}

Apart from this connect method, there are other methods available in
HttpURLConnection class. They are listed below −

Sr.N
Method & description
o

disconnect()
1 This method releases this connection so that its resources may be either reused
or closed

getRequestMethod()
2 This method returns the request method which will be used to make the request
to the remote HTTP server

getResponseCode()
3
This method returns response code returned by the remote HTTP server

487 | P a g e
setRequestMethod(String method)
4 This method Sets the request command which will be sent to the remote HTTP
server

usingProxy()
5
This method returns whether this connection uses a proxy server or not

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

Example
The below example demonstrates the use of HttpURLConnection class. It creates
a basic application that allows you to download HTML from a given web page.

To experiment with this example, you need to run this on an actual device on
which wifi internet is connected .

Ste
Description
ps

You will use Android studio IDE to create an Android application under a
1
package com.tutorialspoint.myapplication.

2 Modify src/MainActivity.java file to add Activity code.

Modify layout XML file res/layout/activity_main.xml add any GUI component


4
if required.

6 Modify AndroidManifest.xml to add necessary permissions.

Run the application and choose a running android device and install the
7
application on it and verify the results.

Here is the content of src/MainActivity.java.

package com.tutorialspoint.myapplication;

import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import android.net.ConnectivityManager;
import android.os.Bundle;

488 | P a g e
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.view.View;

import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;

import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class MainActivity extends ActionBarActivity {


private ProgressDialog progressDialog;
private Bitmap bitmap = null;
Button b1;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.button);

b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
checkInternetConenction();

downloadImage("https://www.tutorialspoint.com/green/images/logo.png
");
}
});
}

private void downloadImage(String urlStr) {


progressDialog = ProgressDialog.show(this, "", "Downloading
Image from " + urlStr);
final String url = urlStr;

new Thread() {
public void run() {
InputStream in = null;

Message msg = Message.obtain();

489 | P a g e
msg.what = 1;

try {
in = openHttpConnection(url);
bitmap = BitmapFactory.decodeStream(in);
Bundle b = new Bundle();
b.putParcelable("bitmap", bitmap);
msg.setData(b);
in.close();
}catch (IOException e1) {
e1.printStackTrace();
}
messageHandler.sendMessage(msg);
}
}.start();
}

private InputStream openHttpConnection(String urlStr) {


InputStream in = null;
int resCode = -1;

try {
URL url = new URL(urlStr);
URLConnection urlConn = url.openConnection();

if (!(urlConn instanceof HttpURLConnection)) {


throw new IOException("URL is not an Http URL");
}

HttpURLConnection httpConn = (HttpURLConnection) urlConn;


httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
resCode = httpConn.getResponseCode();

if (resCode == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
}catch (MalformedURLException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
return in;
}

private Handler messageHandler = new Handler() {


public void handleMessage(Message msg) {

490 | P a g e
super.handleMessage(msg);
ImageView img = (ImageView) findViewById(R.id.imageView);
img.setImageBitmap((Bitmap)
(msg.getData().getParcelable("bitmap")));
progressDialog.dismiss();
}
};

private boolean checkInternetConenction() {


// get Connectivity Manager object to check connection
ConnectivityManager connec

=(ConnectivityManager)getSystemService(getBaseContext().CONNECTIVIT
Y_SERVICE);

// Check for network connections


if ( connec.getNetworkInfo(0).getState() ==
android.net.NetworkInfo.State.CONNECTED ||
connec.getNetworkInfo(0).getState() ==
android.net.NetworkInfo.State.CONNECTING ||
connec.getNetworkInfo(1).getState() ==
android.net.NetworkInfo.State.CONNECTING ||
connec.getNetworkInfo(1).getState() ==
android.net.NetworkInfo.State.CONNECTED ) {
Toast.makeText(this, " Connected ",
Toast.LENGTH_LONG).show();
return true;
}else if (
connec.getNetworkInfo(0).getState() ==
android.net.NetworkInfo.State.DISCONNECTED ||
connec.getNetworkInfo(1).getState() ==
android.net.NetworkInfo.State.DISCONNECTED ) {
Toast.makeText(this, " Not Connected ",
Toast.LENGTH_LONG).show();
return false;
}
return false;
}

Here is the content of 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"

491 | P a g e
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="UI Animator Viewer"
android:id="@+id/textView"
android:textSize="25sp"
android:layout_centerHorizontal="true" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_alignRight="@+id/textView"
android:layout_alignEnd="@+id/textView"
android:textColor="#ff36ff15"
android:textIsSelectable="false"
android:textSize="35dp" />

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:id="@+id/button"
android:layout_below="@+id/imageView"
android:layout_centerHorizontal="true"
android:layout_marginTop="76dp" />

</RelativeLayout>

Here is the content of Strings.xml.

<resources>

492 | P a g e
<string name="app_name">My Application</string>
</resources>

Here is the content of AndroidManifest.xml

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


<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tutorialspoint.myapplication" >
<uses-permission
android:name="android.permission.INTERNET"></uses-permission>
<uses-permission
android:name="android.permission.ACCESS_NETWORK_STATE"></uses-
permission>

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name=".MainActivity"
android:label="@string/app_name" >

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

</activity>

</application>
</manifest>

Let's try to run your application. I assume you have connected your actual
Android Mobile device with your computer. To run the app from android studio,
open one of your project's activity files and click Run icon from the tool bar.
Before starting your application, Android studio will display following window to
select an option where you want to run your Android application.

493 | P a g e
Select your mobile device as an option and then check your mobile device which
will display following screen −

494 | P a g e
Now just click on button, It will check internet connection as well as it will
download image.

495 | P a g e
Out would be as follows and it has fetch the logo from internet.

496 | P a g e
Android - NFC Guide
NFC stands for Near Field Communication, and as the name implies it
provides a wireless communication mechanism between two compatible
devices. NFC is a short range wireless technology having a range of 4cm or less
for two devices to share data.

How It Works

497 | P a g e
Like Bluetooth and WiFi, and all manner of other wireless signals, NFC works on
the principle of sending information over radio waves. Through NFC data is send
through electromagnetic induction between two devices.

NFC works on the bases of tags , it allows you to share some amount of data
between an NFC tag and an android powered device or between two android
powered devices. Tags have various set of complexities. The Data stored in the
tag can be written in a variety of formats, but android APIs are based around a
NFC standard called as NFC Data Exchange Format(NDEF)..

The transmission frequency for data across NFC is 13.56 megahertz, and data
can be sent at either 106, 212 or 424 kilobits per second, which is quick enough
for a range of data transfers from contact details to swapping pictures, songs
and videos.

Android powered devices with NFC supports following three main modes of
operations −

Three Modes of Operation


 Reader/Writer Mode − It allows the NFC device to read or write passive NFC
tags.
 P2P mode − This mode allows NFC device to exchange data with other NFC
peers.
 Card emulation mode − It allows the NFC device itself to act as an NFC card,
so it can be accessed by an external NFC reader.

How it works with Android


To get the permission to access NFC Hardware, add the following permission in
your Android.Manifest file.

<uses-sdk android:minSdkVersion="10"/>
First thing to note is that not all android powered devices provide NFC
technology. So to make sure that your application shows up in google play for
only those devices that have NFC Hardware, add the following line in
your Android.Manifest file.
<uses-feature android:name="android.hardware.nfc"
android:required="true"/>

Android provides a android.nfc package for communicating with another device.


This package contains following classes −

Sr.N
Classes & Description
o

498 | P a g e
1 NdefMessage
It represents an immutable NDEF Message.

2 NdefRecord
It represents an immutable NDEF Record.

3 NfcAdapter
It represents the local NFC adapter.

4 NfcEvent
It wraps information associated with any NFC event.

5 NfcManager
It is a high level manager used to obtain an instance of an NfcAdapter.

6 Tag
It represents an NFC tag that has been discovered.

NFC tags system works in android with the help of some intent filters that are
listed below:

Sr.N
Filters & Features
o

1 ACTION_NDEF_DISCOVERED
This intent is used to start an Activity when a tag contains an NDEF payload.

ACTION_TECH_DISCOVERED
2 This intent is used to start an activity if the tag does not contain NDEF data, but
is of known technology.

ACTION_TAG_DISCOVERED
3 This intent is started if no activities handle the
ACTION_NDEF_DISCOVERED or ACTION_TECH_DISCOVERED intents.

To code an application that uses NFC technology is complex so don't use it in


your app unless necessary. The use of NFC is not common in devices but it is
getting popular. Let's see what is the future of this technology −

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

499 | P a g e
Future Applications
With this technology growing day by day and due to introduction of contact less
payment systems this technology is getting a boom. A service known as Google
Wallet is already introduced in the US which purpose is to make our
smartphones a viable alternative to credit and transport cards.

Android - PHP/MYSQL
In this chapter , we are going to explain, how you can integrate PHP and MYSQL
with your android application. This is very useful in case you have a webserver,
and you want to access its data on your android application.

MYSQL is used as a database at the webserver and PHP is used to fetch data
from the database. Our application will communicate with the PHP page with
necessary parameters and PHP will contact MYSQL database and will fetch the
result and return the results to us.

PHP - MYSQL

Creating Database
MYSQL database can be created easily using this simple script. The CREATE
DATABASE statement creates the database.
<?php
$con=mysqli_connect("example.com","username","password");
$sql="CREATE DATABASE my_db";
if (mysqli_query($con,$sql)) {
echo "Database my_db created successfully";
}
?>

Creating Tables
Once database is created, its time to create some tables in the database.
The CREATE TABLE statement creates the database.
<?php

$con=mysqli_connect("example.com","username","password","my_db");
$sql="CREATE TABLE table1(Username CHAR(30),Password
CHAR(30),Role CHAR(30))";
if (mysqli_query($con,$sql)) {
echo "Table have been created successfully";
}
?>

500 | P a g e
Inserting Values in tables
When the database and tables are created. Now its time to insert some data
into the tables. The Insert Into statement creates the database.
<?php

$con=mysqli_connect("example.com","username","password","my_db");
$sql="INSERT INTO table1 (FirstName, LastName, Age) VALUES
('admin', 'admin','adminstrator')";
if (mysqli_query($con,$sql)) {
echo "Values have been inserted successfully";
}
?>

PHP - GET and POST methods


PHP is also used to fetch the record from the mysql database once it is created.
In order to fetch record some information must be passed to PHP page regarding
what record to be fetched.

The first method to pass information is through GET method in


which $_GET command is used. The variables are passed in the url and the
record is fetched. Its syntax is given below −
<?php

$con=mysqli_connect("example.com","username","password","database
name");

if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$username = $_GET['username'];
$password = $_GET['password'];
$result = mysqli_query($con,"SELECT Role FROM table1 where
Username='$username'
and Password='$password'");
$row = mysqli_fetch_array($result);
$data = $row[0];

if($data){
echo $data;
}
mysqli_close($con);
?>
The second method is to use POST method. The only change in the above script
is to replace $_GET with $_POST. In Post method, the variables are not passed
through URL.

501 | P a g e
Android - Connecting MYSQL

Connecting Via Get Method


There are two ways to connect to MYSQL via PHP page. The first one is
called Get method. We will use HttpGet and HttpClient class to connect.
Their syntax is given below −
URL url = new URL(link);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(link));
After that you need to call execute method of HttpClient class and receive it in
a HttpResponse object. After that you need to open streams to receive the data.
HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));

Connecting Via Post Method


In the Post method, the URLEncoder,URLConnection class will be used. The
urlencoder will encode the information of the passing variables. It's syntax is
given below −
URL url = new URL(link);
String data = URLEncoder.encode("username", "UTF-8")
+ "=" + URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8")
+ "=" + URLEncoder.encode(password, "UTF-8");
URLConnection conn = url.openConnection();

The last thing you need to do is to write this data to the link. After writing, you
need to open stream to receive the responded data.

OutputStreamWriter wr = new
OutputStreamWriter(conn.getOutputStream());
wr.write( data );
BufferedReader reader = new BufferedReader(new
InputStreamReader(conn.getInputStream()));

Learn MySQL in-depth with real-world projects through our MySQL


certification course. Enroll and become a certified expert to boost your
career.

Example

502 | P a g e
The below example is a complete example of connecting your android
application with MYSQL database via PHP page. It creates a basic application
that allows you to login using GET and POST method.

PHP - MYSQL part


In this example a database with the name of temp has been created at
000webhost.com. In that database, a table has been created with the name of
table1. This table has three fields. (Username, Password, Role). The table has
only one record which is ("admin","admin","administrator").

The php page has been given below which takes parameters by post method.

<?php

$con=mysqli_connect("mysql10.000webhost.com","username","password",
"db_name");

if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$username = $_POST['username'];
$password = $_POST['password'];
$result = mysqli_query($con,"SELECT Role FROM table1 where
Username='$username' and Password='$password'");
$row = mysqli_fetch_array($result);
$data = $row[0];

if($data){
echo $data;
}

mysqli_close($con);
?>

Android Part
To experiment with this example , you need to run this on an actual device on
which wifi internet is connected.

Ste
Description
ps

1 You will use Android studio IDE to create an Android application and name it as

503 | P a g e
PHPMYSQL under a package com.example.phpmysql.

2 Modify src/MainActivity.java file to add Activity code.

3 Create src/SiginActivity.java file to add PHPMYSQL code.

Modify layout XML file res/layout/activity_main.xml add any GUI component if


4
required.

5 Modify res/values/string.xml file and add necessary string components.

6 Modify AndroidManifest.xml to add necessary permissions.

Run the application and choose a running android device and install the application
7
on it and verify the results.

Here is the content of src/com.example.phpmysql/MainActivity.java.


package com.example.phpmysql;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

private EditText usernameField,passwordField;


private TextView status,role,method;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

usernameField = (EditText)findViewById(R.id.editText1);
passwordField = (EditText)findViewById(R.id.editText2);

status = (TextView)findViewById(R.id.textView6);
role = (TextView)findViewById(R.id.textView7);
method = (TextView)findViewById(R.id.textView9);
}

504 | P a g e
public void login(View view){
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
method.setText("Get Method");
new
SigninActivity(this,status,role,0).execute(username,password);

public void loginPost(View view){


String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
method.setText("Post Method");
new
SigninActivity(this,status,role,1).execute(username,password);
}
}
Here is the content of src/com.example.phpmysql/SigninActivity.java.
package com.example.phpmysql;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.os.AsyncTask;
import android.widget.TextView;

public class SigninActivity extends AsyncTask{


private TextView statusField,roleField;
private Context context;
private int byGetOrPost = 0;

//flag 0 means get and 1 means post.(By default it is get.)


public SigninActivity(Context context,TextView
statusField,TextView roleField,int flag) {
this.context = context;
this.statusField = statusField;

505 | P a g e
this.roleField = roleField;
byGetOrPost = flag;
}

protected void onPreExecute(){


}

@Override
protected String doInBackground(String... arg0) {
if(byGetOrPost == 0){ //means by Get Method

try{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link =
"http://myphpmysqlweb.hostei.com/login.php?username="+username+"&
password="+password;

URL url = new URL(link);


HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(link));
HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader(new

InputStreamReader(response.getEntity().getContent()));

StringBuffer sb = new StringBuffer("");


String line="";

while ((line = in.readLine()) != null) {


sb.append(line);
break;
}

in.close();
return sb.toString();
} catch(Exception e){
return new String("Exception: " + e.getMessage());
}
} else{
try{
String username = (String)arg0[0];
String password = (String)arg0[1];

String
link="http://myphpmysqlweb.hostei.com/loginpost.php";
String data = URLEncoder.encode("username", "UTF-8") +
"=" +

506 | P a g e
URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8") +
"=" +
URLEncoder.encode(password, "UTF-8");

URL url = new URL(link);


URLConnection conn = url.openConnection();

conn.setDoOutput(true);
OutputStreamWriter wr = new
OutputStreamWriter(conn.getOutputStream());

wr.write( data );
wr.flush();

BufferedReader reader = new BufferedReader(new


InputStreamReader(conn.getInputStream()));

StringBuilder sb = new StringBuilder();


String line = null;

// Read Server Response


while((line = reader.readLine()) != null) {
sb.append(line);
break;
}

return sb.toString();
} catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
}

@Override
protected void onPostExecute(String result){
this.statusField.setText("Login Successful");
this.roleField.setText(result);
}
}
Add the following content to build.gradle and rebuild the whole project.
android {
useLibrary 'org.apache.http.legacy'
}
Here is the content of activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"

507 | P a g e
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/editText1"
android:layout_below="@+id/editText1"
android:layout_marginTop="25dp"
android:ems="10"
android:inputType="textPassword" >
</EditText>

<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="44dp"
android:ems="10" >

<requestFocus android:layout_width="wrap_content" />

</EditText>

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/editText1"
android:layout_alignParentLeft="true"
android:text="@string/Username" />

<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="@string/App"
android:textAppearance="?android:attr/textAppearanceLarge" />

508 | P a g e
<TextView
android:id="@+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/textView5"
android:layout_alignLeft="@+id/textView6"
android:text="@string/Role"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="10sp" />

<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView6"
android:layout_marginTop="27dp"
android:layout_toLeftOf="@+id/editText1"
android:text="@string/LoginRole" />
<TextView
android:id="@+id/textView8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/textView6"
android:layout_alignLeft="@+id/textView5"
android:layout_marginBottom="27dp"
android:text="@string/method" />

<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView8"
android:layout_below="@+id/button1"
android:layout_marginTop="86dp"
android:text="@string/LoginStatus" />

<TextView
android:id="@+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/textView4"
android:layout_centerHorizontal="true"
android:text="@string/Status"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="10sp" />

<TextView

509 | P a g e
android:id="@+id/textView9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/textView8"
android:layout_alignLeft="@+id/textView6"
android:text="@string/Choose"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="10sp" />

<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="@+id/textView6"
android:onClick="loginPost"
android:text="@string/LoginPost" />

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/button2"
android:layout_alignBottom="@+id/button2"
android:layout_alignLeft="@+id/textView2"
android:onClick="login"
android:text="@string/LoginGet" />

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editText2"
android:layout_alignBottom="@+id/editText2"
android:layout_alignParentLeft="true"
android:text="@string/Password" />

</RelativeLayout>
Here is the content of Strings.xml.
<?xml version="1.0" encoding="utf-8"?>
<resources>

<string name="app_name">PHPMYSQL</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="Username">Username</string>
<string name="Password">Password</string>
<string name="LoginGet">Login - Get</string>

510 | P a g e
<string name="LoginPost">Login - Post</string>
<string name="App">Login Application</string>
<string name="LoginStatus">Login Status</string>
<string name="LoginRole">Login Role</string>
<string name="Status">Not login</string>
<string name="Role">Not assigned</string>
<string name="method">Login Method</string>
<string name="Choose">Choose Method</string>

</resources>
Here is the content of AndroidManifest.xml.
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.phpmysql" >

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission
android:name="android.permission.ACCESS_NETWORK_STATE" />

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name="com.example.phpmysql.MainActivity"
android:label="@string/app_name" >

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

</activity>

</application>
</manifest>

Let's try to run your PHPMYSQL application. I assume you have connected your
actual Android Mobile device with your computer. To run the app from Android
studio, open one of your project's activity files and click Run icon from the tool
bar. Before starting your application, Android studio will display following
window to select an option where you want to run your Android application.

511 | P a g e
Select your mobile device as an option and then check your mobile device which
will display following screen −

512 | P a g e
Now just type in your username and password. In my case i am typing admin as
username and password. It is shown in the figure −

513 | P a g e
Now press the Get button and wait a few seconds and response will be
downloaded and will be shown to you. In this case, the response is the ROLE
that is fetched in case of admin as username and password.It is shown in the
figure below −

514 | P a g e
Now again press the POST button and same result would appear. It is shown in
the figure below −

515 | P a g e
Android - Progress Circle
The easiest way to make a progress circle is using through a class called
ProgressDialog. The loading bar can also be made through that class. The only
logical difference between bar and circle is , that the former is used when you
know the total time for waiting for a particular task whereas the later is used
when you don't know the waiting time.

In order to this , you need to instantiate an object of this class. Its syntax is.

ProgressDialog progress = new ProgressDialog(this);

Now you can set some properties of this dialog. Such as, its style,its text e.t.c

516 | P a g e
progress.setMessage("Downloading Music :) ");
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setIndeterminate(true);

Apart from these methods, there are other methods that are provided by the
ProgressDialog class.

Sr.N
Classes & Description
o

getMax()
1
This methods returns the maximum value of the progress

incrementProgressBy(int diff)
2 This method increment the progress bar by the difference of value passed as a
parameter

setIndeterminate(boolean indeterminate)
3
This method set the progress indicator as determinate or indeterminate

setMax(int max)
4
This method set the maximum value of the progress dialog

setProgress(int value)
5
This method is used to update the progress dialog with some specific value

show(Context context, CharSequence title,


6 CharSequence message)
This is a static method, used to display progress dialog

Example
This example demonstrates the spinning use of the progress dialog. It display a
spinning progress dialog on pressing the button.

To experiment with this example, you need to run this on an actual device on
after developing the application according to the steps below.

Ste
Description
ps

You will use Android Studio to create an Android application under a package
1
com.example.sairamkrishna.myapplication.

517 | P a g e
Modify src/MainActivity.java file to add progress code to display the spinning
2
progress dialog.

3 Modify res/layout/activity_main.xml file to add respective XML code.

Run the application and choose a running android device and install the
4
application on it and verify the results.

Following is the content of the modified main activity


file src/MainActivity.java.

package com.example.sairamkrishna.myapplication;

import android.app.ProgressDialog;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {


Button b1;
private ProgressDialog progressBar;
private int progressBarStatus = 0;
private Handler progressBarbHandler = new Handler();
private long fileSize = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button);

b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
progressBar = new ProgressDialog(v.getContext());
progressBar.setCancelable(true);
progressBar.setMessage("File downloading ...");

progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressBar.setProgress(0);
progressBar.setMax(100);
progressBar.show();
progressBarStatus = 0;

fileSize = 0;

518 | P a g e
new Thread(new Runnable() {
public void run() {
while (progressBarStatus < 100) {
progressBarStatus = downloadFile();

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}

progressBarbHandler.post(new Runnable() {
public void run() {

progressBar.setProgress(progressBarStatus);
}
});
}

if (progressBarStatus >= 100) {


try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
progressBar.dismiss();
}
}
}).start();
}
});
}

public int downloadFile() {


while (fileSize <= 1000000) {
fileSize++;

if (fileSize == 100000) {
return 10;
}else if (fileSize == 200000) {
return 20;
}else if (fileSize == 300000) {
return 30;
}else if (fileSize == 400000) {
return 40;
}else if (fileSize == 500000) {
return 50;
}else if (fileSize == 700000) {
return 70;

519 | P a g e
}else if (fileSize == 800000) {
return 80;
}
}
return 100;
}
}

Modify the content of res/layout/activity_main.xml to the following

In the following code abc indicates the logo of tutorialspoint.com


<?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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView android:text="Music Palyer"


android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textview"
android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:id="@+id/textView"
android:layout_below="@+id/textview"
android:layout_centerHorizontal="true"
android:textColor="#ff7aff24"
android:textSize="35dp" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="download"
android:id="@+id/button"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"

520 | P a g e
android:layout_marginBottom="112dp" />

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true" />

</RelativeLayout>

Modify the res/values/string.xml to the following

<resources>
<string name="app_name">My Application</string>
</resources>

This is the default AndroidManifest.xml

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


<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity

android:name="com.example.sairamkrishna.myapplication.MainActivity"
android:label="@string/app_name" >

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

</application>
</manifest>

521 | P a g e
Let's try to run your application. To run the app from android studio, open one of
your project's activity files and click Run icon from the toolbar. Before starting
your application, Android studio will display following window to select an option
where you want to run your Android application.

Just press the button to start the Progress Dialog. After pressing , following
screen would appear.

522 | P a g e
523 | P a g e
Android Progress Bar using ProgressDialog
Progress bars are used to show progress of a task. For example, when you are
uploading or downloading something from the internet, it is better to show the
progress of download/upload to the user.

In android there is a class called ProgressDialog that allows you to create


progress bar. In order to do this, you need to instantiate an object of this class.
Its syntax is.

ProgressDialog progress = new ProgressDialog(this);

Now you can set some properties of this dialog. Such as, its style, its text etc.

progress.setMessage("Downloading Music :) ");


progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progress.setIndeterminate(true);

Apart from these methods, there are other methods that are provided by the
ProgressDialog class

Sr.
Title & description
No

getMax()
1
This method returns the maximum value of the progress.

incrementProgressBy(int diff)
2 This method increments the progress bar by the difference of value passed as a
parameter.

setIndeterminate(boolean indeterminate)
3
This method sets the progress indicator as determinate or indeterminate.

setMax(int max)
4
This method sets the maximum value of the progress dialog.

setProgress(int value)
5
This method is used to update the progress dialog with some specific value.

show(Context context, CharSequence title,


6 CharSequence message)
This is a static method, used to display progress dialog.

Example
524 | P a g e
This example demonstrates the horizontal use of the progress dialog which is in
fact a progress bar. It display a progress bar on pressing the button.

To experiment with this example, you need to run this on an actual device after
developing the application according to the steps below.

Ste
Description
ps

You will use Android studio to create an Android application under a package
1
com.example.sairamkrishna.myapplication.

Modify src/MainActivity.java file to add progress code to display the progress


2
dialog.

3 Modify res/layout/activity_main.xml file to add respective XML code.

Run the application and choose a running android device and install the
4
application on it and verify the results.

Following is the content of the modified main activity


file src/MainActivity.java.

package com.example.sairamkrishna.myapplication;

import android.app.ProgressDialog;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends ActionBarActivity {


Button b1;
private ProgressDialog progress;

protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.button2);
}

public void download(View view){


progress=new ProgressDialog(this);
progress.setMessage("Downloading Music");
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progress.setIndeterminate(true);
progress.setProgress(0);

525 | P a g e
progress.show();

final int totalProgressTime = 100;


final Thread t = new Thread() {
@Override
public void run() {
int jumpTime = 0;

while(jumpTime < totalProgressTime) {


try {
sleep(200);
jumpTime += 5;
progress.setProgress(jumpTime);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
t.start();
}
}

Modify the content of res/layout/activity_main.xml to the following −

<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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp"
android:text="Progress bar" />

<TextView
android:layout_width="wrap_content"

526 | P a g e
android:layout_height="wrap_content"
android:text="Tutorials Point"
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:textSize="35dp"
android:textColor="#ff16ff01" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Download"
android:onClick="download"
android:id="@+id/button2"
android:layout_marginLeft="125dp"
android:layout_marginStart="125dp"
android:layout_centerVertical="true" />

</RelativeLayout>

This is the default AndroidManifest.xml −

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


<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name=".MainActivity"
android:label="@string/app_name" >

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

</activity>

</application>
</manifest>

527 | P a g e
Let's try to run your application. We assume, you have connected your actual
Android Mobile device with your computer. To run the app from Android studio,
open one of your project's activity files and click Run icon from the toolbar.
Before starting your application, Android studio will display following window to
select an option where you want to run your Android application.

Select your mobile device as an option and then check your mobile device which
will display following screen −

528 | P a g e
Just press the button to start the Progress bar. After pressing, following screen
would appear −

529 | P a g e
It will continuously update itself.

Android - Push Notification


notification is a message you can display to the user outside of your
application's normal UI. You can create your own notifications in android very
easily.

Android provides NotificationManager class for this purpose. In order to use


this class, you need to instantiate an object of this class by requesting the

530 | P a g e
android system through getSystemService() method. Its syntax is given
below −

NotificationManager NM;
NM=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

After that you will create Notification through Notification class and specify its
attributes such as icon,title and time e.t.c. Its syntax is given below −

Notification notify = new


Notification(android.R.drawable.stat_notify_more,title,System.currentTimeMillis()
);

The next thing you need to do is to create a PendingIntent by passing context


and intent as a parameter. By giving a PendingIntent to another application, you
are granting it the right to perform the operation you have specified as if the
other application was yourself.

PendingIntent pending = PendingIntent.getActivity(getApplicationContext(), 0,


new Intent(),0);

The last thing you need to do is to call setLatestEventInfo method of the


Notification class and pass the pending intent along with notification subject and
body details. Its syntax is given below. And then finally call the notify method of
the NotificationManager class.

notify.setLatestEventInfo(getApplicationContext(), subject, body,pending);


NM.notify(0, notify);

Apart from the notify method, there are other methods available in the
NotificationManager class. They are listed below −

Sr.N
Method & description
o

cancel(int id)
1
This method cancel a previously shown notification.

cancel(String tag, int id)


2
This method also cancel a previously shown notification.

cancelAll()
3
This method cancel all previously shown notifications.

531 | P a g e
notify(int id, Notification notification)
4
This method post a notification to be shown in the status bar.

notify(String tag, int id, Notification notification)


5
This method also Post a notification to be shown in the status bar.

Example
The below example demonstrates the use of NotificationManager class. It crates
a basic application that allows you to create a notification.

To experiment with this example, you need to run this on an actual device or in
an emulator.

Ste
Description
ps

You will use Android studio to create an Android application under a


1
packagecom.example.sairamkrishna.myapplication.

2 Modify src/MainActivity.java file to add Notification code.

Modify layout XML file res/layout/activity_main.xml add any GUI component


3
if required.

Run the application and choose a running android device and install the
4
application on it and verify the results.

Here is the content of MainActivity.java.

In the following code abc indicates the logo of tutorialspoint.com


package com.example.sairamkrishna.myapplication;

import android.app.Notification;
import android.app.NotificationManager;

import android.content.Context;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;

import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends ActionBarActivity {

532 | P a g e
EditText ed1,ed2,ed3;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

ed1=(EditText)findViewById(R.id.editText);
ed2=(EditText)findViewById(R.id.editText2);
ed3=(EditText)findViewById(R.id.editText3);
Button b1=(Button)findViewById(R.id.button);

b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String tittle=ed1.getText().toString().trim();
String subject=ed2.getText().toString().trim();
String body=ed3.getText().toString().trim();

NotificationManager
notif=(NotificationManager)getSystemService(Context.NOTIFICATION_SE
RVICE);
Notification notify=new Notification.Builder

(getApplicationContext()).setContentTitle(tittle).setContentText(bo
dy).

setContentTitle(subject).setSmallIcon(R.drawable.abc).build();

notify.flags |= Notification.FLAG_AUTO_CANCEL;
notif.notify(0, notify);
}
});
}
}

Here is the content of 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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

533 | P a g e
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Notification"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />
.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials Point"
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:textSize="35dp"
android:textColor="#ff16ff01" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_below="@+id/textView2"
android:layout_alignLeft="@+id/textView2"
android:layout_alignStart="@+id/textView2"
android:layout_marginTop="52dp"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2"
android:hint="Name" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText2"
android:hint="Subject"
android:layout_below="@+id/editText"
android:layout_alignLeft="@+id/editText"
android:layout_alignStart="@+id/editText"
android:layout_alignRight="@+id/editText"
android:layout_alignEnd="@+id/editText" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="@+id/editText3"
android:hint="Body"

534 | P a g e
android:layout_below="@+id/editText2"
android:layout_alignLeft="@+id/editText2"
android:layout_alignStart="@+id/editText2"
android:layout_alignRight="@+id/editText2"
android:layout_alignEnd="@+id/editText2" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Notification"
android:id="@+id/button"
android:layout_marginTop="77dp"
android:layout_below="@+id/editText3"
android:layout_alignRight="@+id/textView"
android:layout_alignEnd="@+id/textView" />

</RelativeLayout>

Here is the content of AndroidManifest.xml.

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


<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name=".MainActivity"
android:label="@string/app_name" >

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

</activity>

</application>
</manifest>

Let's try to run our application. To run the app from Android studio, open one of
your project's activity files and click Run icon from the tool bar. Before starting

535 | P a g e
your application, Android studio will display following window to select an option
where you want to run your Android application.

Now fill in the field with the title , subject and the body. This has been shown
below in the figure −

536 | P a g e
Now click on the notify button and you will see a notification in the top
notification bar. It has been shown below −

537 | P a g e
Now scroll down the notification bar and see the notification. This has been
shown below in the figure −

538 | P a g e
539 | P a g e
Android - RenderScript
n this chapter, we will learn about Android RenderScript. Usually the apps on
android are designed as to consume as minimum resources as possible. But
some applications like some 3D games need high level processing on android.

To provide these applications high performance android introduced the


RenderScript. It is android based framework which is used for running
applications that perform very highly computational tasks. The development on
this framework is done in Native Development Kit(NDK) provided by android.
RenderScript is extremely useful for applications which performs following types
of actions −

 3D Rendering
 Image Processing
 Computational Photography
 Computer Vision

How RenderScript Works


RenderScript framework is basically based on data parallel computation. It
distributes your application workload on all the processors available on your
device like multi-core CPUs or GPUs.

This parallel distribution of workload frees the programmer from the tension of
load balancing and work scheduling. You can write more detailed and complex
algorithms for your app without the worry of computational power.

How to Begin
To use the RenderScript Framework you must have following two things −

 A RenderScript Kernel
 RenderScript APIs

A RenderScript Kernel
A kernel is a program which manages data processing instructions and manage
workload on Central Processing Units.A kernel is a fundamental part of the
operating system.

Similarly to run the RenderScript framework we need a written script named as


Kernel to manage all the data processing requests from our app and utilize more
features of the android OS provided by the NDK and as mentioned earlier that
the development of RenderScript is done in the Native Development Kit of
Android.

540 | P a g e
The Kernel Script is written in C-99 standard of C-language. This Standard was
before the development of C++. A RenderScript kernel script file usually placed
in .rs file. Each file is called as a script. A RenderScript Kernel script can contain
following elements −
Sr.N
Elements & Description
o

1 A Language declaration
It declares the version of RenderScript Kernel language used in this script.

A package declaration
2 This declaration names the package name of the Java class which will be
affected by this Kernel Code.

Invokable functions
3 You can call these invokable functions from your JAVA code with arbitrary
arguments.

Script Global Variables


4 These are just like the variables defined in C and C++ programming language.
You can access these variables from your JAVA code.

Following is the Sample Code of a Kernel −

uchar4 __convert__((kernel)) invert(uchar4 in, uint32_t x, uint32_t


y) {
uchar4 out = in;
out.r = 255 - in.r;
out.g = 255 - in.g;
return out;
}

RenderScript APIs
If you want to use RenderScript in your API, you can do it in following two ways

Sr.No APIs & Description

1 android.renderscript
This API is available on devices running Android 3.0 and higher.

2 android.support.v8.renderscript
This API is available on devices running Android 2.2 and higher.

541 | P a g e
To android support library following tools are required −

 Latest Android SDK Tools version


 Latest Android SDK Build-tools version

How to use RenderScript Support Library


First Open the project.properties file in your project and add following lines in
the file −
renderscript.target=18
renderscript.support.mode=true
sdk.buildtools=18.1.0

Now open your main class which use RenderScript and add an import for the
Support Library classes as following −

import android.support.v8.renderscript.*;
Following are the purposes of above mentioned properties that we add in
the project.properties file.
Sr.N
Project properties & Description
o

1 renderscript.target
It specifies the byte code version to be generated.

2 renderscript.support.mode
It specifies a compatible version for the generated byte code to fall back.

3 sdk.buildtools
It Specifies the versions of Android SDK build tools to use.

Now call your RenderScript Kernel functions and compute complex algorithms in
your app.

Android - RSS Reader


RSS stands for Really Simple Syndication. RSS is an easy way to share your
website updates and content with your users so that users might not have to
visit your site daily for any kind of updates.

RSS Example

542 | P a g e
RSS is a document that is created by the website with .xml extension. You can
easily parse this document and show it to the user in your application. An RSS
document looks like this.

<rss version="2.0">
<channel>
<title>Sample RSS</title>
<link>http://www.google.com</link>
<description>World's best search engine</description>
</channel>
</rss>

RSS Elements
An RSS document such as above has the following elements.

Sr.No Component & description

channel
1
This element is used to describe the RSS feed

title
2
Defines the title of the channel

link
3
Defines the hyper link to the channel

description
4
Describes the channel

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

Parsing RSS
Parsing an RSS document is more like parsing XML. So now lets see how to
parse an XML document.

For this, We will create XMLPullParser object , but in order to create that we will
first create XmlPullParserFactory object and then call its newPullParser() method
to create XMLPullParser. Its syntax is given below −

543 | P a g e
private XmlPullParserFactory xmlFactoryObject =
XmlPullParserFactory.newInstance();
private XmlPullParser myparser = xmlFactoryObject.newPullParser();

The next step involves specifying the file for XmlPullParser that contains XML. It
could be a file or could be a Stream. In our case it is a stream.Its syntax is given
below −

myparser.setInput(stream, null);

The last step is to parse the XML. An XML file consist of events , Name , Text ,
AttributesValue e.t.c. So XMLPullParser has a separate function for parsing each
of the component of XML file. Its syntax is given below −

int event = myParser.getEventType();


while (event != XmlPullParser.END_DOCUMENT) {
String name=myParser.getName();

switch (event){
case XmlPullParser.START_TAG:
break;

case XmlPullParser.END_TAG:
if(name.equals("temperature")){
temperature = myParser.getAttributeValue(null,"value");
}
break;
}
event = myParser.next();
}

The method getEventType returns the type of event that happens. e.g:
Document start, tag start e.t.c. The method getName returns the name of the
tag and since we are only interested in temperature, so we just check in
conditional statement that if we got a temperature tag, we call the
method getAttributeValue to return us the value of temperature tag.

Apart from the these methods, there are other methods provided by this class
for better parsing XML files. These methods are listed below −

Sr.N
Method & description
o

getAttributeCount()
1
This method just Returns the number of attributes of the current start tag.

544 | P a g e
getAttributeName(int index)
2
This method returns the name of the attribute specified by the index value.

getColumnNumber()
3
This method returns the Returns the current column number, starting from 0.

getDepth()
4
This method returns Returns the current depth of the element.

getLineNumber()
5
Returns the current line number, starting from 1.

getNamespace()
6
This method returns the name space URI of the current element.

getPrefix()
7
This method returns the prefix of the current element.

getName()
8
This method returns the name of the tag.

getText()
9
This method returns the text for that particular element.

isWhitespace()
10 This method checks whether the current TEXT event contains only white space
characters.

Example
Here is an example demonstrating the use of XMLPullParser class. It creates a
basic Parsing application that allows you to parse an RSS document present
here at /android/sampleXML.xml and then show the result.

To experiment with this example, you can run this on an actual device or in an
emulator.

Ste
Description
ps

You will use Android studio to create an Android application under a package
1
com.example.sairamkrishna.myapplication.

2 Modify src/MainActivity.java file to add necessary code.

545 | P a g e
3 Modify the res/layout/activity_main to add respective XML components.

Create a new java file under src/HandleXML.java to fetch and parse XML
4
data.

5 Create a new java file under src/second.java to display result of XML

5 Modify AndroidManifest.xml to add necessary internet permission.

Run the application and choose a running android device and install the
6
application on it and verify the results.

Following is the content of the modified main activity


file src/MainActivity.java.

package com.example.sairamkrishna.myapplication;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {


EditText title,link,description;
Button b1,b2;
private String
finalUrl="https://www.tutorialspoint.com/android/sampleXML.xml";
private HandleXML obj;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

title = (EditText) findViewById(R.id.editText);


link = (EditText) findViewById(R.id.editText2);
description = (EditText) findViewById(R.id.editText3);

b1=(Button)findViewById(R.id.button);
b2=(Button)findViewById(R.id.button2);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
obj = new HandleXML(finalUrl);

546 | P a g e
obj.fetchXML();

while(obj.parsingComplete);
title.setText(obj.getTitle());
link.setText(obj.getLink());
description.setText(obj.getDescription());
}
});

b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent in=new Intent(MainActivity.this,second.class);
startActivity(in);
}
});
}

Following is the content of the java file src/HandleXML.java.

package com.example.rssreader;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.util.Log;

public class HandleXML {


private String title = "title";
private String link = "link";
private String description = "description";
private String urlString = null;
private XmlPullParserFactory xmlFactoryObject;
public volatile boolean parsingComplete = true;

public HandleXML(String url){


this.urlString = url;
}

public String getTitle(){


return title;
}

547 | P a g e
public String getLink(){
return link;
}

public String getDescription(){


return description;
}

public void parseXMLAndStoreIt(XmlPullParser myParser) {


int event;
String text=null;

try {
event = myParser.getEventType();

while (event != XmlPullParser.END_DOCUMENT) {


String name=myParser.getName();

switch (event){
case XmlPullParser.START_TAG:
break;

case XmlPullParser.TEXT:
text = myParser.getText();
break;

case XmlPullParser.END_TAG:

if(name.equals("title")){
title = text;
}

else if(name.equals("link")){
link = text;
}

else if(name.equals("description")){
description = text;
}

else{
}

break;
}

event = myParser.next();
}

548 | P a g e
parsingComplete = false;
}

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

public void fetchXML(){


Thread thread = new Thread(new Runnable(){
@Override
public void run() {

try {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection)
url.openConnection();

conn.setReadTimeout(10000 /* milliseconds */);


conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);

// Starts the query


conn.connect();
InputStream stream = conn.getInputStream();

xmlFactoryObject =
XmlPullParserFactory.newInstance();
XmlPullParser myparser =
xmlFactoryObject.newPullParser();

myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES,
false);
myparser.setInput(stream, null);

parseXMLAndStoreIt(myparser);
stream.close();
}

catch (Exception e) {
}
}
});
thread.start();
}
}

549 | P a g e
Create a file and named as second.java file under directory java/second.java

package com.example.sairamkrishna.myapplication;

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;

public class second extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
WebView w1=(WebView)findViewById(R.id.webView);

w1.loadUrl("https://www.tutorialspoint.com/android/sampleXML.xml");
}
}

Create a xml file at res/layout/second_activity.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">

<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/webView"
android:layout_gravity="center_horizontal" />
</LinearLayout>

Modify the content of res/layout/activity_main.xml to the following −

<?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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"

550 | P a g e
tools:context=".MainActivity"
android:transitionGroup="true">

<TextView android:text="RSS example"


android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textview"
android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:id="@+id/textView"
android:layout_below="@+id/textview"
android:layout_centerHorizontal="true"
android:textColor="#ff7aff24"
android:textSize="35dp" />

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:theme="@style/Base.TextAppearance.AppCompat" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_below="@+id/imageView"
android:hint="Tittle"
android:textColorHint="#ff69ff0e"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText2"
android:layout_below="@+id/editText"
android:layout_alignLeft="@+id/editText"
android:layout_alignStart="@+id/editText"

551 | P a g e
android:textColorHint="#ff21ff11"
android:hint="Link"
android:layout_alignRight="@+id/editText"
android:layout_alignEnd="@+id/editText" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText3"
android:layout_below="@+id/editText2"
android:layout_alignLeft="@+id/editText2"
android:layout_alignStart="@+id/editText2"
android:hint="Description"
android:textColorHint="#ff33ff20"
android:layout_alignRight="@+id/editText2"
android:layout_alignEnd="@+id/editText2" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fetch"
android:id="@+id/button"
android:layout_below="@+id/editText3"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_toLeftOf="@+id/imageView"
android:layout_toStartOf="@+id/imageView" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Result"
android:id="@+id/button2"
android:layout_alignTop="@+id/button"
android:layout_alignRight="@+id/editText3"
android:layout_alignEnd="@+id/editText3" />

</RelativeLayout>

Modify the res/values/string.xml to the following

<resources>
<string name="app_name">My Application</string>
</resources>

This is the default AndroidManifest.xml.

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

552 | P a g e
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >
<uses-permission android:name="android.permission.INTERNET"/>

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name=".MainActivity"
android:label="@string/app_name" >

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

</activity>

<activity android:name=".second"></activity>
</application>
</manifest>

Let's try to run your application. I assume you had created your AVD while
doing environment setup. To run the app from Android studio, open one of your
project's activity files and click Run icon from the toolbar. Android studio
installs the app on your AVD and starts it and if everything is fine with your
setup and application, it will display following Emulator window −

553 | P a g e
Just press the Fetch Feed button to fetch RSS feed. After pressing, following
screen would appear which would show the RSS data.

554 | P a g e
Just press the result button to see XML, which is placed
at https://www.tutorialspoint.com/android/sampleXML.xml

555 | P a g e
556 | P a g e
Android - Screen Cast
Android Screen cast is a desktop application to control an android device
remotely. If your phone is not rooted, you can only view your mobile activity in
PC.

But if you phone is rooted , you can communicate both ways. You can also
control your device remotely using keyboard and mouse if your phone is rooted.

Screen Cast Steps


The steps of using screen cast has been mentioned below −

Steps Description

1 You should have latest android SDK installed on your PC.

2 Turn on USB debugging feature on your phone.

3 Connect your pc with phone via data cable.

4 Make sure you have installed latest version of Google Chrome.

5 Download and open vysor chrome app.

Step 1
You can download the latest android SDK from here.

Step 2
Turn on USB debugging feature on your device. It is usually found under settings
and developer options.

Step 3
Just connect your pc with your phone via the USB data cable.

Step 4
Finally it will install Vysor app on your mobile Once installed, it will open
automatically in your mobile as shown below −

557 | P a g e
558 | P a g e
If everything work fine, It will open a screen in windows as shown below −

Now click on view button, it will open cast your mobile screen as shown below.

559 | P a g e
Android - SDK Manager
To download and install latest android APIs and development tools from the
internet, android provide us with android SDK manager. Android SDK Manager
separates the APIs, tools and different platforms into different packages which
you can download.

560 | P a g e
Android SDK manager comes with the Android SDK bundle. You can't download
it separately. You can download the android sdk from here.

Running Android SDK Manager


Once downloaded, you can launch Android SDK Manager in one of the following
ways −

 Click tools->Android-> SDK Manager option in Eclipse.


 Double Click on the SDK Manager.exe file in the Android SDK folder.

When it runs you will see the following screen −

You can select which package you want to download by selecting the checkbox
and then click Install to install those packages. By default SDK Manager keeps
it up to date with latest APIs and other packages.

Once you download the SDK, following packages are available but first three are
necessary to run your SDK and others are recommended.

561 | P a g e
Recommended Packages
Sr.N
Package & Description
o

1 SDK Tools
This is necessary package to run your SDK.

2 SDK Platform-tools
This package will be installed once when you first run the SDK manager.

SDK Platform
3 At least one platform must be installed in your environment to run your
application.

System Image
4 It's a good practice to download system images for all of the android versions
so you can test your app on them with the Android Emulator.

5 SDK Samples
This will give you some sample codes to learn about android.

Enabling Proxy in Android SDK Manager


When you run the Android SDK Manager, by default it will check from the
Android Repository and Third Party Add-ons and display the available packages
to you.

If you want to use proxy, you can do it by clicking on the Tools-->Optionsin the
menu. Once you click it, you will see the following screen −

562 | P a g e
Just Enter the proxy and run your SDK Manager.

Adding New Third Party Sites


If you want to download some Third Party made Android add-ons, you can do it
in the SDK manager by following steps −

 Click on the Tools option in the menu.


 Click on the Manage Add-On Sites option in the sub menu.
 Select the User Defined Sites tab.
 Click the New button.

Following screen will be displayed −

563 | P a g e
Just add the URL of Add-on.xml file and click Ok. Now you can download the
Third Party Add-on in your development environment and use it.

Android - Sensors
Most of the android devices have built-in sensors that measure motion,
orientation, and various environmental condition. The android platform supports
three broad categories of sensors.

 Motion Sensors
 Environmental sensors
 Position sensors

Some of the sensors are hardware based and some are software based sensors.
Whatever the sensor is, android allows us to get the raw data from these
sensors and use it in our application. For this android provides us with some
classes.

564 | P a g e
Android provides SensorManager and Sensor classes to use the sensors in our
application. In order to use sensors, first thing you need to do is to instantiate
the object of SensorManager class. It can be achieved as follows.

SensorManager sMgr;
sMgr = (SensorManager)this.getSystemService(SENSOR_SERVICE);

The next thing you need to do is to instantiate the object of Sensor class by
calling the getDefaultSensor() method of the SensorManager class. Its syntax is
given below −

Sensor light;
light = sMgr.getDefaultSensor(Sensor.TYPE_LIGHT);

Once that sensor is declared , you need to register its listener and override two
methods which are onAccuracyChanged and onSensorChanged. Its syntax is as
follows −

sMgr.registerListener(this, light,SensorManager.SENSOR_DELAY_NORMAL);
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}

public void onSensorChanged(SensorEvent event) {


}

Getting list of sensors supported


You can get a list of sensors supported by your device by calling the
getSensorList method, which will return a list of sensors containing their name
and version number and much more information. You can then iterate the list to
get the information. Its syntax is given below −

sMgr = (SensorManager)this.getSystemService(SENSOR_SERVICE);
List<Sensor> list = sMgr.getSensorList(Sensor.TYPE_ALL);
for(Sensor sensor: list){
}

Apart from the these methods, there are other methods provided by the
SensorManager class for managing sensors framework. These methods are
listed below −

Sr.N Method & description

565 | P a g e
o

1 getDefaultSensor(int type)
This method get the default sensor for a given type.

getInclination(float[] I)
2 This method computes the geomagnetic inclination angle in radians from the
inclination matrix.

registerListener(SensorListener listener, int sensors, int


3 rate)
This method registers a listener for the sensor

unregisterListener(SensorEventListener listener, Sensor


4 sensor)
This method unregisters a listener for the sensors with which it is registered.

5 getOrientation(float[] R, float[] values)


This method computes the device's orientation based on the rotation matrix.

getAltitude(float p0, float p)


6 This method computes the Altitude in meters from the atmospheric pressure
and the pressure at sea level.

Example
Here is an example demonstrating the use of SensorManager class. It creates a
basic application that allows you to view the list of sensors on your device.

To experiment with this example , you can run this on an actual device or in an
emulator.

Ste
Description
ps

You will use Android studio to create an Android application under a package
1
com.example.sairamkrishna.myapplication.

2 Modify src/MainActivity.java file to add necessary code.

3 Modify the res/layout/activity_main to add respective XML components.

566 | P a g e
Run the application and choose a running android device and install the application
4
on it and verify the results.

Following is the content of the modified MainActivity.java.


package com.example.sairamkrishna.myapplication;

import android.app.Activity;
import android.hardware.SensorManager;
import android.os.Bundle;

import android.util.Log;

import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import android.widget.TextView;

import java.util.List;
import android.hardware.Sensor;
import android.hardware.SensorManager;

public class MainActivity extends Activity {


TextView tv1=null;
private SensorManager mSensorManager;
@Override

protected void onCreate(Bundle savedInstanceState) {


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

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


tv1.setVisibility(View.GONE);

mSensorManager = (SensorManager)
getSystemService(SENSOR_SERVICE);
List<Sensor> mList=
mSensorManager.getSensorList(Sensor.TYPE_ALL);

for (int i = 1; i < mList.size(); i++) {


tv1.setVisibility(View.VISIBLE);
tv1.append("\n" + mList.get(i).getName() + "\n" +
mList.get(i).getVendor() + "\n" + mList.get(i).getVersion());
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

567 | P a g e
// Inflate the menu; this adds items to the action bar if it
is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.

int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Following is the modified content of the xml activity_main.xml.
In the below code abc indicates about the logo of tutorialspoint.com

<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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:transitionGroup="true">

<TextView android:text="Sensor "


android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textview"
android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:id="@+id/textView"

568 | P a g e
android:layout_below="@+id/textview"
android:layout_centerHorizontal="true"
android:textColor="#ff7aff24"
android:textSize="35dp" />

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:theme="@style/Base.TextAppearance.AppCompat" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="@+id/textView2"
android:layout_below="@+id/imageView"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />

</RelativeLayout>
Following is the content of the res/values/string.xml.
<resources>
<string name="app_name">My Application</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
</resources>
Following is the content of AndroidManifest.xml file.
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name=".MainActivity"
android:label="@string/app_name" >

569 | P a g e
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>

</activity>

</application>
</manifest>
Let's try to run our application we just modified. I assume you had created
your AVD while doing environment setup. To run the app from Android studio,
open one of your project's activity files and click Run icon from the toolbar.
Android studio installs the app on your AVD and starts it and if everything is fine
with your setup and application, it will display following Emulator window −

570 | P a g e
Now if you will look at your device screen, you will see the list of sensors
supported by your device along with their name and version and other
information.

If you would run this application on different devices, the output would be
different because the output depends upon the number of sensors supported by
your device.

571 | P a g e
Android - Session Management
Session help you when want to store user data outside your application, so that
when the next time user use your application, you can easily get back his details
and perform accordingly.

This can be done in many ways. But the most easiest and nicest way of doing
this is through Shared Preferences.

Shared Preferences
Shared Preferences allow you to save and retrieve data in the form of key,value
pair. In order to use shared preferences, you have to call a method
getSharedPreferences() that returns a SharedPreference instance pointing to the
file that contains the values of preferences.

SharedPreferences sharedpreferences =
getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

You can save something in the sharedpreferences by using


SharedPreferences.Editor class. You will call the edit method of
SharedPreference instance and will receive it in an editor object. Its syntax is −

Editor editor = sharedpreferences.edit();


editor.putString("key", "value");
editor.commit();

Apart from the putString method, there are methods available in the editor class
that allows manipulation of data inside shared preferences. They are listed as
follows −

Sr.N
Mode & description
o

apply()
1 It is an abstract method. It will commit your changes back from editor to the
sharedPreference object you are calling

clear()
2
It will remove all values from the editor

remove(String key)
3
It will remove the value whose key has been passed as a parameter

572 | P a g e
putLong(String key, long value)
4
It will save a long value in a preference editor

putInt(String key, int value)


5
It will save a integer value in a preference editor

putFloat(String key, float value)


6
It will save a float value in a preference editor

Session Management through Shared Preferences


In order to perform session management from shared preferences, we need to
check the values or data stored in shared preferences in
the onResume method. If we don't have the data, we will start the application
from the beginning as it is newly installed. But if we got the data, we will start
from the where the user left it. It is demonstrated in the example below −

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

Example
The below example demonstrates the use of Session Management. It crates a
basic application that allows you to login for the first time. And then when you
exit the application without logging out, you will be brought back to the same
place if you start the application again. But if you logout from the application,
you will be brought back to the main login screen.

To experiment with this example, you need to run this on an actual device or in
an emulator.

Ste
Description
ps

You will use android studio IDE to create an Android application under a
1
package com.example.sairamkrishna.myapplication.

2 Modify src/MainActivity.java file to add progress code to add session code.

Create New Activity and it name as second.java.Edit this file to add progress
3
code to add session code.

573 | P a g e
4 Modify res/layout/activity_main.xml file to add respective XML code.

5 Modify res/layout/second_main.xml file to add respective XML code.

Run the application and choose a running android device and install the
7
application on it and verify the results.

Here is the content of MainActivity.java.

package com.example.sairamkrishna.myapplication;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
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 {


EditText ed1,ed2,ed3;
Button b1;
Intent in;

public static final String MyPREFERENCES = "MyPrefs" ;


public static final String Name = "nameKey";
public static final String Phone = "phoneKey";
public static final String Email = "emailKey";
SharedPreferences sharedpreferences;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

ed1=(EditText)findViewById(R.id.editText);
ed2=(EditText)findViewById(R.id.editText2);
ed3=(EditText)findViewById(R.id.editText3);

b1=(Button)findViewById(R.id.button);
sharedpreferences = getSharedPreferences(MyPREFERENCES,
Context.MODE_PRIVATE);

b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String n = ed1.getText().toString();

574 | P a g e
String ph = ed2.getText().toString();
String e = ed3.getText().toString();

SharedPreferences.Editor editor =
sharedpreferences.edit();

editor.putString(Name, n);
editor.putString(Phone, ph);
editor.putString(Email, e);
editor.commit();

in = new Intent(MainActivity.this,second_main.class);
startActivity(in);
}
});
}
}

Here is the content of second_main.java.

package com.example.sairamkrishna.myapplication;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class second_main extends Activity {


Button bu=null;
Button bu2=null;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_main);

bu=(Button)findViewById(R.id.button2);
bu2=(Button)findViewById(R.id.button3);
}

public void logout(View view){


SharedPreferences sharedpreferences =
getSharedPreferences(MainActivity.MyPREFERENCES,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.clear();

575 | P a g e
editor.commit();
}

public void close(View view){


finish();
}
}

Here is the content of 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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Shared Preference"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="35dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials Point"
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:textSize="35dp"
android:textColor="#ff16ff01" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_below="@+id/textView2"
android:layout_marginTop="67dp"
android:hint="Name"

576 | P a g e
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText2"
android:layout_below="@+id/editText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:hint="Pass" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText3"
android:layout_below="@+id/editText2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:hint="Email" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="login"
android:id="@+id/button"
android:layout_below="@+id/editText3"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp" />

</RelativeLayout>

Here is the content of second_main.xml.

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


<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<Button

577 | P a g e
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Logout"
android:onClick="logout"
android:id="@+id/button2"
android:layout_gravity="center_horizontal"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="191dp" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Close"
android:onClick="close"
android:id="@+id/button3"
android:layout_below="@+id/button2"
android:layout_centerHorizontal="true"
android:layout_marginTop="69dp" />

</RelativeLayout>

Here is the content of Strings.xml.

<resources>
<string name="app_name">My Application</string>
</resources>

Here is the content of AndroidManifest.xml.

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


<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name=".MainActivity"
android:label="@string/app_name" >

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

578 | P a g e
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>

</activity>

<activity android:name=".second"></activity>

</application>
</manifest>

Let's try to run your application. I assume you had created your AVD while doing
environment setup. To run the app from Android studio, open one of your
project's activity files and click Run icon from the tool bar. Android studio
installs the app on your AVD and starts it and if everything is fine with your set-
up and application, it will display following Emulator window −

579 | P a g e
Type in your username and password (type anything you like, but
remember what you type), and click on login button. It is shown in the image
below −

580 | P a g e
As soon as you click on login button, you will be brought to this Welcome screen.
Now your login information is stored in shared preferences.

581 | P a g e
Now click on Exit without logout button and you will be brought back to the
home screen and in preference file out put would be as shown below image

582 | P a g e
If you open myPref.xml file as note file, it would be as follows

If you click on logout button, it will erase preference values. and if you entered
different values as inputs,it will enter those values as preference in XML.

Android - Shared Preferences


Android provides many ways of storing data of an application. One of this way is
called Shared Preferences. Shared Preferences allow you to save and retrieve
data in the form of key,value pair.

In order to use shared preferences, you have to call a method


getSharedPreferences() that returns a SharedPreference instance pointing to the
file that contains the values of preferences.

583 | P a g e
SharedPreferences sharedpreferences =
getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

The first parameter is the key and the second parameter is the MODE. Apart
from private there are other modes available that are listed below −

Sr.N
Mode & description
o

MODE_APPEND
1
This will append the new preferences with the already existing preferences

MODE_ENABLE_WRITE_AHEAD_LOGGING
2 Database open flag. When it is set , it would enable write ahead logging by
default

MODE_MULTI_PROCESS
3 This method will check for modification of preferences even if the
sharedpreference instance has already been loaded

MODE_PRIVATE
4
By setting this mode, the file can only be accessed using calling application

MODE_WORLD_READABLE
5
This mode allow other application to read the preferences

MODE_WORLD_WRITEABLE
6
This mode allow other application to write the preferences

You can save something in the sharedpreferences by using


SharedPreferences.Editor class. You will call the edit method of
SharedPreference instance and will receive it in an editor object. Its syntax is −

Editor editor = sharedpreferences.edit();


editor.putString("key", "value");
editor.commit();

Apart from the putString method , there are methods available in the editor
class that allows manipulation of data inside shared preferences. They are listed
as follows −

Sr.
Mode & description
NO

584 | P a g e
apply()
1 It is an abstract method. It will commit your changes back from editor to the
sharedPreference object you are calling

clear()
2
It will remove all values from the editor

remove(String key)
3
It will remove the value whose key has been passed as a parameter

putLong(String key, long value)


4
It will save a long value in a preference editor

putInt(String key, int value)


5
It will save a integer value in a preference editor

putFloat(String key, float value)


6
It will save a float value in a preference editor

Example
This example demonstrates the use of the Shared Preferences. It display a
screen with some text fields, whose value are saved when the application is
closed and brought back when it is opened again.

To experiment with this example, you need to run this on an actual device on
after developing the application according to the steps below −

Ste
Description
ps

You will use Android studio to create an Android application under a package
1
com.example.sairamkrishna.myapplication.

Modify src/MainActivity.java file to add progress code to display the spinning


2
progress dialog.

3 Modify res/layout/activity_main.xml file to add respective XML code.

Run the application and choose a running android device and install the
4
application on it and verify the results.

Following is the content of the modified MainActivity.java.

package com.example.sairamkrishna.myapplication;

585 | P a g e
import android.content.Context;
import android.content.SharedPreferences;
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;

public class MainActivity extends AppCompatActivity {


EditText ed1,ed2,ed3;
Button b1;

public static final String MyPREFERENCES = "MyPrefs" ;


public static final String Name = "nameKey";
public static final String Phone = "phoneKey";
public static final String Email = "emailKey";

SharedPreferences sharedpreferences;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

ed1=(EditText)findViewById(R.id.editText);
ed2=(EditText)findViewById(R.id.editText2);
ed3=(EditText)findViewById(R.id.editText3);

b1=(Button)findViewById(R.id.button);
sharedpreferences = getSharedPreferences(MyPREFERENCES,
Context.MODE_PRIVATE);

b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String n = ed1.getText().toString();
String ph = ed2.getText().toString();
String e = ed3.getText().toString();

SharedPreferences.Editor editor =
sharedpreferences.edit();

editor.putString(Name, n);
editor.putString(Phone, ph);
editor.putString(Email, e);
editor.commit();

586 | P a g e
Toast.makeText(MainActivity.this,"Thanks",Toast.LENGTH_LONG).show()
;
}
});
}

Following is the content of the modified main activity


fileres/layout/activiy_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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Shared Preference "
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="35dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials Point"
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:textSize="35dp"
android:textColor="#ff16ff01" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_below="@+id/textView2"

587 | P a g e
android:layout_marginTop="67dp"
android:hint="Name"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText2"
android:layout_below="@+id/editText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:hint="Pass" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText3"
android:layout_below="@+id/editText2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:hint="Email" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:id="@+id/button"
android:layout_below="@+id/editText3"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp" />

</RelativeLayout>

Following is the content of the modified content of file res/values/strings.xml.

<resources>
<string name="app_name">My Application</string>
</resources>

Following is the content default file AndroidManifest.xml.

588 | P a g e
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name=".MainActivity"
android:label="@string/app_name" >

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

</activity>

</application>
</manifest>

Let's try to run your application. I assume you have connected your actual
Android Mobile device with your computer. To run the app from Android studio,
open one of your project's activity files and click Run icon from the toolbar.
Before starting your application, Android studio will display following window to
select an option where you want to run your Android application.

589 | P a g e
Select your mobile device as an option and then check your mobile device which
will display following screen −

Now just put in some text in the field. Like i put some random name and other
information and click on save button.

590 | P a g e
Now when you press save button, the text will be saved in the shared
preferences. Now press back button and exit the application. Now open it again
and you will see all the text you have written back in your application.

591 | P a g e
Android - SIP Protocol
SIP stands for (Session Initiation Protocol). It is a protocol that let applications
easily set up outgoing and incoming voice calls, without having to manage
sessions, transport-level communication, or audio record or playback directly.

Applications
Some of the common applications of SIP are.

 Video conferencing
 Instant messaging

Requirements
Here are the requirements for developing a SIP application −

 Android OS must be 2.3 or higher


 You must have a data connection or WIFI
 You must have an SIP account in order to use this service.

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

592 | P a g e
SIP Classes
Here is a summary of the classes that are included in the Android SIP API:

Sr.N
Class & description
o

1 SipAudioCall
Handles an Internet audio call over SIP

2 SipErrorCode
Defines error codes returned during SIP actions

SipManager
3 Provides APIs for SIP tasks, such as initiating SIP connections, and provides
access to related SIP services

4 SipProfile
Defines a SIP profile, including a SIP account, domain and server information

SipSession
5 Represents a SIP session that is associated with a SIP dialog or a standalone
transaction not within a dialog

Functions of SIP
SIP has following major functions.

 SIP allows for the establishment of user location


 SIP provides a mechanism for call management
 SIP provides feature negotiation, so that all the parties in the call can agree to
the features supported among them

Components of SIP
SIP has two major components which are listed below.

 User Agent Client (UAC)


 User Agent Server (UAS)

593 | P a g e
UAC
UAC or User Agent Client are those end users who generates requests and send
those requests to the server.These requests are generated by the client
applications running on their systems.

UAS
UAS or User Agent Server are those systems which get the request generated by
UAC. The UAS process those requests and then according to the requests it
generates responses accordingly.

SipManager
SipManager is an android API for SIP tasks, such as initiating SIP connections,
and provides access to related SIP services. This class is the starting point for
any SIP actions. You can acquire an instance of it with newInstance().

The SipManager has many functions for managing SIP tasks. Some of the
functions are listed below.

Sr.N
Class & description
o

1 close(String localProfileUri)
Closes the specified profile to not make/receive calls

2 getCallId(Intent incomingCallIntent)
Gets the call ID from the specified incoming call broadcast intent

isOpened(String localProfileUri)
3 Checks if the specified profile is opened in the SIP service for making and/or
receiving calls

4 isSipWifiOnly(Context context)
Returns true if SIP is only available on WIFI

isRegistered(String localProfileUri)
5 Checks if the SIP service has successfully registered the profile to the SIP
provider (specified in the profile) for receiving calls

6 isVoipSupported(Context context)
Returns true if the system supports SIP-based VOIP API

594 | P a g e
takeAudioCall(Intent incomingCallIntent,
7 SipAudioCall.Listener listener)
Creates a SipAudioCall to take an incoming call

unregister(SipProfile localProfile,
8 SipRegistrationListener listener)
Manually unregisters the profile from the corresponding SIP provider for stop
receiving further calls
Android - Spelling Checker
The Android platform offers a spelling checker framework that lets you
implement and access spell checking in your application.

In order to use spelling checker , you need to


implement SpellCheckerSessionListener interface and override its methods.
Its syntax is given below −

public class HelloSpellCheckerActivity extends Activity implements


SpellCheckerSessionListener {
@Override
public void onGetSuggestions(final SuggestionsInfo[] arg0) {
// TODO Auto-generated method stub
}

@Override
public void onGetSentenceSuggestions(SentenceSuggestionsInfo[]
arg0) {
// TODO Auto-generated method stub
}
}

Next thing you need to do is to create an object of SpellCheckerSession class.


This object can be instantiated by calling newSpellCheckerSession method of
TextServicesManager class. This class handles interaction between application
and text services. You need to request system service to instantiate it. Its
syntax is given below −

private SpellCheckerSession mScs;


final TextServicesManager tsm = (TextServicesManager) getSystemService(
Context.TEXT_SERVICES_MANAGER_SERVICE);
mScs = tsm.newSpellCheckerSession(null, null, this, true);

The last thing you need to do is to call getSuggestions method to get


suggestion for any text, you want. The suggestions will be passed onto
the onGetSuggestions method from where you can do whatever you want.

595 | P a g e
mScs.getSuggestions(new TextInfo(editText1.getText().toString()),
3);

This method takes two parameters. First parameter is the string in the form of
Text Info object, and second parameter is the cookie number used to distinguish
suggestions.

Apart from the the methods , there are other methods provided by
the SpellCheckerSession class for better handling suggestions. These
methods are listed below −

Sr.N
Method & description
o

cancel()
1
Cancel pending and running spell check tasks

close()
2 Finish this session and allow TextServicesManagerService to disconnect the
bound spell checker

getSentenceSuggestions(TextInfo[] textInfos, int


3 suggestionsLimit)
Get suggestions from the specified sentences

getSpellChecker()
4
Get the spell checker service info this spell checker session has.

isSessionDisconnected()
5 True if the connection to a text service of this session is disconnected and not
alive.

Example
Here is an example demonstrating the use of Spell Checker. It creates a basic
spell checking application that allows you to write text and get suggestions.

To experiment with this example , you can run this on an actual device or in an
emulator.

Ste
Description
ps

You will use Android studio to create an Android application under a package
1
com.example.sairamkrishna.myapplication.

596 | P a g e
2 Modify src/MainActivity.java file to add necessary code.

3 Modify the res/layout/main to add respective XML components

Run the application and choose a running android device and install the
4
application on it and verify the results

Following is the content of the modified main activity


file src/MainActivity.java.

package com.example.sairamkrishna.myapplication;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.textservice.TextInfo;
import android.view.textservice.TextServicesManager;

import android.widget.Button;
import android.widget.EditText;

import android.view.textservice.SentenceSuggestionsInfo;
import android.view.textservice.SpellCheckerSession;
import
android.view.textservice.SpellCheckerSession.SpellCheckerSessionLis
tener;
import android.view.textservice.SuggestionsInfo;

import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements


SpellCheckerSessionListener {
Button b1;
TextView tv1;
EditText ed1;
private SpellCheckerSession mScs;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

b1=(Button)findViewById(R.id.button);
tv1=(TextView)findViewById(R.id.textView3);

ed1=(EditText)findViewById(R.id.editText);

597 | P a g e
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),
ed1.getText().toString(),Toast.LENGTH_SHORT).show();
mScs.getSuggestions(new
TextInfo(ed1.getText().toString()), 3);
}
});
}

public void onResume() {


super.onResume();
final TextServicesManager tsm = (TextServicesManager)
getSystemService(Context.TEXT_SERVICES_MANAGER_SERVICE);
mScs = tsm.newSpellCheckerSession(null, null, this, true);
}

public void onPause() {


super.onPause();
if (mScs != null) {
mScs.close();
}
}

public void onGetSuggestions(final SuggestionsInfo[] arg0) {


final StringBuilder sb = new StringBuilder();

for (int i = 0; i < arg0.length; ++i) {


// Returned suggestions are contained in SuggestionsInfo
final int len = arg0[i].getSuggestionsCount();
sb.append('\n');

for (int j = 0; j < len; ++j) {


sb.append("," + arg0[i].getSuggestionAt(j));
}

sb.append(" (" + len + ")");


}

runOnUiThread(new Runnable() {
public void run() {
tv1.append(sb.toString());
}
});
}

@Override

598 | P a g e
public void onGetSentenceSuggestions(SentenceSuggestionsInfo[]
arg0) {
// TODO Auto-generated method stub
}
}

Following is the modified content of the xml res/layout/main.xml.

In the following code abc indicates the logo of tutorialspoint.com


<?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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView android:text="Spell checker "


android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textview"
android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:id="@+id/textView"
android:layout_below="@+id/textview"
android:layout_centerHorizontal="true"
android:textColor="#ff7aff24"
android:textSize="35dp" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Suggestions"
android:id="@+id/button"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />

<EditText

599 | P a g e
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:hint="Enter Text"
android:layout_above="@+id/button"
android:layout_marginBottom="56dp"
android:focusable="true"
android:textColorHighlight="#ff7eff15"
android:textColorHint="#ffff25e6"
android:layout_alignRight="@+id/textview"
android:layout_alignEnd="@+id/textview"
android:layout_alignLeft="@+id/textview"
android:layout_alignStart="@+id/textview" />

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Suggestions"
android:id="@+id/textView3"
android:textSize="25sp"
android:layout_below="@+id/imageView" />

</RelativeLayout>

Following is the content of the res/values/string.xml.

<resources>
<string name="app_name">My Application</string>
</resources>

Following is the content of AndroidManifest.xml file.

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


<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"

600 | P a g e
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name=".MainActivity"
android:label="@string/app_name" >

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

</activity>

</application>
</manifest>

Let's try to run ourr application we just modified. I assume you had created
your AVD while doing environment setup. To run the app from Android studio,
open one of your project's activity files and click Run icon from the toolbar.
Android studio installs the app on your AVD and starts it and if everything is fine
with your setup and application, it will display following Emulator window −

601 | P a g e
Now what you need to do is to enter any text in the field. For example, i have
entered some text. Press the suggestions button. The following notification
would appear in you AVD along with suggestions −

602 | P a g e
Now change the text and press the button again, like i did. And this is what
comes on screen.

603 | P a g e
604 | P a g e
Android - SQLite Database
SQLite is a opensource SQL database that stores data to a text file on a device.
Android comes in with built in SQLite database implementation.

SQLite supports all the relational database features. In order to access this
database, you don't need to establish any kind of connections for it like
JDBC,ODBC e.t.c

Database - Package
The main package is android.database.sqlite that contains the classes to
manage your own databases

Database - Creation
In order to create a database you just need to call this method
openOrCreateDatabase with your database name and mode as a parameter. It
returns an instance of SQLite database which you have to receive in your own
object.Its syntax is given below

SQLiteDatabase mydatabase = openOrCreateDatabase("your database


name",MODE_PRIVATE,null);

Apart from this , there are other functions available in the database package ,
that does this job. They are listed below

Sr.N
Method & Description
o

openDatabase(String path,
SQLiteDatabase.CursorFactory factory, int flags,
1 DatabaseErrorHandler errorHandler)
This method only opens the existing database with the appropriate flag mode.
The common flags mode could be OPEN_READWRITE OPEN_READONLY

openDatabase(String path,
SQLiteDatabase.CursorFactory factory, int flags)
2
It is similar to the above method as it also opens the existing database but it
does not define any handler to handle the errors of databases

3 openOrCreateDatabase(String path,
SQLiteDatabase.CursorFactory factory)
It not only opens but create the database if it not exists. This method is

605 | P a g e
equivalent to openDatabase method.

openOrCreateDatabase(File file,
SQLiteDatabase.CursorFactory factory)
4
This method is similar to above method but it takes the File object as a path
rather then a string. It is equivalent to file.getPath()

Learn SQL in-depth with real-world projects through our SQL certification
course. Enroll and become a certified expert to boost your career.

Database - Insertion
we can create table or insert data into table using execSQL method defined in
SQLiteDatabase class. Its syntax is given below

mydatabase.execSQL("CREATE TABLE IF NOT EXISTS TutorialsPoint(Username


VARCHAR,Password VARCHAR);");
mydatabase.execSQL("INSERT INTO TutorialsPoint VALUES('admin','admin');");

This will insert some values into our table in our database. Another method that
also does the same job but take some additional parameter is given below

Sr.N
Method & Description
o

execSQL(String sql, Object[] bindArgs)


1 This method not only insert data , but also used to update or modify already
existing data in database using bind arguments

Database - Fetching
We can retrieve anything from database using an object of the Cursor class. We
will call a method of this class called rawQuery and it will return a resultset with
the cursor pointing to the table. We can move the cursor forward and retrieve
the data.

Cursor resultSet = mydatbase.rawQuery("Select * from TutorialsPoint",null);


resultSet.moveToFirst();
String username = resultSet.getString(0);
String password = resultSet.getString(1);

606 | P a g e
There are other functions available in the Cursor class that allows us to
effectively retrieve the data. That includes

Sr.N
Method & Description
o

getColumnCount()
1
This method return the total number of columns of the table.

getColumnIndex(String columnName)
2 This method returns the index number of a column by specifying the name of
the column

getColumnName(int columnIndex)
3 This method returns the name of the column by specifying the index of the
column

getColumnNames()
4
This method returns the array of all the column names of the table.

getCount()
5
This method returns the total number of rows in the cursor

getPosition()
6
This method returns the current position of the cursor in the table

isClosed()
7
This method returns true if the cursor is closed and return false otherwise

Database - Helper class


For managing all the operations related to the database , an helper class has
been given and is called SQLiteOpenHelper. It automatically manages the
creation and update of the database. Its syntax is given below

public class DBHelper extends SQLiteOpenHelper {


public DBHelper(){
super(context,DATABASE_NAME,null,1);
}
public void onCreate(SQLiteDatabase db) {}
public void onUpgrade(SQLiteDatabase database, int oldVersion,
int newVersion) {}
}

Example
607 | P a g e
Here is an example demonstrating the use of SQLite Database. It creates a basic
contacts applications that allows insertion, deletion and modification of
contacts.

To experiment with this example, you need to run this on an actual device on
which camera is supported.

Ste
Description
ps

You will use Android studio to create an Android application under a package
1
com.example.sairamkrishna.myapplication.

Modify src/MainActivity.java file to get references of all the XML


2
components and populate the contacts on listView.

3 Create new src/DBHelper.java that will manage the database work

Create a new Activity as DisplayContact.java that will display the contact on


4
the screen

5 Modify the res/layout/activity_main to add respective XML components

Modify the res/layout/activity_display_contact.xml to add respective XML


6
components

7 Modify the res/values/string.xml to add necessary string components

8 Modify the res/menu/display_contact.xml to add necessary menu components

9 Create a new menu as res/menu/mainmenu.xml to add the insert contact option

Run the application and choose a running android device and install the
10
application on it and verify the results.

Following is the content of the modified MainActivity.java.

package com.example.sairamkrishna.myapplication;

import android.content.Context;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;

import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;

608 | P a g e
import android.view.View;

import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends ActionBarActivity {


public final static String EXTRA_MESSAGE = "MESSAGE";
private ListView obj;
DBHelper mydb;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mydb = new DBHelper(this);


ArrayList array_list = mydb.getAllCotacts();
ArrayAdapter arrayAdapter=new
ArrayAdapter(this,android.R.layout.simple_list_item_1, array_list);

obj = (ListView)findViewById(R.id.listView1);
obj.setAdapter(arrayAdapter);
obj.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2,long arg3) {
// TODO Auto-generated method stub
int id_To_Search = arg2 + 1;

Bundle dataBundle = new Bundle();


dataBundle.putInt("id", id_To_Search);

Intent intent = new


Intent(getApplicationContext(),DisplayContact.class);

intent.putExtras(dataBundle);
startActivity(intent);
}
});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

609 | P a g e
// Inflate the menu; this adds items to the action bar if it
is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item){
super.onOptionsItemSelected(item);

switch(item.getItemId()) {
case R.id.item1:Bundle dataBundle = new Bundle();
dataBundle.putInt("id", 0);

Intent intent = new


Intent(getApplicationContext(),DisplayContact.class);
intent.putExtras(dataBundle);

startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}

public boolean onKeyDown(int keycode, KeyEvent event) {


if (keycode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
}
return super.onKeyDown(keycode, event);
}
}

Following is the modified content of display contact


activity DisplayContact.java

package com.example.sairamkrishna.myapplication;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;

import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;

import android.view.Menu;
import android.view.MenuItem;

610 | P a g e
import android.view.View;

import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class DisplayContact extends Activity {


int from_Where_I_Am_Coming = 0;
private DBHelper mydb ;

TextView name ;
TextView phone;
TextView email;
TextView street;
TextView place;
int id_To_Update = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_contact);
name = (TextView) findViewById(R.id.editTextName);
phone = (TextView) findViewById(R.id.editTextPhone);
email = (TextView) findViewById(R.id.editTextStreet);
street = (TextView) findViewById(R.id.editTextEmail);
place = (TextView) findViewById(R.id.editTextCity);

mydb = new DBHelper(this);

Bundle extras = getIntent().getExtras();


if(extras !=null) {
int Value = extras.getInt("id");

if(Value>0){
//means this is the view part not the add contact part.
Cursor rs = mydb.getData(Value);
id_To_Update = Value;
rs.moveToFirst();

String nam =
rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_NAME));
String phon =
rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_PHONE));
String emai =
rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_EMAIL));
String stree =
rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_STREET));
String plac =
rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_CITY));

611 | P a g e
if (!rs.isClosed()) {
rs.close();
}
Button b = (Button)findViewById(R.id.button1);
b.setVisibility(View.INVISIBLE);

name.setText((CharSequence)nam);
name.setFocusable(false);
name.setClickable(false);

phone.setText((CharSequence)phon);
phone.setFocusable(false);
phone.setClickable(false);

email.setText((CharSequence)emai);
email.setFocusable(false);
email.setClickable(false);

street.setText((CharSequence)stree);
street.setFocusable(false);
street.setClickable(false);

place.setText((CharSequence)plac);
place.setFocusable(false);
place.setClickable(false);
}
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it
is present.
Bundle extras = getIntent().getExtras();

if(extras !=null) {
int Value = extras.getInt("id");
if(Value>0){
getMenuInflater().inflate(R.menu.display_contact,
menu);
} else{
getMenuInflater().inflate(R.menu.menu_main menu);
}
}
return true;
}

public boolean onOptionsItemSelected(MenuItem item) {

612 | P a g e
super.onOptionsItemSelected(item);
switch(item.getItemId()) {
case R.id.Edit_Contact:
Button b = (Button)findViewById(R.id.button1);
b.setVisibility(View.VISIBLE);
name.setEnabled(true);
name.setFocusableInTouchMode(true);
name.setClickable(true);

phone.setEnabled(true);
phone.setFocusableInTouchMode(true);
phone.setClickable(true);

email.setEnabled(true);
email.setFocusableInTouchMode(true);
email.setClickable(true);

street.setEnabled(true);
street.setFocusableInTouchMode(true);
street.setClickable(true);

place.setEnabled(true);
place.setFocusableInTouchMode(true);
place.setClickable(true);

return true;
case R.id.Delete_Contact:

AlertDialog.Builder builder = new


AlertDialog.Builder(this);
builder.setMessage(R.string.deleteContact)
.setPositiveButton(R.string.yes, new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id)
{
mydb.deleteContact(id_To_Update);
Toast.makeText(getApplicationContext(), "Deleted
Successfully",
Toast.LENGTH_SHORT).show();
Intent intent = new
Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
}
})
.setNegativeButton(R.string.no, new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}

613 | P a g e
});

AlertDialog d = builder.create();
d.setTitle("Are you sure");
d.show();

return true;
default:
return super.onOptionsItemSelected(item);

}
}

public void run(View view) {


Bundle extras = getIntent().getExtras();
if(extras !=null) {
int Value = extras.getInt("id");
if(Value>0){

if(mydb.updateContact(id_To_Update,name.getText().toString(),
phone.getText().toString(),
email.getText().toString(),
street.getText().toString(),
place.getText().toString())){
Toast.makeText(getApplicationContext(), "Updated",
Toast.LENGTH_SHORT).show();
Intent intent = new
Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
} else{
Toast.makeText(getApplicationContext(), "not
Updated", Toast.LENGTH_SHORT).show();
}
} else{
if(mydb.insertContact(name.getText().toString(),
phone.getText().toString(),
email.getText().toString(),
street.getText().toString(),
place.getText().toString())){
Toast.makeText(getApplicationContext(), "done",

Toast.LENGTH_SHORT).show();
} else{
Toast.makeText(getApplicationContext(), "not done",
Toast.LENGTH_SHORT).show();
}
Intent intent = new
Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);

614 | P a g e
}
}
}
}

Following is the content of Database class DBHelper.java

package com.example.sairamkrishna.myapplication;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;

public class DBHelper extends SQLiteOpenHelper {

public static final String DATABASE_NAME = "MyDBName.db";


public static final String CONTACTS_TABLE_NAME = "contacts";
public static final String CONTACTS_COLUMN_ID = "id";
public static final String CONTACTS_COLUMN_NAME = "name";
public static final String CONTACTS_COLUMN_EMAIL = "email";
public static final String CONTACTS_COLUMN_STREET = "street";
public static final String CONTACTS_COLUMN_CITY = "place";
public static final String CONTACTS_COLUMN_PHONE = "phone";
private HashMap hp;

public DBHelper(Context context) {


super(context, DATABASE_NAME , null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table contacts " +
"(id integer primary key, name text,phone text,email text,
street text,place text)"
);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {

615 | P a g e
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}

public boolean insertContact (String name, String phone, String


email, String street,String place) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("phone", phone);
contentValues.put("email", email);
contentValues.put("street", street);
contentValues.put("place", place);
db.insert("contacts", null, contentValues);
return true;
}

public Cursor getData(int id) {


SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from contacts where
id="+id+"", null );
return res;
}

public int numberOfRows(){


SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db,
CONTACTS_TABLE_NAME);
return numRows;
}

public boolean updateContact (Integer id, String name, String


phone, String email, String street,String place) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("phone", phone);
contentValues.put("email", email);
contentValues.put("street", street);
contentValues.put("place", place);
db.update("contacts", contentValues, "id = ? ", new String[]
{ Integer.toString(id) } );
return true;
}

public Integer deleteContact (Integer id) {


SQLiteDatabase db = this.getWritableDatabase();
return db.delete("contacts",

616 | P a g e
"id = ? ",
new String[] { Integer.toString(id) });
}

public ArrayList<String> getAllCotacts() {


ArrayList<String> array_list = new ArrayList<String>();

//hp = new HashMap();


SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from contacts", null );
res.moveToFirst();

while(res.isAfterLast() == false){

array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_NAM
E)));
res.moveToNext();
}
return array_list;
}
}

Following is the content of the res/layout/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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp"
android:text="Data Base" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"

617 | P a g e
android:text="Tutorials Point"
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:textSize="35dp"
android:textColor="#ff16ff01" />

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true"
android:src="@drawable/logo"/>

<ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/scrollView"
android:layout_below="@+id/imageView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true">

<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" >
</ListView>

</ScrollView>

</RelativeLayout>

Following is the content of the res/layout/activity_display_contact.xml

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


<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".DisplayContact" >

618 | P a g e
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="370dp"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin">

<EditText
android:id="@+id/editTextName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginTop="5dp"
android:layout_marginLeft="82dp"
android:ems="10"
android:inputType="text" >
</EditText>

<EditText
android:id="@+id/editTextEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editTextStreet"
android:layout_below="@+id/editTextStreet"
android:layout_marginTop="22dp"
android:ems="10"
android:inputType="textEmailAddress" />

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/editTextName"
android:layout_alignParentLeft="true"
android:text="@string/name"

android:textAppearance="?android:attr/textAppearanceMedium" />

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editTextCity"
android:layout_alignParentBottom="true"
android:layout_marginBottom="28dp"
android:onClick="run"
android:text="@string/save" />

619 | P a g e
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/editTextEmail"
android:layout_alignLeft="@+id/textView1"
android:text="@string/email"

android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/editTextPhone"
android:layout_alignLeft="@+id/textView1"
android:text="@string/phone"

android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/editTextEmail"
android:layout_alignLeft="@+id/textView5"
android:text="@string/street"

android:textAppearance="?android:attr/textAppearanceMedium" />

<EditText
android:id="@+id/editTextCity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/editTextName"
android:layout_below="@+id/editTextEmail"
android:layout_marginTop="30dp"
android:ems="10"
android:inputType="text" />

<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editTextCity"
android:layout_alignBottom="@+id/editTextCity"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@+id/editTextEmail"

620 | P a g e
android:text="@string/country"

android:textAppearance="?android:attr/textAppearanceMedium" />

<EditText
android:id="@+id/editTextStreet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editTextName"
android:layout_below="@+id/editTextPhone"
android:ems="10"
android:inputType="text" >

<requestFocus />
</EditText>

<EditText
android:id="@+id/editTextPhone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editTextStreet"
android:layout_below="@+id/editTextName"
android:ems="10"
android:inputType="phone|text" />

</RelativeLayout>
</ScrollView>

Following is the content of the res/value/string.xml

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


<resources>
<string name="app_name">Address Book</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="Add_New">Add New</string>
<string name="edit">Edit Contact</string>
<string name="delete">Delete Contact</string>
<string
name="title_activity_display_contact">DisplayContact</string>
<string name="name">Name</string>
<string name="phone">Phone</string>
<string name="email">Email</string>
<string name="street">Street</string>
<string name="country">City/State/Zip</string>
<string name="save">Save Contact</string>
<string name="deleteContact">Are you sure, you want to delete
it.</string>

621 | P a g e
<string name="yes">Yes</string>
<string name="no">No</string>
</resources>

Following is the content of the res/menu/main_menu.xml

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


<menu xmlns:android="http://schemas.android.com/apk/res/android" >

<item android:id="@+id/item1"
android:icon="@drawable/add"
android:title="@string/Add_New" >
</item>

</menu>

Following is the content of the res/menu/display_contact.xml

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


<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/Edit_Contact"
android:orderInCategory="100"
android:title="@string/edit"/>

<item
android:id="@+id/Delete_Contact"
android:orderInCategory="100"
android:title="@string/delete"/>

</menu>

This is the defualt AndroidManifest.xml of this project

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


<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name=".MainActivity"

622 | P a g e
android:label="@string/app_name" >

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

</activity>

<activity android:name=".DisplayContact"/>

</application>
</manifest>

Let's try to run your application. I assume you have connected your actual
Android Mobile device with your computer. To run the app from Android studio ,
open one of your project's activity files and click Run icon from the tool bar.
Before starting your application,Android studio will display following window to
select an option where you want to run your Android application.

623 | P a g e
Select your mobile device as an option and then check your mobile device which
will display following screen −

Now open your optional menu, it will show as below image: Optional menu
appears different places on different versions

624 | P a g e
Click on the add button of the menu screen to add a new contact. It will display
the following screen −

625 | P a g e
It will display the following fields. Please enter the required information and click
on save contact. It will bring you back to main screen.

626 | P a g e
Now our contact sai has been added.In order to see that where is your database
is created. Open your android studio, connect your mobile.
Go tools/android/android device monitor. Now browse the file explorer tab.
Now browse this
folder /data/data/<your.package.name>/databases<database-name>.

627 | P a g e
Android - Support Library
When you develop an app on a latest version of android like 5.x and you also
want it to run on those devices which are running older versions of android like
3.2 e.t.c. you can't do that until you add backward compatibility to your code.

To provide this backward compatibility android provides you the Android


Support Library package. The Android Support Library package is a set of code
libraries that provide backward-compatible versions of Android framework APIs
as well as features that are only available through the library APIs. Each Support
Library is backward-compatible to a specific Android API level.

Including the Support Libraries in your Android project is considered a best


practice for application developers, depending on the range of platform versions
your app is targeting and the APIs that it uses.

Support Library Features


The Android Support Library package contains several libraries that can be
included in your application. Each of these libraries supports a specific range of
Android platform versions and set of features.

In order to effectively use the libraries, it is important to consider that which API
level you want to target as each library supports different API level.

Following is a brief description of android support libraries and API level they
support.

Sr.N
Version & Features
o

1 v4 Support Library
This library is designed to be used with Android 1.6 (API level 4) and higher.

v7 Support Library
2 There are several libraries designed to be used with Android 2.1 (API level 7)
and higher.

3 v8 Support Library
This library is designed to be used with Android (API level 8) and higher.

4 v13 Support Library


This library is designed to be used for Android 3.2 (API level 13) and higher.

628 | P a g e
Please Remember that use of Android Support Library in your app code is
encouraged and preferred. By using these libraries you can increase your target
market and target audience.

Downloading the Support Libraries


Please note that before installing the support library packages you should be
clear that what feature you want to use in your app.

The Android Support Library package is available through the Android SDK
Manager.

Follow the following steps to download the support library package through the
SDK Manager.

 Start the android SDK Manager.


 In the SDK Manager window, scroll to the end of the Packages list, find the
Extras folder.
 Select the Android Support Library item.
 Click the Install packages button.

After downloading, the tool installs the Support Library files to your existing
Android SDK directory. The library files are located in the following subdirectory
of your SDK: /extras/android/support/ directory.

629 | P a g e
Choosing Support Libraries
Before adding a Support Library to your application, decide what features you
want to include and the lowest Android versions you want to support.

Changes in Android build.gradle


If you are increasing the backward compatibility of your existing application to
an earlier version of the Android API with the Support Library, make sure to
update your application's build.gradle. Specifically, you should update
the compileSdkVersion element in the build.gradle to the new, lower version
number, as shown below −
android {
compileSdkVersion 24
buildToolsVersion "24.0.1"

defaultConfig {
applicationId "com.example.tutorialspoint7.myapplication"
minSdkVersion 23
targetSdkVersion 24
versionCode 1
versionName "1.0"
}

buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-
android.txt'), 'proguard-rules.pro'
}
}
}

This change tells Google Playstore app that your application can be installed on
devices with Android minimum version of 23.

Android - Testing
The Android framework includes an integrated testing framework that helps you
test all aspects of your application and the SDK tools include tools for setting up
and running test applications. Whether you are working in Eclipse with ADT or
working from the command line, the SDK tools help you set up and run your
tests within an emulator or the device you are targeting.

630 | P a g e
Test Structure
Android's build and test tools assume that test projects are organized into a
standard structure of tests, test case classes, test packages, and test projects.

Testing Tools in android


There are many tools that can be used for testing android applications. Some
are official like Junit,Monkey and some are third party tools that can be used to
test android applications. In this chapter we are going to explain these two tools
to test android applications.

 JUnit
 Monkey

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.
631 | P a g e
JUnit
You can use the JUnit TestCase class to do unit testing on a class that doesn't
call Android APIs. TestCase is also the base class for AndroidTestCase, which you
can use to test Android-dependent objects. Besides providing the JUnit
framework, AndroidTestCase offers Android-specific setup, teardown, and helper
methods.

In order to use TestCase, extend your class with TestCase class and implement
a method call setUp(). Its syntax is given below −

public class MathTest extends TestCase {


protected double fValue1;
protected double fValue2;

protected void setUp() {


fValue1= 2.0;
fValue2= 3.0;
}
}

For each test implement a method which interacts with the fixture. Verify the
expected results with assertions specified by calling assertTrue(String, boolean)
with a boolean.

public void testAdd() {


double result= fValue1 + fValue2;
assertTrue(result == 5.0);
}

The assert methods compare values you expect from a test to the actual results
and throw an exception if the comparison fails.

Once the methods are defined you can run them. Its syntax is given below −

TestCase test= new MathTest("testAdd");


test.run();

Monkey
The UI/Application Exerciser Monkey, usually called "monkey", is a command-
line tool that sends pseudo-random streams of keystrokes, touches, and
gestures to a device. You run it with the Android Debug Bridge (adb) tool.

632 | P a g e
You use it to stress-test your application and report back errors that are
encountered. You can repeat a stream of events by running the tool each time
with the same random number seed.

Monkey features
Monkey has many features, but it can be all be summed up to these four
categories.

 Basic configuration options


 Operational constraints
 Event types and frequencies
 Debugging options

Monkey Usage
In order to use monkey, open up a command prompt and just navigate to the
following directory.

android ->sdk ->platform-tools

Once inside the directory, attach your device with the PC , and run the following
command.

adb shell monkey -p your.package.name -v 500

This command can be broken down into these steps.

 adb - Android Debug Bridge. A tool used to connect and sends commands to
your Android phone from a desktop or laptop computer.
 shell - shell is just an interface on the device that translates our commands to
system commands.
 monkey - monkey is the testing tool.
 v - v stands for verbose method.
 500- it is the frequency conut or the number of events to be sent for testing.

This is also shown in the figure −

633 | P a g e
In the above command, you run the monkey tool on the default android UI
application. Now in order to run it to your application , here what you have to
do.

finally you will get finish as shown bellow

This has also been shown in the figure below. By typing this command , you are
actually generating 500 random events for testing.

634 | P a g e
Example
The below example demonstrates the use of Testing. It crates a basic
application which can be used for monkey.

To experiment with this example, you need to run this on an actual device and
then follow the monkey steps explained in the beginning.

Ste
Description
ps

You will useAndroid studio to create an Android application under a package


1
com.tutorialspoint.myapplication.

2 Modify src/MainActivity.java file to add Activity code.

635 | P a g e
Modify layouta XML file res/layout/activity_main.xml add any GUI component if
3
required.

4 Create src/second.java file to add Activity code.

5 Modify layout XML file res/layout/view.xml add any GUI component if required.

Run the application and choose a running android device and install the application
6
on it and verify the results.

Here is the content of MainActivity.java.


package com.tutorialspoint.myapplication;

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

public class MainActivity extends AppCompatActivity {


Button b1;
@Override

protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button);
}

public void button(View v){


Intent in =new Intent(MainActivity.this,second.class);
startActivity(in);
}

}
Here is the content of second.java.
package com.tutorialspoint.myapplication;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class second extends Activity{

636 | P a g e
@Override

protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.view);
Button b1=(Button)findViewById(R.id.button2);

b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

Toast.makeText(second.this,"Thanks",Toast.LENGTH_SHORT).show();
}
});
}
}
Here is the content of activity_main.xml.
In the below code abc indicates the logo of tutorialspoint.com

<?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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="UI Animator Viewer"
android:id="@+id/textView"
android:textSize="25sp"
android:layout_centerHorizontal="true" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_alignRight="@+id/textView"
android:layout_alignEnd="@+id/textView"
android:textColor="#ff36ff15"
android:textIsSelectable="false"

637 | P a g e
android:textSize="35dp" />

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:onClick="button"
android:id="@+id/button"
android:layout_below="@+id/imageView"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp" />

</RelativeLayout>
Here is the content of view.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">

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="button"
android:id="@+id/button2"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point "
android:id="@+id/textView3"
android:textColor="#ff3aff22"
android:textSize="35dp"
android:layout_above="@+id/button2"
android:layout_centerHorizontal="true"
android:layout_marginBottom="90dp" />

</RelativeLayout>
Here is the content of Strings.xml.

638 | P a g e
<resources>
<string name="app_name">My Application</string>
</resources>
Here is the content of AndroidManifest.xml.
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tutorialspoint.myapplication" >

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name=".MainActivity"
android:label="@string/app_name" >

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

</activity>

<activity android:name=".second"></activity>

</application>
</manifest>

Let's try to run your Android Testing application. I assume you have connected
your actual Android Mobile device with your computer. To run the app from
Android studio, open one of your project's activity files and click Run icon from
the toolbar. Before starting your application, Android studio will display following
window to select an option where you want to run your Android application.

639 | P a g e
Select your mobile device as an option and then check your mobile device which
will display application screen. Now just follow the steps mentioned at the top
under the monkey section in order to perform testing on this application.

Android - Text To Speech


Android allows you convert your text into voice. Not only you can convert it but
it also allows you to speak text in variety of different languages.

Android provides TextToSpeech class for this purpose. In order to use this
class, you need to instantiate an object of this class and also specify
the initListener. Its syntax is given below −

private EditText write;


ttobj=new TextToSpeech(getApplicationContext(), new
TextToSpeech.OnInitListener() {

640 | P a g e
@Override
public void onInit(int status) {
}
});

In this listener, you have to specify the properties for TextToSpeech object ,
such as its language ,pitch e.t.c. Language can be set by
calling setLanguage() method. Its syntax is given below −

ttobj.setLanguage(Locale.UK);

The method setLanguage takes an Locale object as parameter. The list of some
of the locales available are given below −

Sr.No Locale

1 US

2 CANADA_FRENCH

3 GERMANY

4 ITALY

5 JAPAN

6 CHINA

Once you have set the language, you can call speak method of the class to
speak the text. Its syntax is given below −

ttobj.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);

Apart from the speak method, there are some other methods available in the
TextToSpeech class. They are listed below −

Sr.N
Method & description
o

addSpeech(String text, String filename)


1
This method adds a mapping between a string of text and a sound file.

getLanguage()
2
This method returns a Locale instance describing the language.

641 | P a g e
isSpeaking()
3
This method checks whether the TextToSpeech engine is busy speaking.

setPitch(float pitch)
4
This method sets the speech pitch for the TextToSpeech engine.

setSpeechRate(float speechRate)
5
This method sets the speech rate.

shutdown()
6
This method releases the resources used by the TextToSpeech engine.

stop()
7
This method stop the speak.

Example
The below example demonstrates the use of TextToSpeech class. It crates a
basic application that allows you to set write text and speak it.

To experiment with this example , you need to run this on an actual device.

Ste
Description
ps

You will use Android studio to create an Android application under a package
1
com.example.sairamkrishna.myapplication.

2 Modify src/MainActivity.java file to add TextToSpeech code.

Modify layout XML file res/layout/activity_main.xml add any GUI component


3
if required.

Run the application and choose a running android device and install the
4
application on it and verify the results.

Here is the content of src/MainActivity.java.

package com.example.sairamkrishna.myapplication;

import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.widget.Button;

642 | P a g e
import android.widget.EditText;
import java.util.Locale;
import android.widget.Toast;

public class MainActivity extends Activity {


TextToSpeech t1;
EditText ed1;
Button b1;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed1=(EditText)findViewById(R.id.editText);
b1=(Button)findViewById(R.id.button);

t1=new TextToSpeech(getApplicationContext(), new


TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR) {
t1.setLanguage(Locale.UK);
}
}
});

b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String toSpeak = ed1.getText().toString();
Toast.makeText(getApplicationContext(),
toSpeak,Toast.LENGTH_SHORT).show();
t1.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
}
});
}

public void onPause(){


if(t1 !=null){
t1.stop();
t1.shutdown();
}
super.onPause();
}
}

Here is the content of activity_main.xml

In the following code abcindicates the logo of tutorialspoint.com


643 | P a g e
<?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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:transitionGroup="true">

<TextView android:text="Text to Speech"


android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textview"
android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:id="@+id/textView"
android:layout_below="@+id/textview"
android:layout_centerHorizontal="true"
android:textColor="#ff7aff24"
android:textSize="35dp" />

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:theme="@style/Base.TextAppearance.AppCompat" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_below="@+id/imageView"
android:layout_marginTop="46dp"
android:hint="Enter Text"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"

644 | P a g e
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textColor="#ff7aff10"
android:textColorHint="#ffff23d1" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text to Speech"
android:id="@+id/button"
android:layout_below="@+id/editText"
android:layout_centerHorizontal="true"
android:layout_marginTop="46dp" />

</RelativeLayout>

Here is the content of Strings.xml.

<resources>
<string name="app_name">My Application</string>
</resources>

Here is the content of AndroidManifest.xml

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


<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name=".MainActivity"
android:label="@string/app_name" >

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

</activity>

</application>
</manifest>

645 | P a g e
Let's try to run your application. I assume you have connected your actual
Android Mobile device with your computer. To run the app from Android studio,
open one of your project's activity files and click Run icon from the toolbar.
Before starting your application, android studio will display following window to
select an option where you want to run your Android application.

Select your mobile device as an option and then check your mobile device which
will display following screen.

646 | P a g e
Now just type some text in the field and click on the text to speech button
below. A notification would appear and text will be spoken. It is shown in the
image below −

647 | P a g e
Now type something else and repeat the step again with different locale. You
will again hear sound. This is shown below −

648 | P a g e
649 | P a g e
Android - TextureView
If you want to display a live video stream or any content stream such as video or
an OpenGL scene, you can use TextureView provided by android in order to do
that.

In order to use TextureView, all you need to do is get its SurfaceTexture.The


SurfaceTexture can then be used to render content. In order to do this, you just
need to do instantiate an object of this class and implement
SurfaceTextureListener interface. Its syntax is given below −

private TextureView myTexture;


public class MainActivity extends Activity implements
SurfaceTextureListener{
protected void onCreate(Bundle savedInstanceState) {
myTexture = new TextureView(this);
myTexture.setSurfaceTextureListener(this);
setContentView(myTexture);
}
}

After that, what you need to do is to override its methods. The methods are
listed as follows −

@Override
public void onSurfaceTextureAvailable(SurfaceTexture arg0, int
arg1, int arg2) {
}

@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture arg0) {
}

@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture arg0, int
arg1,int arg2) {
}

@Override
public void onSurfaceTextureUpdated(SurfaceTexture arg0) {
}

Any view that is displayed in the texture view can be rotated and its alpha
property can be adjusted by using setAlpha and setRotation methods. Its
syntax is given below −

myTexture.setAlpha(1.0f);

650 | P a g e
myTexture.setRotation(90.0f);

Apart from these methods, there are other methods available in TextureView
class. They are listed below −

Sr.N
Method & description
o

getSurfaceTexture()
1
This method returns the SurfaceTexture used by this view.

getBitmap(int width, int height)


2 This method returns Returns a Bitmap representation of the content of the
associated surface texture.

getTransform(Matrix transform)
3
This method returns the transform associated with this texture view.

isOpaque()
4
This method indicates whether this View is opaque.

lockCanvas()
5
This method start editing the pixels in the surface

setOpaque(boolean opaque)
6
This method indicates whether the content of this TextureView is opaque.

setTransform(Matrix transform)
7
This method sets the transform to associate with this texture view.

unlockCanvasAndPost(Canvas canvas)
8
This method finish editing pixels in the surface.

Example
The below example demonstrates the use of TextureView class. It crates a basic
application that allows you to view camera inside a texture view and change its
angle , orientation e.t.c.

To experiment with this example , you need to run this on an actual device on
which camera is present.

Ste
Description
ps

651 | P a g e
You will use android studio IDE to create an Android application and name it
1
as TextureView under a package com.example.textureview.

2 Modify src/MainActivity.java file to add Activity code.

Modify layout XML file res/layout/activity_main.xml add any GUI component


3
if required.

Run the application and choose a running android device and install the
5
application on it and verify the results.

Here is the content of src/com.example.textureview/MainActivity.java.

package com.example.textureview;

import java.io.IOException;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.os.Bundle;

import android.view.Gravity;
import android.view.Menu;
import android.view.TextureView;
import android.view.TextureView.SurfaceTextureListener;
import android.view.View;
import android.widget.FrameLayout;

public class MainActivity extends Activity implements


SurfaceTextureListener {
private TextureView myTexture;
private Camera mCamera;

@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

myTexture = new TextureView(this);


myTexture.setSurfaceTextureListener(this);
setContentView(myTexture);
}

@Override

652 | P a g e
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it
is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@SuppressLint("NewApi")
@Override
public void onSurfaceTextureAvailable(SurfaceTexture arg0, int
arg1, int arg2) {
mCamera = Camera.open();
Camera.Size previewSize =
mCamera.getParameters().getPreviewSize();

myTexture.setLayoutParams(new FrameLayout.LayoutParams(
previewSize.width, previewSize.height, Gravity.CENTER));

try {
mCamera.setPreviewTexture(arg0);
} catch (IOException t) {
}

mCamera.startPreview();
myTexture.setAlpha(1.0f);
myTexture.setRotation(90.0f);
}

@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture arg0) {
mCamera.stopPreview();
mCamera.release();
return true;
}

@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture arg0, int
arg1,
int arg2) {
// TODO Auto-generated method stub
}

@Override
public void onSurfaceTextureUpdated(SurfaceTexture arg0) {
// TODO Auto-generated method stub
}
}

Here is the content of activity_main.xml

653 | P a g e
<?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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextureView
android:id="@+id/textureView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>

Here is the default content of AndroidManifest.xml

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


<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.textureview" >

<uses-permission android:name="android.permission.CAMERA"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name="com.example.textureview.MainActivity"
android:label="@string/app_name" >

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

</activity>

</application>
</manifest>

654 | P a g e
Let's try to run your TextureView application. I assume you have connected your
actual Android Mobile device with your computer. To run the app from Android
studio, open one of your project's activity files and click Run icon from the
toolbar. Before starting your application, Android studio will display following
window to select an option where you want to run your Android application.

Select your mobile device as an option and then check your mobile device which
will display following screen. This screen has alpha property set to 0.5 and
rotation set to 45.

655 | P a g e
This screen has alpha property set to 1.5 and rotation set to 45.

656 | P a g e
This screen has alpha property set to 1.0 and rotation set to 90.

657 | P a g e
Android - Twitter Integration
Android allows your application to connect to twitter and share data or any kind
of updates on twitter. This chapter is about integrating twitter into your
application.

There are two ways through which you can integrate twitter and share
something from your application. These ways are listed below −

 Twitter SDK (Twitter4J)


 Intent Share

Integrating Twitter SDK

658 | P a g e
This is the first way of connecting with Twitter. You have to register your
application and then receive some Application Id, and then you have to
download the twitter SDK and add it to your project. The steps are listed below

Registering your application


Create a new twitter application at dev.twitter.com/apps/new and fill all the
information. It is shown below −

Now under settings tab, change the access to read,write and access messages
and save the settings. It is shown below −

659 | P a g e
If everything works fine, you will receive an consumer ID with the secret. Just
copy the application id and save it somewhere. It is shown in the image below −

Downloading SDK and integrating it


Download twitter sdk here. Copy the twitter4J jar into your project libs folder.

Posting tweets on twitter application


Once everything is complete , you can run the twitter 4J samples which can be
found here.
In order to use twitter, you need to instantiate an object of twitter class.It can be
done by calling the static method getsingleton(). Its syntax is given below.
// The factory instance is re-usable and thread safe.
Twitter twitter = TwitterFactory.getSingleton();

In order to update the status , you can call updateStatus() method. Its syntax is
given below −

Status status = twitter.updateStatus(latestStatus);

660 | P a g e
System.out.println("Successfully updated the status to [" +
status.getText() + "].");

Intent share
Intent share is used to share data between applications. In this strategy, we will
not handle the SDK stuff, but let the twitter application handles it. We will simply
call the twitter application and pass the data to share. This way, we can share
something on twitter.

Android provides intent library to share data between activities and applications.
In order to use it as share intent, we have to specify the type of the share intent
to ACTION_SEND. Its syntax is given below −
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);

Next thing you need to is to define the type of data to pass, and then pass the
data. Its syntax is given below −

shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, "Hello, from
tutorialspoint");
startActivity(Intent.createChooser(shareIntent, "Share your
thoughts"));

Apart from the these methods, there are other methods available that allows
intent handling. They are listed below −

Sr.N
Method & description
o

1 addCategory(String category)
This method add a new category to the intent.

2 createChooser(Intent target, CharSequence title)


Convenience function for creating a ACTION_CHOOSER Intent

getAction()
3 This method retrieve the general action to be performed, such as
ACTION_VIEW

getCategories()
4 This method return the set of all categories in the intent and the current scaling
event

661 | P a g e
5 putExtra(String name, int value)
This method add extended data to the intent.

toString()
6 This method returns a string containing a concise, human-readable description
of this object

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

Example
Here is an example demonstrating the use of IntentShare to share data on
twitter. It creates a basic application that allows you to share some text on
twitter.

To experiment with this example , you can run this on an actual device or in an
emulator.

Ste
Description
ps

You will use Android studio to create an Android application under a package
1
com.example.sairamkrishna.myapplication.

2 Modify src/MainActivity.java file to add necessary code.

3 Modify the res/layout/activity_main to add respective XML components

Run the application and choose a running android device and install the application
4
on it and verify the results

Following is the content of the modified MainActivity.java.


package com.example.sairamkrishna.myapplication;

import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;

662 | P a g e
import android.widget.Button;
import android.widget.ImageView;
import java.io.FileNotFoundException;
import java.io.InputStream;

public class MainActivity extends ActionBarActivity {


private ImageView img;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

img=(ImageView)findViewById(R.id.imageView);
Button b1=(Button)findViewById(R.id.button);

b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
Uri screenshotUri =
Uri.parse("android.resource://comexample.sairamkrishna.myapplicatio
n/*");

try {
InputStream stream =
getContentResolver().openInputStream(screenshotUri);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sharingIntent.setType("image/jpeg");
sharingIntent.putExtra(Intent.EXTRA_STREAM,
screenshotUri);
startActivity(Intent.createChooser(sharingIntent,
"Share image using"));
}
});
}
}
Following is the modified content of the xml res/layout/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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"

663 | P a g e
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp"
android:text="Twitter share " />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials Point"
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:textSize="35dp"
android:textColor="#ff16ff01" />

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true"
android:src="@drawable/abc"/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Share"
android:id="@+id/button"
android:layout_marginTop="61dp"
android:layout_below="@+id/imageView"
android:layout_centerHorizontal="true" />

</RelativeLayout>
Following is the content of AndroidManifest.xml file.
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >

<application
android:allowBackup="true"

664 | P a g e
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name=".MainActivity"
android:label="@string/app_name" >

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

</activity>

</application>
</manifest>

Let's try to run your application. I assume you have connected your actual
Android Mobile device with your computer. To run the app from Android studio,
open one of your project's activity files and click Run icon from the toolbar.
Before starting your application,Android studio will display following window to
select an option where you want to run your Android application.

665 | P a g e
Select your mobile device as an option and then check your mobile device which
will display your default screen −

666 | P a g e
Now just tap on the button and you will see a list of share providers.

667 | P a g e
Now just select twitter from that list and then write any message. It is shown in
the image below −

668 | P a g e
Now just select the tweet button and then it would be post on your twitter page.
It is shown below −

669 | P a g e
Android - UI Design
In this chapter we will look at the different UI components of android screen.
This chapter also covers the tips to make a better UI design and also explains
how to design a UI.

UI screen components
A typical user interface of an android application consists of action bar and the
application content area.

670 | P a g e
 Main Action Bar
 View Control
 Content Area
 Split Action Bar

These components have also been shown in the image below −

Understanding Screen Components


The basic unit of android application is the activity. A UI is defined in an xml file.
During compilation, each element in the XML is compiled into equivalent Android
GUI class with attributes represented by methods.

View and ViewGroups


An activity is consist of views. A view is just a widget that appears on the
screen. It could be button e.t.c. One or more views can be grouped together into
one GroupView. Example of ViewGroup includes layouts.

Types of layout
There are many types of layout. Some of which are listed below −

 Linear Layout
 Absolute Layout
 Table Layout
 Frame Layout
 Relative Layout

671 | P a g e
Linear Layout
Linear layout is further divided into horizontal and vertical layout. It means it
can arrange views in a single column or in a single row. Here is the code of
linear layout(vertical) that includes a text view.

<?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” >

<TextView
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”@string/hello” />
</LinearLayout>

AbsoluteLayout
The AbsoluteLayout enables you to specify the exact location of its children. It
can be declared like this.

<AbsoluteLayout
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
xmlns:android=”http://schemas.android.com/apk/res/android” >

<Button
android:layout_width=”188dp”
android:layout_height=”wrap_content”
android:text=”Button”
android:layout_x=”126px”
android:layout_y=”361px” />
</AbsoluteLayout>

TableLayout
The TableLayout groups views into rows and columns. It can be declared like
this.

<TableLayout
xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_height=”fill_parent”
android:layout_width=”fill_parent” >

672 | P a g e
<TableRow>
<TextView
android:text=”User Name:”
android:width =”120dp”
/>

<EditText
android:id=”@+id/txtUserName”
android:width=”200dp” />
</TableRow>

</TableLayout>

RelativeLayout
The RelativeLayout enables you to specify how child views are positioned
relative to each other.It can be declared like this.

<RelativeLayout
android:id=”@+id/RLayout”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
xmlns:android=”http://schemas.android.com/apk/res/android” >
</RelativeLayout>

FrameLayout
The FrameLayout is a placeholder on screen that you can use to display a single
view. It can be declared like this.

<?xml version=”1.0” encoding=”utf-8”?>


<FrameLayout
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_alignLeft=”@+id/lblComments”
android:layout_below=”@+id/lblComments”
android:layout_centerHorizontal=”true” >

<ImageView
android:src = “@drawable/droid”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content” />
</FrameLayout>

Apart form these attributes, there are other attributes that are common in all
views and ViewGroups. They are listed below −

673 | P a g e
Sr.N
View & description
o

1 layout_width
Specifies the width of the View or ViewGroup

2 layout_height
Specifies the height of the View or ViewGroup

3 layout_marginTop
Specifies extra space on the top side of the View or ViewGroup

4 layout_marginBottom
Specifies extra space on the bottom side of the View or ViewGroup

5 layout_marginLeft
Specifies extra space on the left side of the View or ViewGroup

6 layout_marginRight
Specifies extra space on the right side of the View or ViewGroup

7 layout_gravity
Specifies how child Views are positioned

layout_weight
8 Specifies how much of the extra space in the layout should be allocated to the
View

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

Units of Measurement
When you are specifying the size of an element on an Android UI, you should
remember the following units of measurement.

Sr.N
Unit & description
o

1 dp
Density-independent pixel. 1 dp is equivalent to one pixel on a 160 dpi screen.

674 | P a g e
sp
2 Scale-independent pixel. This is similar to dp and is recommended for
specifying font sizes

pt
3 Point. A point is defined to be 1/72 of an inch, based on the physical screen
size.

4 px
Pixel. Corresponds to actual pixels on the screen

Screen Densities
Sr.No Density & DPI

1 Low density (ldpi)


120 dpi

2 Medium density (mdpi)


160 dpi

3 High density (hdpi)


240 dpi

4 Extra High density (xhdpi)


320 dpi

Optimizing layouts
Here are some of the guidelines for creating efficient layouts.
 Avoid unnecessary nesting
 Avoid using too many Views
 Avoid deep nesting

Android - UI Patterns
In this chapter we will look at the different UI Patterns which are available by
android to design apps that behave in a consistent and foreseeable way.

UI Patterns components
A good android application should follow following UI patterns −

675 | P a g e
 Action Bar
 Confirming and Acknowledging
 Settings
 Help
 Selection

Now we will discuss the above mentioned UI Patterns in detail.

Action Bar
The action bar is a dedicated bar at the top of each screen that is generally
persistent throughout the app. It provides you several key function which are as
following −

 Makes important actions prominent and accessible


 Supports consistent navigation and view switching within apps
 Reduces clutter by providing an action overflow for rarely used actions
 Provides a dedicated space for giving your app an identity

Action Bar Components


Action Bar has four major components which can be seen in the following image.

These components name and functionality is discussed below −

Sr.N
Action Bar Components
o

App Icon
1 The app icon establishes your app's identity. It can be replaced with a different
logo or branding if you wish.

View control
2 If your app displays data in different views, this segment of the action bar
allows users to switch views.

3 Action buttons
Show the most important actions of your app in the actions section.

4 Action overflow

676 | P a g e
Move less often used actions to the action overflow.

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

Confirming and Acknowledging


When a user invokes a action on your app's UI, it is a good practice
to confirm or acknowledge that action through a toast or a dialog box.

There is a difference between Confirming and Acknowledging.

Confirming
When we ask the user to verify that they truly want to proceed with a action
that they just invoked, it is called confirming. As you can see in the following
image −

Acknowledging
When we display a toast to let the user know that the action they just invoked
has been completed, this is called acknowledging, As you can see in the
following image −

Settings
The place in your app where users can indicate their preferences for how your
app should behave is called as Settings. The use of settings can benefit your
app's users in the following ways −

 Settings help user to predetermine that what will happen in certain situations
 Use of settings in your app help users to feel in control

677 | P a g e
Placement of Settings
It is preferred by the android developers to always make "settings" option part
of action overflow which is mentioned above. As users did not frequently use
this option so the common practice is to place it below all other items except
"Help". As you can see in the following picture −

Help
Some of your app users may run into some difficulty while using your app and
they will be looking for some answers, and they want them within the app. So
always make "help" part of your app.

Placement of Help
Like "Settings" the standard design of placing "Help" option is in action
overflow. Always make it very last item in the menu and always label it "Help".
Even if your app screen has no other action overflow items, "Help" should
appear there. As you can see this in the following picture −

Selection
Android 3.0 version changed the long press gesture to the global gesture to
select data. The long press gesture is now used to select data, combining
contextual actions and selection management functions for selected data into a
new element called the contextual action bar (CAB).

678 | P a g e
Using Contextual Action Bar (CAB)
The selection CAB is a temporary action bar that overlays your app's current
action bar while data is selected. It appears after the user long presses on a
selectable data item. As you can see in the following picture −

From the CAB bar user can perform following actions −

 Select additional data items by touching them


 Trigger an action from the CAB that applies to all highlighted data items
 Dismiss the CAB via the navigation bar's Back button or the CAB's checkmark
button

Android - UI Testing
Android SDK provides the following tools to support automated, functional UI
testing on your application.

 uiautomatorviewer
 uiautomator

uiautomatorviewer
A GUI tool to scan and analyse the UI components of an Android application.

The uiautomatorviewer tool provides a convenient visual interface to inspect the


layout hierarchy and view the properties of the individual UI components that
are displayed on the test device. Using this information, you can later create
uiautomator tests with selector objects that target specific UI components to
test.

To analyse the UI components of the application that you want to test, perform
the following steps after installing the application given in the example.

 Connect your Android device to your development machine


 Open a terminal window and navigate to <android-sdk>/tools/
 Run the tool with this command
uiautomatorviewer

Commands would be followed as shown below

679 | P a g e
You will see the following window appear. It is the default window of the UI
Automator Viewer.

680 | P a g e
 Click on the devices icon at the top right corner. It will start taking the UI XML
snapshot of the screen currently opened in the device. It would be something
like this.

After that, you will see the snapshot of your device screen in the
uiautomatorviewer window.

681 | P a g e
On the right side of this window, you will see two partitions. The upper partition
explains the Nodes structure, the way the UI components are arranged and
contained. Clicking on each node gives detail in the lower partition.

As an example, consider the below figure. When you click on the button, you
can see in the upper partition that Button is selected, and in the lower partition,
its details are shown. Since this button is click able, that's why its property of
click able is set to true.

682 | P a g e
UI Automator Viewer also helps you to examine your UI in different orientations.
For example, just change your device orientation to landscape, and again
capture the screen shot. It is shown in the figure below −

683 | P a g e
uiautomator
Now you can create your own test cases and run it with uiautomatorviewer to
examine them. In order to create your own test case, you need to perform the
following steps −

 From the Project Explorer, right-click on the new project that you created, then
select Properties > Java Build Path, and do the following −
 Click Add Library > JUnit then select JUnit3 to add JUnit support.
 Click Add External JARs... and navigate to the SDK directory. Under the
platforms directory, select the latest SDK version and add both the
uiautomator.jar and android.jar files.
 Extend your class with UiAutomatorTestCase
 Right the necessary test cases.
 Once you have coded your test, follow these steps to build and deploy your test
JAR to your target Android test device.
 Create the required build configuration files to build the output JAR. To generate
the build configuration files, open a terminal and run the following command:
<android-sdk>/tools/android create uitest-project -n <name> -t 1 -p <path>
 The <name> is the name of the project that contains your uiautomator test
source files, and the <path> is the path to the corresponding project directory.

684 | P a g e
 From the command line, set the ANDROID_HOME variable.
set ANDROID_HOME=<path_to_your_sdk>
 Go to the project directory where your build.xml file is located and build your
test JAR.
ant build
 Deploy your generated test JAR file to the test device by using the adb push
command.
adb push <path_to_output_jar> /data/local/tmp/
 Run your test by following command −
adb shell uiautomator runtest LaunchSettings.jar -c
com.uia.example.my.LaunchSettings

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

Example
The below example demonstrates the use of UITesting. It crates a basic
application which can be used for uiautomatorviewer.

To experiment with this example, you need to run this on an actual device and
then follow the uiautomatorviewer steps explained in the beginning.

Ste
Description
ps

You will use Android studio to create an Android application under a package
1
com.tutorialspoint.myapplication.

2 Modify src/MainActivity.java file to add Activity code.

Modify layout XML file res/layout/activity_main.xml add any GUI component if


3
required.

4 Create src/second.java file to add Activity code.

5 Modify layout XML file res/layout/view.xml add any GUI component if required.

6 Run the application and choose a running android device and install the application

685 | P a g e
on it and verify the results.

Here is the content of MainActivity.java.


package com.tutorialspoint.myapplication;

import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends ActionBarActivity {


Button b1;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

b1=(Button)findViewById(R.id.button);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent in =new Intent(MainActivity.this,second.class);
startActivity(in);
}
});
}
}
Here is the content of second.java.
package com.tutorialspoint.myapplication;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class second extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
Button b1=(Button)findViewById(R.id.button2);

b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

686 | P a g e
Toast.makeText(second.this,"Thanks",Toast.LENGTH_LONG).show();
}
});
}
}
Here is the content of activity_main.xml
In the following code abc indicates the logo of tutorialspoint.com

<?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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="UI Animator Viewer"
android:id="@+id/textView"
android:textSize="25sp"
android:layout_centerHorizontal="true" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_alignRight="@+id/textView"
android:layout_alignEnd="@+id/textView"
android:textColor="#ff36ff15"
android:textIsSelectable="false"
android:textSize="35dp" />

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true" />

687 | P a g e
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:id="@+id/button"
android:layout_marginTop="98dp"
android:layout_below="@+id/imageView"
android:layout_centerHorizontal="true" />

</RelativeLayout>
Here is the content of view.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Button"
android:id="@+id/button2"
android:layout_gravity="center_horizontal"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Here is the content of Strings.xml.
<resources>
<string name="app_name">My Application</string>
</resources>
Here is the content of AndroidManifest.xml.
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tutorialspoint.myapplication" >

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name=".MainActivity"
android:label="@string/app_name" >

<intent-filter>

688 | P a g e
<action android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>

</activity>

<activity android:name=".second"></activity>

</application>
</manifest>

Let's try to run your UI Testing application. I assume you have connected your
actual Android Mobile device with your computer. To run the app from Android
studio, open one of your project's activity files and click Run icon from the tool
bar. Before starting your application, Android studio will display following
window to select an option where you want to run your Android application.

Select your mobile device as an option and then check your mobile device which
will display application screen. Now just follow the steps mentioned at the top
under the ui automator viewer section in order to perform ui testing on this
application.

689 | P a g e
Android - WebView
WebView is a view that display web pages inside your application. You can also
specify HTML string and can show it inside your application using WebView.
WebView makes turns your application to a web application.

In order to add WebView to your application, you have to


add <WebView> element to your xml layout file. Its syntax is as follows −

<WebView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>

In order to use it, you have to get a reference of this view in Java file. To get a
reference, create an object of the class WebView. Its syntax is −

WebView browser = (WebView) findViewById(R.id.webview);

In order to load a web url into the WebView, you need to call a
method loadUrl(String url) of the WebView class, specifying the required url.
Its syntax is:

browser.loadUrl("https://www.tutorialspoint.com");

Apart from just loading url, you can have more control over your WebView by
using the methods defined in WebView class. They are listed as follows −

Sr.N
Method & Description
o

canGoBack()
1
This method specifies the WebView has a back history item.

canGoForward()
2
This method specifies the WebView has a forward history item.

clearHistory()
3
This method will clear the WebView forward and backward history.

4 destroy()

690 | P a g e
This method destroy the internal state of WebView.

findAllAsync(String find)
5
This method find all instances of string and highlight them.

getProgress()
6
This method gets the progress of the current page.

getTitle()
7
This method return the title of the current page.

getUrl()
8
This method return the url of the current page.

If you click on any link inside the webpage of the WebView, that page will not be
loaded inside your WebView. In order to do that you need to extend your class
from WebViewClient and override its method. Its syntax is −

private class MyBrowser extends WebViewClient {


@Override
public boolean shouldOverrideUrlLoading(WebView view, String
url) {
view.loadUrl(url);
return true;
}
}

Example
Here is an example demonstrating the use of WebView Layout. It creates a basic
web application that will ask you to specify a url and will load this url website in
the WebView.

To experiment with this example, you need to run this on an actual device on
which internet is running.

Ste
Description
ps

You will use Android studio to create an Android application under a package
1
com.example.sairamkrishna.myapplication.

2 Modify src/MainActivity.java file to add WebView code.

3 Modify the res/layout/activity_main to add respective XML components

691 | P a g e
4 Modify the AndroidManifest.xml to add the necessary permissions

Run the application and choose a running android device and install the
5
application on it and verify the results.

Following is the content of the modified main activity


file src/MainActivity.java.

package com.example.sairamkrishna.myapplication;
import android.app.Activity;
import android.os.Bundle;

import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {


Button b1;
EditText ed1;

private WebView wv1;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

b1=(Button)findViewById(R.id.button);
ed1=(EditText)findViewById(R.id.editText);

wv1=(WebView)findViewById(R.id.webView);
wv1.setWebViewClient(new MyBrowser());

b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String url = ed1.getText().toString();

wv1.getSettings().setLoadsImagesAutomatically(true);
wv1.getSettings().setJavaScriptEnabled(true);
wv1.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
wv1.loadUrl(url);
}
});
}

692 | P a g e
private class MyBrowser extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String
url) {
view.loadUrl(url);
return true;
}
}
}

Following is the modified content of the xml res/layout/activity_main.xml.

In the following code abc indicates the logo of tutorialspoint.com


<?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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView android:text="WebView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textview"
android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:id="@+id/textView"
android:layout_below="@+id/textview"
android:layout_centerHorizontal="true"
android:textColor="#ff7aff24"
android:textSize="35dp" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:hint="Enter Text"

693 | P a g e
android:focusable="true"
android:textColorHighlight="#ff7eff15"
android:textColorHint="#ffff25e6"
android:layout_marginTop="46dp"
android:layout_below="@+id/imageView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignRight="@+id/imageView"
android:layout_alignEnd="@+id/imageView" />

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter"
android:id="@+id/button"
android:layout_alignTop="@+id/editText"
android:layout_toRightOf="@+id/imageView"
android:layout_toEndOf="@+id/imageView" />

<WebView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/webView"
android:layout_below="@+id/button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true" />

</RelativeLayout>

Following is the content of the res/values/string.xml.

<resources>
<string name="app_name">My Application</string>
</resources>

Following is the content of AndroidManifest.xml file.

694 | P a g e
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name=".MainActivity"
android:label="@string/app_name" >

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

</activity>

</application>
</manifest>

Let's try to run your WebView application. To run the app from Android studio,
open one of your project's activity files and click Run icon from the toolbar.
Android studio will display as shown below

Now just specify a url on the url field and press the browse button that
appears,to launch the website. But before that please make sure that you are
connected to the internet. After pressing the button, the following screen would
appear −

695 | P a g e
Note. By just changing the url in the url field, your WebView will open your
desired website.

696 | P a g e
Above image shows webview of tutorialspoint.com

697 | P a g e
Android - Wi-Fi
Android allows applications to access to view the access the state of the
wireless connections at very low level. Application can access almost all the
information of a wifi connection.

The information that an application can access includes connected network's


link speed,IP address, negotiation state, other networks information.
Applications can also scan, add, save, terminate and initiate Wi-Fi connections.

Android provides WifiManager API to manage all aspects of WIFI connectivity.


We can instantiate this class by calling getSystemService method. Its syntax
is given below −

WifiManager mainWifiObj;
mainWifiObj = (WifiManager) getSystemService(Context.WIFI_SERVICE);

In order to scan a list of wireless networks, you also need to register your
BroadcastReceiver. It can be registered using registerReceiver method with
argument of your receiver class object. Its syntax is given below −

class WifiScanReceiver extends BroadcastReceiver {


public void onReceive(Context c, Intent intent) {
}
}

WifiScanReceiver wifiReciever = new WifiScanReceiver();


registerReceiver(wifiReciever, new
IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));

The wifi scan can be start by calling the startScan method of the WifiManager
class. This method returns a list of ScanResult objects. You can access any
object by calling the get method of list. Its syntax is given below −

List<ScanResult> wifiScanList = mainWifiObj.getScanResults();


String data = wifiScanList.get(0).toString();

Apart from just Scanning, you can have more control over your WIFI by using the
methods defined in WifiManager class. They are listed as follows −

Sr.N
Method & Description
o

addNetwork(WifiConfiguration config)
1
This method add a new network description to the set of configured networks.

698 | P a g e
createWifiLock(String tag)
2
This method creates a new WifiLock.

disconnect()
3
This method disassociate from the currently active access point.

enableNetwork(int netId, boolean disableOthers)


4
This method allow a previously configured network to be associated with.

getWifiState()
5
This method gets the Wi-Fi enabled state

isWifiEnabled()
6
This method return whether Wi-Fi is enabled or disabled.

setWifiEnabled(boolean enabled)
7
This method enable or disable Wi-Fi.

updateNetwork(WifiConfiguration config)
8
This method update the network description of an existing configured network.

Example
Here is an example demonstrating the use of WIFI. It creates a basic application
that open your wifi and close your wifi

To experiment with this example, you need to run this on an actual device on
which wifi is turned on.

Ste
Description
ps

You will use Android studio to create an Android application under a package
1
com.example.sairamkrishna.myapplication.

2 Modify src/MainActivity.java file to add WebView code.

3 Modify the res/layout/activity_main to add respective XML components

4 Modify the AndroidManifest.xml to add the necessary permissions

Run the application and choose a running android device and install the
5
application on it and verify the results.

699 | P a g e
Following is the content of the modified main activity
file src/MainActivity.java.

package com.example.sairamkrishna.myapplication;

import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {


Button enableButton,disableButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

enableButton=(Button)findViewById(R.id.button1);
disableButton=(Button)findViewById(R.id.button2);

enableButton.setOnClickListener(new OnClickListener(){
public void onClick(View v){
WifiManager wifi = (WifiManager)
getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(true);
}
});

disableButton.setOnClickListener(new OnClickListener(){
public void onClick(View v){
WifiManager wifi = (WifiManager)
getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(false);
}
});
}
}

Following is the modified content of the xml res/layout/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"

700 | P a g e
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="76dp"
android:text="Enable Wifi"
android:layout_centerVertical="true"
android:layout_alignEnd="@+id/imageView" />

<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Disable Wifi"
android:layout_marginBottom="93dp"
android:layout_alignParentBottom="true"
android:layout_alignStart="@+id/imageView" />

</RelativeLayout>

Following is the content of AndroidManifest.xml file.

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


<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >
<uses-permission
android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission
android:name="android.permission.CHANGE_WIFI_STATE" />

<application
android:allowBackup="true"

701 | P a g e
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name=".MainActivity"
android:label="@string/app_name" >

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

</activity>

</application>
</manifest>

Let's try to run your application. I assume you have connected your actual
Android Mobile device with your computer. To run the app from Android studio,
open one of your project's activity files and click Run icon from the toolbar.
Before starting your application, Android studio will display following window to
select an option where you want to run your Android application.

702 | P a g e
Select your mobile device as an option and It will shows the following image−

703 | P a g e
Now click on disable wifi button.then the sample output should be like this −

704 | P a g e
Android - Widgets
A widget is a small gadget or control of your android application placed on the
home screen. Widgets can be very handy as they allow you to put your favourite
applications on your home screen in order to quickly access them. You have
probably seen some common widgets, such as music widget, weather widget,
clock widget e.t.c

705 | P a g e
Widgets could be of many types such as information widgets, collection widgets,
control widgets and hybrid widgets. Android provides us a complete framework
to develop our own widgets.

Widget - XML file


In order to create an application widget, first thing you need is
AppWidgetProviderInfo object, which you will define in a separate widget XML
file. In order to do that, right click on your project and create a new folder
called xml. Now right click on the newly created folder and create a new XML
file. The resource type of the XML file should be set to AppWidgetProvider. In
the xml file, define some properties which are as follows −

<appwidget-provider
xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="146dp"
android:updatePeriodMillis="0"
android:minHeight="146dp"
android:initialLayout="@layout/activity_main">
</appwidget-provider>

Widget - Layout file


Now you have to define the layout of your widget in your default XML file. You
can drag components to generate auto xml.

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

Widget - Java file


After defining layout, now create a new JAVA file or use existing one, and extend
it with AppWidgetProvider class and override its update method as follows.

In the update method, you have to define the object of two classes which are
PendingIntent and RemoteViews. Its syntax is −

PendingIntent pending = PendingIntent.getActivity(context, 0,


intent, 0);
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.activity_main);

706 | P a g e
In the end you have to call an update method updateAppWidget() of the
AppWidgetManager class. Its syntax is −

appWidgetManager.updateAppWidget(currentWidgetId,views);

A part from the updateAppWidget method, there are other methods defined in
this class to manipulate widgets. They are as follows −

Sr.N
Method & Description
o

onDeleted(Context context, int[] appWidgetIds)


1
This is called when an instance of AppWidgetProvider is deleted.

onDisabled(Context context)
2
This is called when the last instance of AppWidgetProvider is deleted

onEnabled(Context context)
3
This is called when an instance of AppWidgetProvider is created.

onReceive(Context context, Intent intent)


4
It is used to dispatch calls to the various methods of the class

Widget - Manifest file


You also have to declare the AppWidgetProvider class in your manifest file as
follows:

<receiver android:name="ExampleAppWidgetProvider" >

<intent-filter>
<action
android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>

<meta-data android:name="android.appwidget.provider"
android:resource="@xml/example_appwidget_info" />
</receiver>

Example
Here is an example demonstrating the use of application Widget. It creates a
basic widget applications that will open this current website in the browser.

707 | P a g e
To experiment with this example, you need to run this on an actual device on
which internet is running.

Ste
Description
ps

You will use Android studio to create an Android application under a package
1
com.example.sairamkrishna.myapplication.

2 Modify src/MainActivity.java file to add widget code.

3 Modify the res/layout/activity_main to add respective XML components

Create a new folder and xml file under res/xml/mywidget.xml to add


4
respective XML components

5 Modify the AndroidManifest.xml to add the necessary permissions

Run the application and choose a running android device and install the
6
application on it and verify the results.

Following is the content of the modified MainActivity.java.

package com.example.sairamkrishna.myapplication;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.widget.RemoteViews;
import android.widget.Toast;

public class MainActivity extends AppWidgetProvider{


public void onUpdate(Context context, AppWidgetManager
appWidgetManager,int[] appWidgetIds) {
for(int i=0; i<appWidgetIds.length; i++){
int currentWidgetId = appWidgetIds[i];
String url = "https://www.tutorialspoint.com";

Intent intent = new Intent(Intent.ACTION_VIEW);


intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setData(Uri.parse(url));

PendingIntent pending = PendingIntent.getActivity(context,


0,intent, 0);

708 | P a g e
RemoteViews views = new
RemoteViews(context.getPackageName(),R.layout.activity_main);

views.setOnClickPendingIntent(R.id.button, pending);
appWidgetManager.updateAppWidget(currentWidgetId,views);
Toast.makeText(context, "widget added",
Toast.LENGTH_SHORT).show();
}
}
}

Following is the modified content of the xml res/layout/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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:transitionGroup="true">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:id="@+id/textView"
android:layout_centerHorizontal="true"
android:textColor="#ff3412ff"
android:textSize="35dp" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Widget"
android:id="@+id/button"
android:layout_centerHorizontal="true"
android:layout_marginTop="61dp"
android:layout_below="@+id/textView" />

</RelativeLayout>

Following is the content of the res/xml/mywidget.xml.

709 | P a g e
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider
xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="146dp"
android:updatePeriodMillis="0"
android:minHeight="146dp"
android:initialLayout="@layout/activity_main">
</appwidget-provider>

Following is the content of the res/values/string.xml.

<resources>
<string name="app_name">My Application</string>
</resources>

Following is the content of AndroidManifest.xml file.

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


<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >

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

<intent-filter>
<action
android:name="android.appwidget.action.APPWIDGET_UPDATE"></action>
</intent-filter>

<meta-data android:name="android.appwidget.provider"
android:resource="@xml/mywidget"></meta-data>

</receiver>

</application>
</manifest>

Let's try to run your application. I assume you have connected your actual
Android Mobile device with your computer. To run the app from Android studio,
open one of your project's activity files and click Run icon from the tool bar.
Before starting your application, Android studio will display following window to
select an option where you want to run your Android application.

710 | P a g e
Select your mobile device as an option and then check your mobile device which
will display your default screen −

711 | P a g e
Go to your widget section and add your created widget to the desktop or home
screen. It would look something like this −

712 | P a g e
Now just tap on the widget button that appears, to launch the browser. But
before that please make sure that you are connected to the internet. After
pressing the button , the following screen would appear −

713 | P a g e
Note. By just changing the url in the java file, your widget will open your desired
website in the browser.

Android - XML Parser


XML stands for Extensible Mark-up Language.XML is a very popular format and
commonly used for sharing data on the internet. This chapter explains how to
parse the XML file and extract necessary information from it.

Android provides three types of XML parsers which are DOM,SAX and
XMLPullParser. Among all of them android recommend XMLPullParser because
it is efficient and easy to use. So we are going to use XMLPullParser for parsing
XML.

714 | P a g e
The first step is to identify the fields in the XML data in which you are interested
in. For example. In the XML given below we interested in getting temperature
only.

<?xml version="1.0"?>
<current>

<city id="2643743" name="London">


<coord lon="-0.12574" lat="51.50853"/>
<country>GB</country>
<sun rise="2013-10-08T06:13:56" set="2013-10-08T17:21:45"/>
</city>

<temperature value="289.54" min="289.15" max="290.15"


unit="kelvin"/>
<humidity value="77" unit="%"/>
<pressure value="1025" unit="hPa"/>
</current>

XML - Elements
An xml file consist of many components. Here is the table defining the
components of an XML file and their description.

Sr.N
Component & description
o

Prolog
1 An XML file starts with a prolog. The first line that contains the information
about a file is prolog

Events
2 An XML file has many events. Event could be like this. Document starts ,
Document ends, Tag start , Tag end and Text e.t.c

Text
3 Apart from tags and events, and xml file also contains simple text. Such
as GB is a text in the country tag.

Attributes
4
Attributes are the additional properties of a tag such as value e.t.c

XML - Parsing

715 | P a g e
In the next step, we will create XMLPullParser object , but in order to create that
we will first create XmlPullParserFactory object and then call its newPullParser()
method to create XMLPullParser. Its syntax is given below −

private XmlPullParserFactory xmlFactoryObject =


XmlPullParserFactory.newInstance();
private XmlPullParser myparser = xmlFactoryObject.newPullParser();

The next step involves specifying the file for XmlPullParser that contains XML. It
could be a file or could be a Stream. In our case it is a stream.Its syntax is given
below −

myparser.setInput(stream, null);

The last step is to parse the XML. An XML file consist of events, Name, Text,
AttributesValue e.t.c. So XMLPullParser has a separate function for parsing each
of the component of XML file. Its syntax is given below −

int event = myParser.getEventType();


while (event != XmlPullParser.END_DOCUMENT) {
String name=myParser.getName();
switch (event){
case XmlPullParser.START_TAG:
break;

case XmlPullParser.END_TAG:
if(name.equals("temperature")){
temperature = myParser.getAttributeValue(null,"value");
}
break;
}
event = myParser.next();
}

The method getEventType returns the type of event that happens. e.g:
Document start , tag start e.t.c. The method getName returns the name of the
tag and since we are only interested in temperature , so we just check in
conditional statement that if we got a temperature tag , we call the
method getAttributeValue to return us the value of temperature tag.

Apart from the these methods, there are other methods provided by this class
for better parsing XML files. These methods are listed below −

Sr.N
Method & description
o

716 | P a g e
getAttributeCount()
1
This method just Returns the number of attributes of the current start tag

getAttributeName(int index)
2
This method returns the name of the attribute specified by the index value

getColumnNumber()
3
This method returns the Returns the current column number, starting from 0.

getDepth()
4
This method returns Returns the current depth of the element.

getLineNumber()
5
Returns the current line number, starting from 1.

getNamespace()
6
This method returns the name space URI of the current element.

getPrefix()
7
This method returns the prefix of the current element

getName()
8
This method returns the name of the tag

getText()
9
This method returns the text for that particular element

isWhitespace()
10 This method checks whether the current TEXT event contains only whitespace
characters.

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

Example
Here is an example demonstrating the use of XML DOM Parser. It creates a basic
application that allows you to parse XML.

To experiment with this example, you can run this on an actual device or in an
emulator.

Ste
Description
ps

717 | P a g e
You will use Android studio to create an Android application under a package
1
com.example.sairamkrishna.myapplication.

2 Modify src/MainActivity.java file to add necessary code.

3 Modify the res/layout/activity_main to add respective XML components

4 Create a new XML file under Assets Folder/file.xml

5 Modify AndroidManifest.xml to add necessary internet permission

Run the application and choose a running android device and install the
6
application on it and verify the results

Following is the content of the modified main activity file MainActivity.java.

package com.example.sairamkrishna.myapplication;

import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {


TextView tv1;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1=(TextView)findViewById(R.id.textView1);

try {
InputStream is = getAssets().open("file.xml");

DocumentBuilderFactory dbFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(is);

Element element=doc.getDocumentElement();
element.normalize();

718 | P a g e
NodeList nList = doc.getElementsByTagName("employee");

for (int i=0; i<nList.getLength(); i++) {

Node node = nList.item(i);


if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element2 = (Element) node;
tv1.setText(tv1.getText()+"\nName : " +
getValue("name", element2)+"\n");
tv1.setText(tv1.getText()+"Surname : " +
getValue("surname", element2)+"\n");
tv1.setText(tv1.getText()
+"-----------------------");
}
}

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

private static String getValue(String tag, Element element) {


NodeList nodeList =
element.getElementsByTagName(tag).item(0).getChildNodes();
Node node = nodeList.item(0);
return node.getNodeValue();
}

Following is the content of Assets/file.xml.

<?xml version="1.0"?>
<records>
<employee>
<name>Sairamkrishna</name>
<surname>Mammahe</surname>
<salary>50000</salary>
</employee>

<employee>
<name>Gopal </name>
<surname>Varma</surname>
<salary>60000</salary>
</employee>

<employee>
<name>Raja</name>

719 | P a g e
<surname>Hr</surname>
<salary>70000</salary>
</employee>

</records>

Following is the modified content of the xml res/layout/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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>

Following is the content of AndroidManifest.xml file.

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


<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name=".MainActivity"
android:label="@string/app_name" >

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

720 | P a g e
</activity>

</application>
</manifest>

Let's try to run our application we just modified. I assume you had created
your AVD while doing environment setup. To run the app from Android studio,
open one of your project's activity files and click Run icon from the toolbar.
Android studio installs the app on your AVD and starts it and if everything is fine
with your setup and application, it will display following Emulator window −

721 | P a g e
Android Questions and Answers
Android Questions and Answers has been designed with a special intention
of helping students and professionals preparing for various Certification
Exams and Job Interviews. This section provides a useful collection of sample
Interview Questions and Multiple Choice Questions (MCQs) and their answers
with appropriate explanations.

S
Question/Answers Type
N

Android Interview Questions


This section provides a huge collection of Android Interview Questions with their
1
answers hidden in a box to challenge you to have a go at them before discovering
the correct answer.

Android Online Quiz


This section provides a great collection of Android Multiple Choice Questions
2
(MCQs) on a single page along with their correct answers and explanation. If you
select the right option, it turns green; else red.

Android Online Test


If you are preparing to appear for a Java and Android Framework related
certification exam, then this section is a must for you. This section simulates a
3
real online test along with a given timer which challenges you to complete the test
within a given time-frame. Finally you can check your overall test score and how
you fared among millions of other candidates who attended this online test.

Android Mock Test


This section provides various mock tests that you can download at your local
4
machine and solve offline. Every mock test is supplied with a mock test key to let
you verify the final score and grade yourself.

722 | P a g e
Android - Useful Resources

723 | P a g e

You might also like