Mobile Application Development - Android
Mobile Application Development - Android
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.
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.
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.
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
KitKat for
Android 4.4W 20 KITKAT_WATCH
Wearables Only
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 2.3.4
10 GINGERBREAD_MR1
Android 2.3.3
Android 2.3.2
Android 2.3.1 9 GINGERBREAD
Android 2.3
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 −
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.
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.
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
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 −
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.
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.
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 −
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.
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.
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.
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.
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.
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.
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.
So let us proceed to write a simple Android Application which will print "Hello
World!".
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.
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.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
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.
<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 −
<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!".
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.
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 −
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 −
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 −
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 −
54 | P a g e
}
Now you can use these resources in the following layout file to set the text color
and text string as follows −
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.
57 | P a g e
package com.example.helloworld;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
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:
<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 −
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:
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:
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.
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;
63 | P a g e
@Override
public void onCreate() {
}
}
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.
Run the application to launch Android emulator and verify the result of the
7
changes done in the application.
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;
65 | P a g e
Log.d(msg, "The onCreate() event");
}
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.
*/
@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();
}
}
<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>
</manifest>
<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.
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 −
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.
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.
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.
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
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;
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.
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>
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.
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.
82 | P a g e
methods.
4 Register your content provider in your AndroidManifest.xml file using <provider.../> tag
Run the application to launch Android emulator and verify the result of the changes
7
done in the application.
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;
@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());
Toast.makeText(getBaseContext(),
uri.toString(), Toast.LENGTH_LONG).show();
}
public void onClickRetrieveStudents(View view) {
// Retrieve student records
String URL =
"content://com.example.MyApplication.StudentsProvider";
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;
/**
* Database specific constant declarations
*/
/**
* Helper class that actually creates and manages
85 | P a g e
* the provider's underlying data repository.
*/
@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;
}
@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:
}
@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.
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.
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.
95 | P a g e
Fragment lifecycle
Here is the list of methods which you can to override in your fragment class −
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.
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
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.
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().
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.
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 −
// 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 −
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();
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.
Run the application to launch Android emulator and verify the result of the changes
4
done in the application.
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;
@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.
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.
Run the application to launch Android emulator and verify the result of the changes
7
done in the application.
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;
@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 −
<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" />
</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);
}
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 −
Gravity attribute plays important role in positioning the view object and it can
take one or more (separated by '|') of the following constant values.
123 | P a g e
Grow the vertical size of the object if needed so it
fill_vertical 0x70
completely fills its container.
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"
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 −
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.
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 −
<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 −
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.
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.
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.
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) ;
}
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.
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.
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;
@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
<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.
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.
<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.
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>
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.
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.
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>
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
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.
<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;
146 | P a g e
}
}
if(this.titleText != null )
setText(this.titleText+" "+time);
else
setText(time);
}
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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
147 | P a g e
setContentView(R.layout.activity_main);
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.
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.
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.
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.
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};
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);
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.
159 | P a g e
You have simple way to create a notification. Follow the following steps in your
application to create a notification −
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.
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);
Sr.N
Constants & Description
o.
Notification build()
1 Combine all of the options that have been set and return a new Notification
object.
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.
NotificationCompat.Builder setStyle
13 (NotificationCompat.Style style)
Add a rich notification style to be applied at build time.
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
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.
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;
b1 = (Button)findViewById(R.id.button);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
addNotification();
}
});
}
// 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;
<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 −
mBuilder.setContentTitle("New Message");
mBuilder.setContentText("You've received new message.");
mBuilder.setTicker("New Message Alert!");
mBuilder.setSmallIcon(R.drawable.woman);
169 | P a g e
// Sets a title for the Inbox style big view
inboxStyle.setBigContentTitle("Big Title Details:");
mBuilder.setStyle(inboxStyle);
/* 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);
Now if you will try to run your application then you will find following result in
expanded form of the view −
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
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.
171 | P a g e
Set the estimated accuracy of this location, meters.
String toString()
19 Returns a string containing a concise, human-readable description of this
object.
These interfaces provide following important callback methods, which you need
to implement in your activity class −
172 | P a g e
use disconnect() method to disconnect from the location client.
Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.
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.
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.
You will use Android studio IDE to create an Android application and name it
1
as Tutorialspoint under a package com.example.tutorialspoint7.myapplication.
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.
Run the application to launch Android emulator and verify the result of the changes
7
done in the application.
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;
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) {
@Override
public void onClick(View arg0) {
// create class object
gps = new GPSTracker(MainActivity.this);
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;
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
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);
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
* */
/**
* Function to get latitude
* */
179 | P a g e
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* @return boolean
* */
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
180 | P a g e
mContext.startActivity(intent);
}
});
@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">
<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.
Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.
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 −
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.
Run the application to launch Android emulator and verify the result of the changes
6
done in the application.
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;
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.
SmsManager API
192 | P a g e
smsManager.sendTextMessage("phoneNo", null, "sms message", null, null);
Apart from the above method, there are few other important functions available
in SmsManager class. These methods are listed below −
Sr.No
Method & Description
.
void sendMultipartTextMessage(String
destinationAddress, String scAddress,
ArrayList<String> parts, ArrayList<PendingIntent>
4
sentIntents, ArrayList<PendingIntent>
deliveryIntents)
Send a multi-part 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.
Run the application to launch Android emulator and verify the result of the
6
changes done in the application.
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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendSMSMessage();
}
});
}
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;
}
}
}
}
}
<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>
<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.
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.
smsIntent.setData(Uri.parse("smsto:"));
smsIntent.setType("vnd.android-dir/mms-sms");
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.
Run the application to launch Android emulator and verify the result of the
6
changes done in the application.
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;
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;
}
}
<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>
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.
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.
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.
Run the application to launch Android emulator and verify the result of the
6
changes done in the application.
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;
@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);
}
});
}
}
<Button
android:id="@+id/buttonCall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="call 0377778888" />
</LinearLayout>
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" >
<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.
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.
215 | P a g e
Apk development process
Before exporting the apps, you must some of tools
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.
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.
219 | P a g e
Some of App markets
Google play
Amazon AppStore
220 | P a g e
F-Droid
Samsung Galaxy AppStore
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.
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.
setMessage(CharSequence message)
3
This method sets the message to be displayed in the alert dialog
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
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
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.
.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.
223 | P a g e
mSelectedItems = new ArrayList();
AlertDialog.Builder builder = new
AlertDialog.Builder(getActivity());
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));
}
}
})
.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.
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.
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.
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;
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();
}
});
<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>
<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.
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 −
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 −
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.
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.
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.
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.
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;
233 | P a g e
AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.move);
image.startAnimation(animation1);
}
<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>
<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>
<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>
<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>
<translate
android:fromXDelta="0%p"
android:toXDelta="75%p"
android:duration="800" />
</set>
<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>
<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.
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.
Run the application and choose a running android device and install the
5
application on it and verify the results.
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 android.support.v4.app.ActivityCompat;
import android.content.pm.PackageManager;
import android.support.v4.content.ContextCompat;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonStop.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(false);
buttonStopPlayingRecording.setEnabled(false);
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.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();
}
}
});
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP)
;
250 | P a g e
mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mediaRecorder.setOutputFile(AudioSavePathInDevice);
}
i++ ;
}
return stringBuilder.toString();
}
@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;
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;
}
}
<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>
<resources>
<string name="app_name">My Application</string>
</resources>
<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.
257 | P a g e
private AudioManager myAudioManager;
myAudioManager =
(AudioManager)getSystemService(Context.AUDIO_SERVICE);
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
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.
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
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.
Run the application and choose a running android device and install the
6
application on it and verify the results.
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;
@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();
}
}
});
}
}
<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>
<resources>
<string name="app_name">My Application</string>
</resources>
<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.
<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.
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
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.
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;
@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);
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());
}
}
<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>
<resources>
<string name="app_name">My Application</string>
</resources>
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.
<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" />
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.
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.
Run the application and choose a running android device and install the application
4
on it and verify the results.
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;
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
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: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.
In order to enable the Bluetooth of your device, call the intent with the following
Bluetooth constant ACTION_REQUEST_ENABLE. Its syntax is.
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
288 | P a g e
2 Modify src/MainActivity.java file to add the code
Run the application and choose a running android device and install the application
5
on it and verify the results.
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;
@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);
}
for(BluetoothDevice bt : pairedDevices)
list.add(bt.getName());
Toast.makeText(getApplicationContext(), "Showing Paired
Devices",Toast.LENGTH_SHORT).show();
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: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
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
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
298 | P a g e
Bundle options)
It starts an activity , but can take extra bundle of options with it
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.
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.
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;
@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) {
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();
}
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();
}
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "DONT
ALLOW",
new DialogInterface.OnClickListener() {
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE,
"SETTINGS",
new DialogInterface.OnClickListener() {
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);
}
}
}
}
@Override
protected void onResume() {
super.onResume();
}
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.
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 −
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.
Run the application and choose a running android device and install the
4
application on it and verify the results
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;
@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);
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();
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ClipData abc = myClipboard.getPrimaryClip();
ClipData.Item item = abc.getItemAt(0);
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>
<resources>
<string name="app_name">My Application</string>
</resources>
<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 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
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.
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.
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;
tv1=(TextView)findViewById(R.id.textView3);
tv2=(TextView)findViewById(R.id.textView4);
<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>
<resources>
<string name="app_name">My Application</string>
</resources>
<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.
322 | P a g e
only backup your application data. In order to access the other applications
data, you need to root your phone.
<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
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.
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
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 −
<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;
@Override
public void onCreate() {
SharedPreferencesBackupHelper helper = new
SharedPreferencesBackupHelper(this,
File_Name_Of_Prefrences);
addHelper(PREFS_BACKUP_KEY, helper);
}
}
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 −
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 −
This forces the Backup Manager to perform all backup requests that are in its
queue.
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:
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.
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.
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.
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.
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.
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.
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 −
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
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.
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.
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 −
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 −
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.
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 −
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() {
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.
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
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.
Run the application and choose a running android device and install the application
4
on it and verify the results.
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;
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
<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());
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 −
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.
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;
@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());
}
@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;
}
}
}
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>
<resources>
357 | P a g e
<string name="app_name>My Application</string>
</resources>
<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
−
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<!--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" />
<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"));
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.
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
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;
@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>
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.
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 −
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(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
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.
Run the application and choose a running android device and install the
4
application on it and verify the results
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;
@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);
371 | P a g e
double red = 0.33;
double green = 0.59;
double blue = 0.11;
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);
}
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);
}
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);
}
r = r + 150;
g = 0;
b = 0;
alpha = 0;
operation.setPixel(i, j, Color.argb(Color.alpha(p), r,
g, b));
}
}
im.setImageBitmap(operation);
}
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);
}
r = 0;
g = 0;
b = b+150;
alpha = 0;
operation.setPixel(i, j, Color.argb(Color.alpha(p), r,
g, b));
}
}
im.setImageBitmap(operation);
}
}
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.
<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>
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
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.
Run the application and choose a running android device and install the
4
application on it and verify the results
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;
@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);
}
});
}
}
<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>
<resources>
<string name="app_name">My Application</string>
<string name="left"><![CDATA[<]]></string>
<string name="right"><![CDATA[>]]></string>
</resources>
<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 −
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 −
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);
}
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
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
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
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.
Run the application and choose a running android device and install the
4
application on it and verify the results
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;
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
}
<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>
<resources>
<string name="app_name">My Application</string>
</resources>
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.
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 −
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.
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 −
python JetCreator.py
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 −
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 −
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
Run the application and choose a running android device and install the
5
application on it and verify the results
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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new GetContacts().execute();
}
@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);
413 | P a g e
try {
JSONObject jsonObj = new JSONObject(jsonStr);
} 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);
}
}
}
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;
415 | P a g e
public HttpHandler() {
}
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.
tools:context="com.example.tutorialspoint7.myapplication.MainActivi
ty">
<ListView
android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
<TextView
android:id="@+id/mobile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d5d"
android:textStyle="bold" />
</LinearLayout>
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.
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.
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.
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.
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
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.
Run the application and choose a running android device and install the application
4
on it and verify the results
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;
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
<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.
<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 −
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.
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
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;
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);
}
});
}
}
<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>
<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>
<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.
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 −
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
Run the application and choose a running android device and install the application
4
on it and verify the results
<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.
443 | P a g e
if(username.getText().toString().equals("admin") &&
password.getText().toString().equals("admin")){
//correcct password
}else{
//wrong password
}
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.
Run the application and choose a running android device and install the
5
application on it and verify the results
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;
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();
}
});
}
}
<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>
<resources>
<string name="app_name">My Application</string>
</resources>
<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.
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
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.
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
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;
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");
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;
}
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long)
finalTime)))
);
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);
}
};
}
<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>
<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.
<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.
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 −
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.
Run the application and choose a running android device and install the
4
application on it and verify the results.
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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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();
xAxis += dx;
yAxis += dy;
ed3.setText(Float.toString(xAxis));
ed4.setText(Float.toString(yAxis));
break;
}
}
return true;
}
});
}
}
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: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>
<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.
android:parentActivityName = "com.example.test.MainActivity"
getActionBar().setDisplayHomeAsUpEnabled(true);
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
}
Sr.N
Method & description
o
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.
Run the application and choose a running android device and install the
7
application on it and verify the results.
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;
@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);
}
});
}
}
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.
*/
@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");
}
480 | P a g e
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_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>
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>
<resources>
<string name="app_name">My Application</string>
</resources>
<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 −
The last thing you need to do is to check Connected State of the network. Its
syntax is given below −
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
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.
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.
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="";
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.
Run the application and choose a running android device and install the
7
application on it and verify the results.
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;
@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
");
}
});
}
new Thread() {
public void run() {
InputStream in = null;
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();
}
try {
URL url = new URL(urlStr);
URLConnection urlConn = url.openConnection();
if (resCode == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
}catch (MalformedURLException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
return in;
}
490 | P a g e
super.handleMessage(msg);
ImageView img = (ImageView) findViewById(R.id.imageView);
img.setImageBitmap((Bitmap)
(msg.getData().getParcelable("bitmap")));
progressDialog.dismiss();
}
};
=(ConnectivityManager)getSystemService(getBaseContext().CONNECTIVIT
Y_SERVICE);
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>
<resources>
492 | P a g e
<string name="app_name">My Application</string>
</resources>
<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 −
<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"/>
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.
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";
}
?>
$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
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()));
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.
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.
Run the application and choose a running android device and install the application
7
on it and verify the results.
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
@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);
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;
505 | P a g e
this.roleField = roleField;
byGetOrPost = flag;
}
@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;
InputStreamReader(response.getEntity().getContent()));
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");
conn.setDoOutput(true);
OutputStreamWriter wr = new
OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
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" >
</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.
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
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.
Run the application and choose a running android device and install the
4
application on it and verify the results.
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;
@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 (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;
}
}
<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>
<resources>
<string name="app_name">My Application</string>
</resources>
<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.
Now you can set some properties of this dialog. Such as, its style, its text etc.
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.
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.
Run the application and choose a running android device and install the
4
application on it and verify the results.
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;
525 | P a g e
progress.show();
<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>
<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.
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 −
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.
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.
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
Run the application and choose a running android device and install the
4
application on it and verify the results.
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;
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);
}
});
}
}
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>
<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.
3D Rendering
Image Processing
Computational Photography
Computer Vision
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.
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.
RenderScript APIs
If you want to use RenderScript in your API, you can do it in following two ways
−
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 −
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.
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.
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 −
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.
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.
Run the application and choose a running android device and install the
6
application on it and verify the results.
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;
@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);
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);
}
});
}
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;
547 | P a g e
public String getLink(){
return link;
}
try {
event = myParser.getEventType();
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();
}
}
try {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection)
url.openConnection();
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;
w1.loadUrl("https://www.tutorialspoint.com/android/sampleXML.xml");
}
}
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/webView"
android:layout_gravity="center_horizontal" />
</LinearLayout>
550 | P a g e
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_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>
<resources>
<string name="app_name">My Application</string>
</resources>
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.
Steps Description
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.
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.
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.
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) {
}
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 −
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.
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.
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.
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;
mSensorManager = (SensorManager)
getSystemService(SENSOR_SERVICE);
List<Sensor> mList=
mSensorManager.getSensorList(Sensor.TYPE_ALL);
@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: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);
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
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.
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.
Run the application and choose a running android device and install the
7
application on it and verify the results.
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;
@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);
}
});
}
}
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;
@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);
}
575 | P a g e
editor.commit();
}
<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>
<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>
<resources>
<string name="app_name">My Application</string>
</resources>
<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.
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
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
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.
Run the application and choose a running android device and install the
4
application on it and verify the results.
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;
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()
;
}
});
}
<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>
<resources>
<string name="app_name">My Application</string>
</resources>
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 −
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.
Components of SIP
SIP has two major components which are listed below.
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.
@Override
public void onGetSentenceSuggestions(SentenceSuggestionsInfo[]
arg0) {
// TODO Auto-generated method stub
}
}
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
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.
Run the application and choose a running android device and install the
4
application on it and verify the results
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;
@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);
}
});
}
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
}
}
<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>
<resources>
<string name="app_name">My Application</string>
</resources>
<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
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
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
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.
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
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.
Run the application and choose a running android device and install the
10
application on it and verify the results.
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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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;
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);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
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;
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);
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;
}
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:
613 | P a g e
});
AlertDialog d = builder.create();
d.setTitle("Are you sure");
d.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
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
}
}
}
}
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;
@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);
}
616 | P a g e
"id = ? ",
new String[] { Integer.toString(id) });
}
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_NAM
E)));
res.moveToNext();
}
return array_list;
}
}
<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>
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>
621 | P a g e
<string name="yes">Yes</string>
<string name="no">No</string>
</resources>
<item android:id="@+id/item1"
android:icon="@drawable/add"
android:title="@string/Add_New" >
</item>
</menu>
<item
android:id="@+id/Delete_Contact"
android:orderInCategory="100"
android:title="@string/delete"/>
</menu>
<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.
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.
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.
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.
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.
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.
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 −
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.
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 −
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.
Monkey Usage
In order to use monkey, open up a command prompt and just navigate to the
following directory.
Once inside the directory, attach your device with the PC , and run the following
command.
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.
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.
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
635 | P a g e
Modify layouta XML file res/layout/activity_main.xml add any GUI component if
3
required.
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.
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
}
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;
636 | P a g e
@Override
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
<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 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 −
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 −
Apart from the speak method, there are some other methods available in the
TextToSpeech class. They are listed below −
Sr.N
Method & description
o
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.
Run the application and choose a running android device and install the
4
application on it and verify the results.
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;
@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);
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);
}
});
}
<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>
<resources>
<string name="app_name">My Application</string>
</resources>
<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.
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.
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.
Run the application and choose a running android device and install the
5
application on it and verify the results.
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;
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
@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
}
}
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>
<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 −
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
−
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 −
In order to update the status , you can call updateStatus() method. Its syntax is
given below −
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.
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.
Run the application and choose a running android device and install the application
4
on it and verify the results
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;
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
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.
<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.
<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
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
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 −
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
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 −
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.
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.
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.
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.
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
@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;
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
<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.
<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 −
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 −
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.
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.
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;
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;
}
}
}
<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>
<resources>
<string name="app_name">My Application</string>
</resources>
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.
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 −
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 −
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.
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.
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;
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);
}
});
}
}
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>
<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.
<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>
Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.
In the update method, you have to define the object of two classes which are
PendingIntent and RemoteViews. Its syntax is −
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
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.
<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.
Run the application and choose a running android device and install the
6
application on it and verify the results.
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;
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();
}
}
}
<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>
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>
<resources>
<string name="app_name">My Application</string>
</resources>
<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 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>
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 −
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 −
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.
Run the application and choose a running android device and install the
6
application on it and verify the results
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;
@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");
<?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>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
<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
722 | P a g e
Android - Useful Resources
723 | P a g e