Professional Documents
Culture Documents
Android Advanced Tutorial PDF
Android Advanced Tutorial PDF
tutorialspoint.com
i
ABOUT THE TUTORIAL
This tutorial will teach you basic Android programming and will also take you through some advance
concepts related to Android application development.
Audience
This tutorial has been prepared for the beginners to help them understand basic Android programming.
After completing this tutorial you will find yourself at a moderate level of expertise in Android
programming from where you can take yourself to next levels.
Prerequisites
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.
This tutorial may contain inaccuracies or errors and tutorialspoint provides no guarantee regarding the
accuracy of the site or its contents including this tutorial. If you discover that the tutorialspoint.com site
or this tutorial content contains some errors, please contact us at webmaster@tutorialspoint.com
TUTORIALS POINT
Simply Easy Learning
Table of Content
Advanced Android Tutorial ....................................................... 2
Audience .................................................................................. 2
Prerequisites ............................................................................ 2
Copyright & Disclaimer Notice.................................................. 2
Drag and Drop ....................................................................... 12
The Drag/Drop Process............................................................................ 12
The DragEvent Class ............................................................................... 13
CONSTANTS ........................................................................................... 13
METHODS ............................................................................................... 13
Listening for Drag Event ........................................................................... 14
Starting a Drag Event ............................................................................... 14
Example ................................................................................................... 14
Notifications ........................................................................... 19
Create and Send Notifications.................................................................. 20
STEP 1 - CREATE NOTIFICATION BUILDER ........................................ 20
STEP 2 - SETTING NOTIFICATION PROPERTIES ................................ 20
STEP 3 - ATTACH ACTIONS .................................................................. 20
STEP 4 - ISSUE THE NOTIFICATION..................................................... 21
The NotificationCompat.Builder Class ...................................................... 21
Example ................................................................................................... 22
Big View Notification ................................................................................ 28
Location Based Services ........................................................ 31
The Location Object ................................................................................. 31
Get the Current Location .......................................................................... 32
Get the Updated Location ........................................................................ 33
Location Quality of Service ....................................................................... 33
Displaying a Location Address ................................................................. 33
Example ................................................................................................... 34
INSTALL THE GOOGLE PLAY SERVICES SDK .................................... 34
CREATE ANDROID APPLICATION ........................................................ 34
Sending Email ........................................................................ 43
Intent Object - Action to send Email ......................................................... 43
Intent Object - Data/Type to send Email................................................... 43
Intent Object - Extra to send Email ........................................................... 43
Example ................................................................................................... 44
Sending SMS ......................................................................... 49
Using SmsManager to send SMS ............................................................ 49
TUTORIALS POINT
Simply Easy Learning
Example ................................................................................................... 50
Using Built-in Intent to send SMS ............................................................. 54
Intent Object - Action to send SMS .......................................................... 54
Intent Object - Data/Type to send SMS .................................................... 54
Intent Object - Extra to send SMS ............................................................ 54
Example ................................................................................................... 54
Phone Calls ........................................................................... 59
Intent Object - Action to make Phone Call................................................ 59
Intent Object - Data/Type to make Phone Call ......................................... 59
Example ................................................................................................... 59
Publishing Android Application ............................................. 64
Export Android Application ....................................................................... 65
Google Play Registration.......................................................................... 68
Android Alert Dialoges ........................................................... 70
Example ................................................................................................... 71
Android Animations ................................................................ 81
Tween Animation ..................................................................................... 81
Zoom in animation .................................................................................... 82
Example ................................................................................................... 82
Android Audio Capture ........................................................... 93
Example ................................................................................................... 94
Android AudioManager ........................................................ 103
Example ................................................................................................. 104
Android Auto Complete ........................................................ 113
Example ................................................................................................. 114
Android Best Practices ......................................................... 121
Best Practices - User input ..................................................................... 121
Best Practices - Background jobs .......................................................... 121
ASYNCTASK VS SERVICES. ................................................................ 121
Best Practices - Performance ................................................................. 122
Best Practices - Security and privacy ..................................................... 122
Example ................................................................................................. 122
Android Bluetooth ................................................................ 131
Example ................................................................................................. 132
Android Camera ................................................................... 143
Using existing android camera application in our application ................. 143
Example ................................................................................................. 144
Directly using Camera API provided by android in our application ......... 150
Example ................................................................................................. 152
TUTORIALS POINT
Simply Easy Learning
Android Clipboard ................................................................ 158
Copying data .......................................................................................... 158
Pasting data ........................................................................................... 159
Example ................................................................................................. 159
Android Custom Fonts ......................................................... 166
Example ................................................................................................. 167
Android Data Backup ........................................................... 170
Example ................................................................................................. 171
Test your BackupAgent .......................................................................... 173
INSTALL YOUR APPLICATION ON A SUITABLE ANDROID SYSTEM IMAGE. 173
ENSURE DATA BACKUP IS ENABLED ................................................ 173
PERFORMING BACKUP ....................................................................... 173
UNINSTALL AND REINSTALL YOUR APPLICATION .......................... 173
Android Developer Tools...................................................... 174
SDK tools ............................................................................................... 174
Android ................................................................................................... 175
DDMS..................................................................................................... 175
RUNNING DDMS ................................................................................... 175
HOW IT WORKS .................................................................................... 175
USING DDMS ........................................................................................ 175
MAKING SMS ........................................................................................ 175
MAKING CALL ....................................................................................... 176
CAPTURING SCREENSHOT ................................................................ 178
Sqlite3 .................................................................................................... 179
USE SQLITE3 FROM A REMOTE SHELL............................................. 179
USING SQLITE3 DIRECTLY ................................................................. 179
Platform tools ......................................................................................... 180
Android Emulator ................................................................. 181
Creating AVD ......................................................................................... 181
Creating Snapshots ................................................................................ 181
Changing Orientation ............................................................................. 182
Emulator Commands.............................................................................. 183
Emulator - Sending SMS ........................................................................ 184
SENDING SMS THROUGH TELNET. ................................................... 184
Emulator - Making Call ........................................................................... 185
Emulator - Transferring files ................................................................... 186
Android Facebook Integration .............................................. 187
Integrating Facebook SDK ..................................................................... 187
GENERATING APPLICATION SIGNATURE ......................................... 187
TUTORIALS POINT
Simply Easy Learning
REGISTERING YOUR APPLICATION................................................... 188
DOWNLOADING SDK AND INTEGRATING IT ..................................... 188
CREATING FACEBOOK LOGIN APPLICATION ................................... 188
Intent share ............................................................................................ 189
Example ................................................................................................. 190
Android Gestures ................................................................. 197
Handling Pinch Gesture ......................................................................... 197
Example ................................................................................................. 198
Android Google Maps .......................................................... 205
Adding Google Map ............................................................................... 205
GOOGLE MAP - ACTIVITY FILE ........................................................... 205
GOOGLE MAP - LAYOUT FILE ............................................................. 205
GOOGLE MAP - ANDROIDMANIFEST FILE......................................... 205
Customizing Google Map ....................................................................... 206
ADDING MARKER ................................................................................. 206
CHANING MAP TYPE............................................................................ 206
ENABLE/DISABLE ZOOM ..................................................................... 206
Example ................................................................................................. 207
Integrating Google Maps ........................................................................ 207
Download and configure. Google Play Services SDK ............................ 208
INSTALL GOOGLE SERVICES SDK ..................................................... 208
IMPORT SDK TO ECLIPSE ................................................................... 208
CONFIGURE YOUR PROJECT WITH SDK .......................................... 208
Obtaining the API key............................................................................. 209
GETTING CERTIFICATE FROM KEYTOOL ......................................... 209
GETTING KEY FROM GOOGLE CONSOLE ....................................... 210
Specify Android Manifest settings .......................................................... 210
Adding Google Maps to your application. ............................................... 211
Android Image Effects .......................................................... 215
Example ................................................................................................. 216
Android Image Switcher ....................................................... 224
Example ................................................................................................. 225
Android Internal Storage ...................................................... 231
Writing file .............................................................................................. 231
Reading file ............................................................................................ 231
Example ................................................................................................. 232
Android JetPlayer................................................................. 239
Example ................................................................................................. 240
Using JetCreator .................................................................................... 240
TUTORIALS POINT
Simply Easy Learning
INSTALLING PYTHON .......................................................................... 240
INSTALLING WXPYTHON ................................................................... 241
RUUNING JETCREATOR .................................................................... 241
CREATING JETCONTENT ................................................................... 242
Verifying Results .................................................................................... 243
Android JSON Parser........................................................... 244
JSON - Elements ................................................................................... 244
JSON - Parsing ...................................................................................... 245
Example ................................................................................................. 246
Android Linkedin Integration ................................................ 254
Integrating Linkedin SDK........................................................................ 254
REGISTERING YOUR APPLICATION ................................................. 254
DOWNLOADING SDK AND INTEGRATING IT .................................... 255
POSTING UPDATES ON LINKEDIN APPLICATION ........................... 255
Intent share ............................................................................................ 255
Example ................................................................................................. 256
Android Loading Spinner...................................................... 263
Example ................................................................................................. 264
Android Localization ............................................................. 268
LOCALIZING STRINGS ........................................................................ 268
ITALY, RES/VALUES-IT/STRINGS.XML .............................................. 268
SPANISH, RES/VALUES-IT/STRINGS.XML ........................................ 269
FRENCH, RES/VALUES-IT/STRINGS.XML ......................................... 269
Example ................................................................................................. 269
Android Login Screen........................................................... 274
Example ................................................................................................. 275
Android MediaPlayer ............................................................ 283
Example ................................................................................................. 284
Android Multitouch ............................................................... 295
Example ................................................................................................. 296
Android Navigation ............................................................... 305
Providing Up Navigation ......................................................................... 305
Handling device back button .................................................................. 305
Example ................................................................................................. 306
Android Network Connection................................................ 314
Checking Network Connection ............................................................... 314
Performing Network Operations ............................................................. 315
Example ................................................................................................. 315
Android NFC Guide .............................................................. 324
TUTORIALS POINT
Simply Easy Learning
How It Works: ......................................................................................... 324
THREE MODES OF OPERATION ......................................................... 324
How it works with Android: ..................................................................... 324
Future Applications: ............................................................................... 325
Android PHP/MySQL ........................................................... 326
PHP - MYSQL ....................................................................................... 326
CREATING DATABASE........................................................................ 326
CREATING TABLES ............................................................................. 326
INSERTING VALUES IN TABLES ........................................................ 327
PHP - GET AND POST METHODS ...................................................... 327
ANDROID - CONNECTING MYSQL ..................................................... 327
CONNECTING VIA GET METHOD ...................................................... 327
CONNECTING VIA POST METHOD .................................................... 328
EXAMPLE ............................................................................................. 328
PHP - MYSQL PART............................................................................. 328
ANDROID PART ................................................................................... 329
Android Progress Circle ....................................................... 340
Example ................................................................................................. 341
Android ProgressBar ............................................................ 347
Example ................................................................................................. 348
Android Push Notification ..................................................... 355
Example ................................................................................................. 356
Android RenderScript ........................................................... 365
How RenderScript Works: ...................................................................... 365
How to Begin: ......................................................................................... 365
A RENDERSCRIPT KERNEL ............................................................... 366
RENDERSCRIPT APIS ......................................................................... 366
HOW TO USE RENDERSCRIPT SUPPORT LIBRARY....................... 367
Android RSS Reader ........................................................... 368
RSS Example ......................................................................................... 368
RSS Elements ........................................................................................ 368
Parsing RSS........................................................................................... 369
Example ................................................................................................. 370
Android Screen Cast ............................................................ 377
Screen Cast Steps ................................................................................. 377
STEP 1 ................................................................................................... 377
STEP 2 ................................................................................................... 377
STEP 3 ................................................................................................... 377
STEP 4 ................................................................................................... 377
TUTORIALS POINT
Simply Easy Learning
STEP 5 ................................................................................................... 377
Android SDK Manager ......................................................... 381
RUNNING ANDROID SDK MANAGER: ............................................... 381
RECOMMENDED PACKAGES ............................................................ 382
ENABLING PROXY IN ANDROID SDK MANAGER ............................ 382
Adding New Third Party Sites ................................................................ 383
Android Sensors .................................................................. 385
Getting list of sensors supported. ........................................................... 386
Example ................................................................................................. 386
Android Session Management ............................................. 390
Shared Preferences ............................................................................... 390
Session Management through Shared Preferences ............................... 391
Example ................................................................................................. 391
Android Shared Preferences ................................................ 402
Example ................................................................................................. 403
Android SIP Protocol ............................................................ 413
Applications ............................................................................................ 413
Requirements ......................................................................................... 413
SIP Classes............................................................................................ 413
Functions of SIP ..................................................................................... 414
Components of SIP ................................................................................ 414
UAC........................................................................................................ 414
UAS ........................................................................................................ 414
SipManager ............................................................................................ 414
Android Spell Checker ......................................................... 416
Example ................................................................................................. 417
Android SQLite Database .................................................... 423
Database - Package ............................................................................... 423
Database - Creation ............................................................................... 423
Database - Insertion ............................................................................... 424
Database - Fetching ............................................................................... 424
Database - Helper class ......................................................................... 425
Example ................................................................................................. 425
Android Support Library ....................................................... 444
Support Library Features........................................................................ 444
DOWNLOADING THE SUPPORT LIBRARIES .................................... 445
CHOOSING SUPPORT LIBRARIES .................................................... 445
CHANGES IN ANDROID.MANIFEST ................................................... 445
API VERSION ....................................................................................... 446
TUTORIALS POINT
Simply Easy Learning
Android Testing .................................................................... 447
Test Structure......................................................................................... 447
Testing Tools in android ......................................................................... 448
JUnit ....................................................................................................... 448
Monkey................................................................................................... 449
MONKEY FEATURES........................................................................... 449
MONKEY USAGE ................................................................................. 449
Example ................................................................................................. 450
Android Text to Speech........................................................ 456
Example ................................................................................................. 457
Android TextureView ............................................................ 464
Example ................................................................................................. 465
Android Twitter Integration ................................................... 472
Integrating Twitter SDK .......................................................................... 472
REGISTERING YOUR APPLICATION................................................... 472
DOWNLOADING SDK AND INTEGRATING IT .................................... 474
POSTING TWEETS ON TWITTER APPLICATION .............................. 474
INTENT SHARE .................................................................................... 474
Example ................................................................................................. 475
Android UI Design ................................................................ 482
UI screen components ........................................................................... 482
Understanding Screen Components ...................................................... 483
VIEW AND VIEWGROUPS .................................................................... 483
TYPES OF LAYOUT .............................................................................. 483
LINEARLAYOUT .................................................................................... 484
ABSOLUTELAYOUT .............................................................................. 484
TABLELAYOUT ..................................................................................... 484
RELATIVELAYOUT ............................................................................... 484
FRAMELAYOUT .................................................................................... 485
Units of Measurement ............................................................................ 485
Screen Densities .................................................................................... 486
Optimizing layouts .................................................................................. 486
Android UI Patterns .............................................................. 487
UI Patterns components ......................................................................... 487
Action Bar............................................................................................... 487
ACTION BAR COMPONENTS ............................................................... 487
Confirming and Acknowledging .............................................................. 488
CONFIRMING ........................................................................................ 488
ACKNOWLEDGING ............................................................................... 488
TUTORIALS POINT
Simply Easy Learning
Settings .................................................................................................. 489
PLACEMENT OF SETTINGS ................................................................ 489
Help ........................................................................................................ 489
PLACEMENT OF HELP ......................................................................... 489
Selection ................................................................................................ 489
USING CONTEXTUAL ACTION BAR (CAB) ......................................... 489
Android UI Testing ............................................................... 491
uiautomatorviewer .................................................................................. 491
uiautomator ............................................................................................ 495
Example ................................................................................................. 495
Android WebView Layout ..................................................... 500
Example ................................................................................................. 501
Android Wi-Fi ....................................................................... 507
Example ................................................................................................. 508
Android Widgets................................................................... 513
Widget - XML file .................................................................................... 513
Widget - Layout file ................................................................................ 513
Widget - Java file .................................................................................... 513
Widget - Manifest file .............................................................................. 514
Example ................................................................................................. 514
Android XML Parsers ........................................................... 520
XML - Elements ...................................................................................... 520
XML - Parsing ........................................................................................ 521
Example ................................................................................................. 522
TUTORIALS POINT
Simply Easy Learning
CHAPTER
18
Drag and Drop
A ndroid 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. The framework includes following three important
components to support drag & drop functionality:
Started: This event occurs when you start dragging an item in a layout, your application
callsstartDrag() 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.
TUTORIALS POINT
Simply Easy Learning
The DragEvent Class
The DragEvent represents an event that is sent out by the system at various times during a drag and drop
operation. This class provides few Constants and important methods which we use during Drag/Drop process.
CONSTANTS
Following are all constants integers available as a part of DragEvent class.
ACTION_DRAG_STARTED
1
Signals the start of a drag and drop operation.
ACTION_DRAG_ENTERED
2
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.
ACTION_DRAG_ENDED
6
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.
int getAction()
1
Inspect the action value of this event..
ClipData getClipData()
2
Returns the ClipData object sent to the system as part of the call to startDrag().
ClipDescription getClipDescription()
3
Returns the ClipDescription object contained in the ClipData.
boolean getResult()
4
Returns an indication of the result of the drag and drop operation.
float getX()
5
Gets the X coordinate of the drag point.
float getY()
6
Gets the Y coordinate of the drag point.
String toString()
7
Returns a string representation of this DragEvent object.
TUTORIALS POINT
Simply Easy Learning
Listening for Drag Event
If you want any of your views within a Layout should respond Drag event then your view either
implements View.OnDragListener or setup onDragEvent(DragEvent) callback method. When the system calls
the method or listener, it passes to them a DragEvent object explained above. You can have both a listener and a
callback method for View object. If this occurs, the system first calls the listener and then defined callback as long
as listener returns true.
The combination of the onDragEvent(DragEvent) method and View.OnDragListener is analogous to the
combination of the onTouchEvent() and View.OnTouchListener used with touch events in old versions of
Android.
Example
Following example shows the functionality of a simple Drag & Drop using aView.setOnLongClickListener() event
listener along with View.OnDragEventListener().
Step Description
You will use Eclipse IDE to create an Android application and name it as DragNDropDemounder a
1 package com.example.dragndropdemo. While creating this project, make sure youTarget SDK and Compile
With at the latest version of Android SDK to use higher levels of APIs.
Modify src/MainActivity.java file and add the code to define event listeners as well as a call back methods for the
2
logo image used in the example.
Copy image logo.png in res/drawable-* folders. You can use images with different resolution in case you want to
3
provide them for different devices.
4 Modify layout XML file res/layout/activity_main.xml to define default view of the logo images.
5 Run the application to launch Android emulator and verify the result of the changes done in the aplication.
package com.example.dragndropdemo;
import android.os.Bundle;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipDescription;
import android.util.Log;
import android.view.DragEvent;
import android.view.View;
import android.view.View.DragShadowBuilder;
import android.view.View.OnDragListener;
import android.widget.*;
TUTORIALS POINT
Simply Easy Learning
private static final String IMAGEVIEW_TAG = "Android Logo";
String msg;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ima = (ImageView)findViewById(R.id.iv_logo);
// Sets the tag
ima.setTag(IMAGEVIEW_TAG);
ima.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
ClipData.Item item = new ClipData.Item((CharSequence)v.getTag());
// Create and set the drag event listener for the View
ima.setOnDragListener( new 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;
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;
TUTORIALS POINT
Simply Easy Learning
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;
}
});
}
}
<ImageView
android:id="@+id/iv_logo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/logo"
android:contentDescription="@string/drag_drop" />
</RelativeLayout>
<string name="app_name">DragNDropDemo</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="drag_drop">Click on the image to drag and drop</string>
</resources>
<uses-sdk
TUTORIALS POINT
Simply Easy Learning
android:minSdkVersion="16"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.guidemo.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
Let's try to run your DragNDropDemo application. I assume you had created your AVD while doing environment
setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar.
Eclipse 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 do long click on the displayed android 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.
TUTORIALS POINT
Simply Easy Learning
TUTORIALS POINT
Simply Easy Learning
CHAPTER
19
Notifications
A ndroid 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.
For important messages to be given to the user, it is required to have more persistent method. Anotification is a
message you can display as an icon at the top of the device which we call notification bar or status bar.
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 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 just64 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 notifciation. The following screenshot shows such notification.
TUTORIALS POINT
Simply Easy Learning
Create and Send Notifications
You have simple way to create a notification. Follow the following steps in your application to create a notification:
mBuilder.setSmallIcon(R.drawable.notification_icon);
mBuilder.setContentTitle("Notification Alert, Click Me!");
mBuilder.setContentText("Hi, This is Android Notification Detail!");
You have plenty of optional properties which you can set for your notification. To learn more about them, see the
reference documentation for NotificationCompat.Builder.
TUTORIALS POINT
Simply Easy Learning
A PendingIntent object helps you to perform an action on your application’s behalf, often at a later time, without
caring of whether or not your application is running.
We take help of stack builder object which will contain an artificial back stack for the started Activity. This ensures
that navigating backward from the Activity leads out of your application to the Home screen.
// 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);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification build()
1
Combine all of the options that have been set and return a new Notification object.
TUTORIALS POINT
Simply Easy Learning
Set the text (first row) of the notification, in a standard notification.
Example
Following example shows the functionality of a Android notification using a NotificationCompat.BuilderClass
which has been introduced in Android 4.1.
Step Description
You will use Eclipse IDE to create an Android application and name it as NotificationDemounder a
1 package com.example.notificationdemo. While creating this project, make sure youTarget SDK and Compile
With at the latest version of Android SDK to use higher levels of APIs.
Modify src/MainActivity.java file and add the code to define three methods startNotification(), cancelNotification()
2
and updateNotification() to cover maximum functionality related to Android notifications.
Create a new Java file src/NotificationView.java, which will be used to display new layout as a part of new
3
activity which will be started when user will click any of the notifications
Copy image woman.png in res/drawable-* folders and this image will be used as Notification icons. You can use
4
images with different resolution in case you want to provide them for different devices.
5 Modify layout XML file res/layout/activity_main.xml to add three buttons in linear layout.
Create a new layout XML file res/layout/notification.xml. This will be used as layout file for new activity which will
6
start when user will click any of the notifications.
8 Run the application to launch Android emulator and verify the result of the changes done in the aplication.
TUTORIALS POINT
Simply Easy Learning
package com.example.notificationdemo;
import android.os.Bundle;
import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
mBuilder.setContentTitle("New Message");
mBuilder.setContentText("You've received new message.");
mBuilder.setTicker("New Message Alert!");
mBuilder.setSmallIcon(R.drawable.woman);
TUTORIALS POINT
Simply Easy Learning
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(NotificationView.class);
/* Adds the Intent that starts the Activity to the top of the stack */
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder.setContentTitle("Updated Message");
mBuilder.setContentText("You've got updated message.");
mBuilder.setTicker("Updated Message Alert!");
mBuilder.setSmallIcon(R.drawable.woman);
/* 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);
TUTORIALS POINT
Simply Easy Learning
mNotificationManager.notify(notificationID, mBuilder.build());
}
}
package com.example.notificationdemo;
import android.os.Bundle;
import android.app.Activity;
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button android:id="@+id/start"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/start_note"/>
<Button android:id="@+id/cancel"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/cancel_note" />
<Button android:id="@+id/update"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/update_note" />
</LinearLayout>
TUTORIALS POINT
Simply Easy Learning
Following will be the content of res/values/strings.xml to define two new constants:
<string name="app_name">NotificationDemo</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="start_note">Start Notification</string>
<string name="cancel_note">Cancel Notification</string>
<string name="update_note">Update Notification</string>
</resources>
<uses-sdk
android:minSdkVersion="17"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.notificationdemo.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
Let's try to run your NotificationDemo application. I assume you had created your AVD while doing environment
setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar.
Eclipse 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:
TUTORIALS POINT
Simply Easy Learning
Now click Start Notification 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:
TUTORIALS POINT
Simply Easy Learning
Now let's try to click on the image icon, this will launch your new activity which you have set using intent and you
will have following screen:
Next, you can click on "Detail of notification" and it will take you back to the main screen where you can try
using Update Notification button which will update existing notification and number will increase by 1 but if you
will send notification with new notification ID then it will keep adding in the stack and you see them separately
listed on the screen.
TUTORIALS POINT
Simply Easy Learning
mBuilder.setContentTitle("New Message");
mBuilder.setContentText("You've received new message.");
mBuilder.setTicker("New Message Alert!");
mBuilder.setSmallIcon(R.drawable.woman);
inboxStyle.addLine(events[i]);
}
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:
TUTORIALS POINT
Simply Easy Learning
TUTORIALS POINT
Simply Easy Learning
CHAPTER
20
Location Based Services
A ndroid location APIs make it easy for you to build location-aware applications, without needing to focus
on the details of the underlying location technology. This becomes possible with the help ofGoogle Play services,
which facilitates adding location awareness to your app with automated location tracking, geofencing, and activity
recognition.
This tutorial shows you how to use Location Services in your app to get the current location, get periodic location
updates, look up addresses etc.
float getAccuracy()
2
Get the estimated accuracy of this location, in meters.
double getAltitude()
3
Get the altitude if available, in meters above sea level.
float getBearing()
4
Get the bearing, in degrees.
double getLatitude()
5
Get the latitude, in degrees.
double getLongitude()
6
Get the longitude, in degrees.
float getSpeed()
7
Get the speed if it is available, in meters/second over ground.
boolean hasAccuracy()
8
True if this location has an accuracy.
9 boolean hasAltitude()
TUTORIALS POINT
Simply Easy Learning
True if this location has an altitude.
boolean hasBearing()
10
True if this location has a bearing.
boolean hasSpeed()
11
True if this location has a speed.
void reset()
12
Clears the contents of the location.
String toString()
19
Returns a string containing a concise, human-readable description of this object.
You should create the location client in onCreate() method of your activity class, then connect it in onStart(), so
that Location Services maintains the current location while your activity is fully visible. You should disconnect the
client in onStop() method, so that when your app is not visible, Location Services is not maintaining the current
location. This helps in saving battery power up-to a large extent.
TUTORIALS POINT
Simply Easy Learning
Get the Updated Location
If you are willing to have location updates, then apart from above mentioned interfaces, you will need to
implement LocationListener interface as well. This interface provide following callback method, which you need to
implement in your activity class:
setExpirationDuration(long millis)
1
Set the duration of this request, in milliseconds.
setExpirationTime(long millis)
2
Set the request expiration time, in millisecond since boot.
setFastestInterval(long millis)
3
Explicitly set the fastest interval for location updates, in milliseconds.
setInterval(long millis)
4
Set the desired interval for active location updates, in milliseconds.
setNumUpdates(int numUpdates)
5
Set the number of location updates.
setPriority(int priority)
6
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.
Check following example to have better understanding on how we use AynchTask in any Android application to get
work done in the background without interfering main task.
TUTORIALS POINT
Simply Easy Learning
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.
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.
Steps Description
Search for Google Play services option from the given package list under Extra and if its not installed, then
2 install it. The Google Play services SDK is saved in your Android SDK environment at <android-
sdk>/extras/google/google_play_services/.
You will use Eclipse IDE to create an Android application and name it as LBSDemo/i> under a
1 package com.example.lbsdemo. While creating this project, make sure you Target SDK andCompile With at the
latest version of Android SDK to use higher levels of APIs.
2 Add Google Play Service library in your project by following simple steps given below.
Modify src/MainActivity.java file and add required code as shown below to take care of getting current location
3
and its equivalent address.
Modify layout XML file res/layout/activity_main.xml to add all GUI components which include three buttons and
4
two text views to show location/address.
7 Run the application to launch Android emulator and verify the result of the changes done in the aplication.
TUTORIALS POINT
Simply Easy Learning
Let's add Google Play Service reference in the project. Right click on the project and select Build Path >
Configure Build Path > Android > and then click Add button which will show google-play-service_liboption to be
added, just double click on it, which will add required library reference and you will have window as follows:
package com.example.lbsdemo;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.location.LocationClient;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
TUTORIALS POINT
Simply Easy Learning
GooglePlayServicesClient.OnConnectionFailedListener
{
LocationClient mLocationClient;
private TextView addressLabel;
private TextView locationLabel;
private Button getLocationBtn;
private Button disconnectBtn;
private Button connectBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getLocationBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
displayCurrentLocation();
}
});
disconnectBtn = (Button) findViewById(R.id.disconnect);
disconnectBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
mLocationClient.disconnect();
locationLabel.setText("Got disconnected....");
}
});
connectBtn = (Button) findViewById(R.id.connect);
connectBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
mLocationClient.connect();
locationLabel.setText("Got connected....");
}
});
// Create the LocationRequest object
mLocationClient = new LocationClient(this, this, this);
}
@Override
protected void onStart() {
super.onStart();
// Connect the client.
mLocationClient.connect();
locationLabel.setText("Got connected....");
}
@Override
protected void onStop() {
// Disconnect the client.
mLocationClient.disconnect();
super.onStop();
locationLabel.setText("Got disconnected....");
}
@Override
public void onConnected(Bundle dataBundle) {
// Display the connection status
Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
}
@Override
public void onDisconnected() {
TUTORIALS POINT
Simply Easy Learning
// Display the connection status
Toast.makeText(this, "Disconnected. Please re-connect.",
Toast.LENGTH_SHORT).show();
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
// Display the error code on failure
Toast.makeText(this, "Connection Failure : " +
connectionResult.getErrorCode(),
Toast.LENGTH_SHORT).show();
}
public void displayCurrentLocation() {
// Get the current location's latitude & longitude
Location currentLocation = mLocationClient.getLastLocation();
String msg = "Current Location: " +
Double.toString(currentLocation.getLatitude()) + "," +
Double.toString(currentLocation.getLongitude());
/*
* When the task finishes, onPostExecute() displays the address.
*/
@Override
protected void onPostExecute(String address) {
// Display the current address in the UI
addressLabel.setText(address);
}
@Override
protected String doInBackground(Location... params) {
Geocoder geocoder =
new Geocoder(mContext, Locale.getDefault());
// Get the current location from the input parameter list
Location loc = params[0];
// Create a list to contain the result address
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(loc.getLatitude(),
loc.getLongitude(), 1);
} catch (IOException e1) {
Log.e("LocationSampleActivity",
"IO Exception in getFromLocation()");
e1.printStackTrace();
return ("IO Exception trying to get address");
} catch (IllegalArgumentException e2) {
// Error message to post in the log
TUTORIALS POINT
Simply Easy Learning
String errorString = "Illegal arguments " +
Double.toString(loc.getLatitude()) +
" , " +
Double.toString(loc.getLongitude()) +
" passed to address service";
Log.e("LocationSampleActivity", errorString);
e2.printStackTrace();
return errorString;
}
// If the reverse geocode returned an address
if (addresses != null && addresses.size() > 0) {
// Get the first address
Address address = addresses.get(0);
/*
* Format the first line of address (if available),
* city, and country name.
*/
String addressText = String.format(
"%s, %s, %s",
// If there's a street address, add it
address.getMaxAddressLineIndex() > 0 ?
address.getAddressLine(0) : "",
// Locality is usually a city
address.getLocality(),
// The country of the address
address.getCountryName());
// Return the text
return addressText;
} else {
return "No address found";
}
}
}// AsyncTask class
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button android:id="@+id/getLocation"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/get_location"/>
<Button android:id="@+id/disconnect"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/disconnect"/>
<Button android:id="@+id/connect"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/connect"/>
<TextView
android:id="@+id/locationLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
TUTORIALS POINT
Simply Easy Learning
<TextView
android:id="@+id/addressLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
<string name="app_name">LBSDemo</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="get_location">Get Location</string>
<string name="disconnect">Disconnect Service</string>
<string name="connect">Connect Service</string>
</resources>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.lbsdemo.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
Let's try to run your LBSDemo 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, Eclipse will display following window to select an option where you want to
run your Android application.
TUTORIALS POINT
Simply Easy Learning
Select mobile device as an option and then check your mobile device which will display following screen:
TUTORIALS POINT
Simply Easy Learning
Now to see location select Get Location Button which will display location information as follows:
TUTORIALS POINT
Simply Easy Learning
You can try by disconnecting location client using Disconnect Service and then connecting it by usingConnect
Service button. You can also modify to get location update as explained above and in Android Official
documentation.
TUTORIALS POINT
Simply Easy Learning
CHAPTER
21
Sending Email
Y ou have learnt Android Intent, which is an object carrying an intent ie. message from one component to
As such you do not need to develop your email client from scratch because they are already available like Gmail
and K9mail. But you will need to send email from your Android application, where you will have to write an Activity
that needs to launch an email client and sends an email using your Android device. For this purpose, your Activity
will send an ACTION_SEND along with appropriate data load, to the Android Intent Resolver. The specified
chooser gives the proper interface for the user to pick how to send your email data.
Following section explains different parts of our Intent object required to send an email.
emailIntent.setData(Uri.parse("mailto:"));
emailIntent.setType("text/plain");
EXTRA_BCC
1
A String[] holding e-mail addresses that should be blind carbon copied.
2 EXTRA_CC
TUTORIALS POINT
Simply Easy Learning
A String[] holding e-mail addresses that should be carbon copied.
EXTRA_EMAIL
3
A String[] holding e-mail addresses that should be delivered to.
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.
EXTRA_SUBJECT
5
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:
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 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. Second you will need to have an Email client like
GMail or K9mail installed on your device.
Step Description
You will use Eclipse IDE to create an Android application and name it as SendEmailDemounder
1 a package com.example.sendemaildemo. While creating this project, make sure youTarget
SDK and Compile With at the latest version of Android SDK to use higher levels of APIs.
2 Modify src/MainActivity.java file and add required code to take care of sending email.
Modify layout XML file res/layout/activity_main.xml add any GUI component if required. I'm
3
adding a simple button to launch Email Client.
Run the application to launch Android emulator and verify the result of the changes done in the
6
aplication.
package com.example.sendemaildemo;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
TUTORIALS POINT
Simply Easy Learning
import android.view.Menu;
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);
}
protected void sendEmail() {
Log.i("Send email", "");
String[] TO = {"amrood.admin@gmail.com"};
String[] CC = {"mcmohd@gmail.com"};
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setData(Uri.parse("mailto:"));
emailIntent.setType("text/plain");
emailIntent.putExtra(Intent.EXTRA_EMAIL, TO);
emailIntent.putExtra(Intent.EXTRA_CC, CC);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Your subject");
emailIntent.putExtra(Intent.EXTRA_TEXT, "Email message goes here");
try {
startActivity(Intent.createChooser(emailIntent, "Send mail..."));
finish();
Log.i("Finished sending email...", "");
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(MainActivity.this,
"There is no email client installed.", Toast.LENGTH_SHORT).show();
}
}
@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;
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button android:id="@+id/sendEmail"
android:layout_width="fill_parent"
TUTORIALS POINT
Simply Easy Learning
android:layout_height="wrap_content"
android:text="@string/compose_email"/>
</LinearLayout>
<string name="app_name">SendEmailDemo</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
<string name="compose_email">Compose Email</string>
</resources>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.sendemaildemo.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
Let's try to run your SendEmailDemo 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, Eclipse will display following window to select an option
where you want to run your Android application.
TUTORIALS POINT
Simply Easy Learning
Select your mobile device as an option and then check your mobile device which will display following screen:
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.
TUTORIALS POINT
Simply Easy Learning
You can modify either of the given default fields and finally use send email button (marked with red rectangle) to
send your email to the mentioned recipients.
TUTORIALS POINT
Simply Easy Learning
CHAPTER
22
Sending SMS
T here are following two ways to send SMS using Android device:
Once you have SmsManager object, you can use sendDataMessage() method to send SMS at the specified
mobile number as below:
Apart from the above method, there are few other important functions available in SmsManager class. These
methods are listed below:
TUTORIALS POINT
Simply Easy Learning
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.
Step Description
You will use Eclipse IDE to create an Android application and name it as SendSMSDemounder a
1 package com.example.sendsmsdemo. While creating this project, make sure youTarget SDK and Compile
With at the latest version of Android SDK to use higher levels of APIs.
2 Modify src/MainActivity.java file and add required code to take care of sending email.
Modify layout XML file res/layout/activity_main.xml add any GUI component if required. I'm adding a simple GUI
3
to take mobile number and SMS text to be sent and a simple button to send SMS.
6 Run the application to launch Android emulator and verify the result of the changes done in the aplication.
package com.example.sendsmsdemo;
import android.os.Bundle;
import android.app.Activity;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
Button sendBtn;
EditText txtphoneNo;
EditText txtMessage;
@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();
}
});
TUTORIALS POINT
Simply Easy Learning
}
protected void sendSMSMessage() {
Log.i("Send SMS", "");
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, message, null, null);
Toast.makeText(getApplicationContext(), "SMS sent.",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again.",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
@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;
}
}
<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/textViewPhoneNo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/phone_label" />
<EditText
android:id="@+id/editTextPhoneNo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="phone"/>
<TextView
android:id="@+id/textViewMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/sms_label" />
<EditText
android:id="@+id/editTextSMS"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textMultiLine"/>
<Button android:id="@+id/btnSendSMS"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
TUTORIALS POINT
Simply Easy Learning
android:text="@string/send_sms_label"/>
</LinearLayout>
<string name="app_name">SendSMSDemo</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="phone_label">Enter Phone Number:</string>
<string name="sms_label">Enter SMS Message:</string>
<string name="send_sms_label">Send SMS</string>
</resources>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.SEND_SMS" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.sendsmsdemo.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
Let's try to run your SendSMSDemo 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, Eclipse will display following window to select an option where
you want to run your Android application.
TUTORIALS POINT
Simply Easy Learning
Select your mobile device as an option and then check your mobile device which will display following screen:
TUTORIALS POINT
Simply Easy Learning
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 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.
smsIntent.setData(Uri.parse("smsto:"));
smsIntent.setType("vnd.android-dir/mms-sms");
Here address and sms_body are case sensitive and should be specified in small characters only. You can specify
more than one number in single string but separated by semi-colon (;).
Example
Following example shows you in practical how to use Intent object to launch SMS client to send an SMS to the
given recipients.
To experiment with this example, you will need actual Mobile device equipped with latest Android OS, otherwise
you will have to struggle with emulator which may not work.
Step Description
You will use Eclipse IDE to create an Android application and name it as SendSMSDemounder a
1 package com.example.sendsmsdemo. While creating this project, make sure youTarget SDK and Compile
With at the latest version of Android SDK to use higher levels of APIs.
2 Modify src/MainActivity.java file and add required code to take care of sending SMS.
3 Modify layout XML file res/layout/activity_main.xml add any GUI component if required. I'm adding a simple
TUTORIALS POINT
Simply Easy Learning
button to launch SMS Client.
6 Run the application to launch Android emulator and verify the result of the changes done in the aplication.
package com.example.sendsmsdemo;
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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
protected void sendSMS() {
Log.i("Send SMS", "");
TUTORIALS POINT
Simply Easy Learning
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button android:id="@+id/sendSMS"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/compose_sms"/>
</LinearLayout>
<string name="app_name">SendSMSDemo</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
<string name="compose_sms">Compose SMS</string>
</resources>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.sendsmsdemo.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
Let's try to run your SendSMSDemo 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
TUTORIALS POINT
Simply Easy Learning
from the toolbar. Before starting your application, Eclipse 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:
Now use Compose SMS button to launch Android built-in SMS clients which is shown below:
TUTORIALS POINT
Simply Easy Learning
You can modify either of the given default fields and finally use send SMS button (marked with red rectangle) to
send your SMS to the mentioned recipient.
TUTORIALS POINT
Simply Easy Learning
CHAPTER
23
Phone Calls
A s such every Android Device specially Mobile phone is meant to provide a functionality to make a phone
call but still you may need to write an application where you want to give an option to your user to make a call
using a hard coded phone number.
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-800-001-0101"));
The interesting point is that, to make a phone call, you do not need to specify any extra data or data type.
Example
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.
Step Description
1 You will use Eclipse IDE to create an Android application and name it as PhoneCallDemounder a
TUTORIALS POINT
Simply Easy Learning
package com.example.phonecalldemo. While creating this project, make sure youTarget SDK and Compile
With at the latest version of Android SDK to use higher levels of APIs.
2 Modify src/MainActivity.java file and add required code to take care of making a call.
Modify layout XML file res/layout/activity_main.xml add any GUI component if required. I'm adding a simple
3
button to Call 91-800-001-0101 number
6 Run the application to launch Android emulator and verify the result of the changes done in the aplication.
package com.example.phonecalldemo;
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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
protected void makeCall() {
Log.i("Make call", "");
try {
startActivity(phoneIntent);
finish();
Log.i("Finished making a call...", "");
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(MainActivity.this,
"Call 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.
TUTORIALS POINT
Simply Easy Learning
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button android:id="@+id/makeCall"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/make_call"/>
</LinearLayout>
<string name="app_name">PhoneCallDemo</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
<string name="make_call">Call 91-800-001-0101</string>
</resources>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.phonecalldemo.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
TUTORIALS POINT
Simply Easy Learning
</manifest>
Let's try to run your PhoneCallDemo 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, Eclipse 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:
Now use Call 91-800-001-0101 button to make phone call as shown below:
TUTORIALS POINT
Simply Easy Learning
TUTORIALS POINT
Simply Easy Learning
CHAPTER
24
Publishing Android
Application
A ndroid Application publishing is a process that makes your Android applications available to users.
Infact, publishing is the last phase of the Android application development process.
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:
Step Activity
Regression Testing Before you publish your application, you need to make sure that its meeting the basic
1 quality expectations for all Android apps, on all of the devices that you are targeting. So perform all the required
testing on different devices including phone and tablets.
Application Rating When you will publish your application at Google Play, you will have to specify a content
2 rating for your app, which informs Google Play users of its maturity level. Currently available ratings are (a)
Everyone (b) Low maturity (c) Medium maturity (d) High maturity.
Targeted Regions Google Play lets you control what countries and territories where your application will be
3 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
4 exceeds that size, or if you want to offer a secondary 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 designed to run properly on the
5
Android platform versions and device screen sizes that you want to target.
TUTORIALS POINT
Simply Easy Learning
Application Pricing Deciding whether you app will be free or paid is important because, on Google Play, free
6 apps must remain free. If you want to sell your application then you will have to specify its price in different
currencies.
Promotional Content It is a good marketing practice to supply a variety of high-quality graphic assets to
7 showcase your app or brand. After you publish, these appear on your product details page, in store listings and
search results, and elsewhere.
Build and Upload release-ready APK The release-ready APK is what you you will upload to the Developer
8 Console and distribute to users. You can check complete detail on how to create a release-ready version of your
app: Preparing for Release.
Finalize Application Detail Google Play gives you a variety of ways to promote your app and engage with
users on your product details page, from colorful graphics, screenshots, and videos to localized descriptions,
9
release details, and links to your other apps. So you can decorate your application page and provide as much as
clear crisp detail you can provide.
To export an application, just open that application project in Eclipse and select File->Export from your Eclipse
and follow the simple steps to export your application:
TUTORIALS POINT
Simply Easy Learning
Next select, Export Android Application option as shown in the above screen shot and then click Nextand
again Next so that you get following screen where you will choose Create new keystore to store your
application.
Enter your password to protect your application and click on Next button once again. It will display following
screen to let you create a key for your application:
TUTORIALS POINT
Simply Easy Learning
Once you filled up all the information, click Next button and finally it will ask you a location where Application will
be exported:
TUTORIALS POINT
Simply Easy Learning
Finally, you click on Finish button to generate your Android Application Package File which will be uploaded at
Google Play marketplace.
TUTORIALS POINT
Simply Easy Learning
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.
TUTORIALS POINT
Simply Easy Learning
CHAPTER
25
Android Alert Dialoges
S ome times in your application , if you wanted to ask the user about taking a decision between yes or no in
response of any particular action taken by the user, by remaining in the same activity and without changing the
screen, you can use Alert Dialog.
In order to make an alert dialog , you need to make an object of AlertDialogBuilder which an inner class of
AlertDialog. Its syntax is given below
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
setIcon(Drawable icon)
1
This method set the icon of the alert dialog box.
setCancelable(boolean cancelable)
2
This method sets the property that the dialog can be cancelled or not
setMessage(CharSequence message)
3
This method sets the message to be displayed in the alert dialog
setOnCancelListener(DialogInterface.OnCancelListener onCancelListener)
5
This method Sets the callback that will be called if the dialog is canceled.
setTitle(CharSequence title)
6
This method set the title to be appear in the dialog
TUTORIALS POINT
Simply Easy Learning
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.
Example
The following example demonstrates the use of AlertDialog in android. It uses three different activities to
demonstrate it. The dialog asks you to jump to positive activity or negative activity or cancel it.
To experiment with this example , you need to run this on an emulator or an actual device.
Steps Description
You will use Eclipse IDE to create an Android application and name it as AlertDialog under a package
1 com.example.alertdialog. While creating this project, make sure you Target SDK and Compile With at the
latest version of Android SDK to use higher levels of APIs.
2 Modify src/MainActivity.java file to add alert dialog code to launch the dialog.
3 Modify layout XML file res/layout/activity_main.xml add any GUI component if required.
Modify layout XML file of the newly created activity res/layout/activity_positive.xml add any GUI
5
component if required.
Modify layout XML file of the newly created activity res/layout/activity_negative.xml add any GUI
7
component if required.
Run the application and choose a running android device and install the application on it and verify the
9
results.
package com.example.alertdialog;
import com.example.alertdialog.*;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TUTORIALS POINT
Simply Easy Learning
}
@Override
public void onClick(DialogInterface arg0, int arg1) {
Intent positveActivity = new
Intent(getApplicationContext(),com.example.alertdialog.PositiveActivity.class);
startActivity(positveActivity);
}
});
alertDialogBuilder.setNegativeButton(R.string.negative_button,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent negativeActivity = new
Intent(getApplicationContext(),com.example.alertdialog.NegativeActivity.class);
startActivity(negativeActivity);
}
});
@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;
}
}
package com.example.alertdialog;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_positive);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.positive, menu);
return true;
TUTORIALS POINT
Simply Easy Learning
}
package com.example.alertdialog;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_negative);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.negative, menu);
return true;
}
<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" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="170dp"
android:onClick="open"
android:text="@string/hello_world" />
</RelativeLayout>
<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"
TUTORIALS POINT
Simply Easy Learning
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=".PositiveActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="14dp"
android:layout_marginTop="20dp"
android:text="@string/positive"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
<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=".NegativeActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="14dp"
android:layout_marginTop="17dp"
android:text="@string/negative"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
<string name="app_name">AlertDialog</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="title_activity_positive">PositiveActivity</string>
<string name="title_activity_negative">NegativeActivity</string>
<string name="positive">Positive Activity</string>
<string name="negative">Negative Activity</string>
<string name="decision">Are you sure, you wanted to make this decision</string>
<string name="positive_button">+ive</string>
<string name="negative_button">-ive</string>
TUTORIALS POINT
Simply Easy Learning
</resources>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.alertdialog.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
Let's try to run your Camera 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, Eclipse will display following window to select an option where you want to
run your Android application.
TUTORIALS POINT
Simply Easy Learning
Select your mobile device as an option and then check your mobile device which will display following screen:
TUTORIALS POINT
Simply Easy Learning
Now just tap the button hello world to see the alert box , which would be something like this
TUTORIALS POINT
Simply Easy Learning
Now select any of the two buttons and see the respective activity loading up. In case you select positve button ,
this screen would appear
TUTORIALS POINT
Simply Easy Learning
Now press back button on your device , and this time select negative from your alert dialog. The following screen
would appear this time
TUTORIALS POINT
Simply Easy Learning
TUTORIALS POINT
Simply Easy Learning
CHAPTER
26
Android Animations
A nimation in Android is possible from many ways. In this chapter we will discuss one easy and widely
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 povided us a class called Animation.
In order to perform animation in android , we are going to call a static function loadAnimation() of the class
AnimationUtils. We are going to recieve the result in an instance of Animation Object. Its syntax is as follows:
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 usefull 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.
In order to apply this animation to an object , we will just call the startAnimation() method of the object. Its syntax
is:
TUTORIALS POINT
Simply Easy Learning
ImageView image1 = (ImageView)findViewById(R.id.imageView1);
image.startAnimation(animation);
Zoom in animation
In order to perform a zoom in animation , create an XML file under anim folder under res directory and put this
code in the file.
<set xmlns:android="http://schemas.android.com/apk/res/android">
<scale xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXScale="0.5"
android:toXScale="3.0"
android:fromYScale="0.5"
android:toYScale="3.0"
android:duration="5000"
android:pivotX="50%"
android:pivotY="50%" >
</scale>
</set>
The parameter fromXScale and fromYScale defines the start point and the
parameters toXScale andtoYScale defines the end point. The duration defines the time of animation and
the pivotX,pivotYdefines the center from where the animation would start.
Example
The following example demonstrates the use of Animation in android. You would be able to choose different type
of animation from the menu and the selected animation will be applied on an imageView on the screen.
To experiment with this example , you need to run this on an emulator or an actual device.
Steps Description
You will use Eclipse IDE to create an Android application and name it as Animation under a package
1 com.example.animation. While creating this project, make sure you Target SDK and Compile With at the
latest version of Android SDK to use higher levels of APIs.
3 Modify layout XML file res/layout/activity_main.xml add any GUI component if required.
4 Create a new folder under res directory and call it anim. Confim it by visiting res/anim
Right click on anim and click on new and select Android XML file You have to create three different files
5
that are listed below.
Run the application and choose a running android device and install the application on it and verify the
9
results.
TUTORIALS POINT
Simply Easy Learning
Here is the modified code of src/com.example.animation/MainActivity.java.
package com.example.animation;
import com.example.animation.R;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@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;
}
}
return false;
}
TUTORIALS POINT
Simply Easy Learning
<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:gravity="top"
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" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="179dp"
android:src="@drawable/ic_launcher" />
</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"
android:duration="5000"
android:pivotX="50%"
android:pivotY="50%" >
</scale>
</set>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="0"
TUTORIALS POINT
Simply Easy Learning
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"
android:toAlpha="0"
android:duration="2000" >
</alpha>
</set>
<item
android:id="@+id/rotate360"
android:orderInCategory="100"
android:showAsAction="never"
android:title="@string/rotate_String"/>
<item
android:id="@+id/zoomInOut"
android:orderInCategory="100"
android:title="@string/zoom_In_Out"/>
<item
android:id="@+id/fadeInOut"
android:orderInCategory="100"
TUTORIALS POINT
Simply Easy Learning
android:title="@string/fade_String"/>
</menu>
<string name="app_name">Animation</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="zoom_In_Out">Zoom In/Out</string>
<string name="rotate_String">Clockwise/Anti Clockwise</string>
<string name="fade_String">Fade In/Out</string>
</resources>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<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" />
</manifest>
Let's try to run your Animation 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, Eclipse will display following window to select an option where you want to
run your Android application.
TUTORIALS POINT
Simply Easy Learning
Select your mobile device as an option and then check your mobile device which will display following screen:
TUTORIALS POINT
Simply Easy Learning
Now just select the menu from your mobile, and a menu would appear which would be something like this:
TUTORIALS POINT
Simply Easy Learning
Now just select the Zoom in , Zoom out option from menu and an animation would appear which would be
something like this:
TUTORIALS POINT
Simply Easy Learning
Now just select the clockwise option from menu and an animation would appear which would be something like
this:
TUTORIALS POINT
Simply Easy Learning
Now just select the fade in/out option from menu and an animation would appear which would be something like
this:
TUTORIALS POINT
Simply Easy Learning
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.
TUTORIALS POINT
Simply Easy Learning
CHAPTER
27
Android Audio Capture
A ndroid has a built in microphone through which you can capture audio and store it , or play it in your
phone. There are many ways to do that but the most common way is through MediaRecorder class.
Android provides MediaRecorder class to record audio or video. In order to use MediaRecorder class ,you will first
create an instance of MediaRecorder class. Its syntax is given below.
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_GPP);
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 perpare
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.
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
setOutputFile()
5
This method configures the path to the file into which the recorded audio is to be stored
TUTORIALS POINT
Simply Easy Learning
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.
Steps Description
You will use Eclipse IDE to create an Android application and name it as AudioCapture under a package
1 com.example.audiocapture. While creating this project, make sure you Target SDK and Compile With at
the latest version of Android SDK to use higher levels of APIs.
3 Modify layout XML file res/layout/activity_main.xml add any GUI component if required.
Run the application and choose a running android device and install the application on it and verify the
6
results.
package com.example.audiocapture;
import java.io.File;
import java.io.IOException;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
stop.setEnabled(false);
TUTORIALS POINT
Simply Easy Learning
play.setEnabled(false);
outputFile = Environment.getExternalStorageDirectory().
getAbsolutePath() + "/myrecording.3gp";;
TUTORIALS POINT
Simply Easy Learning
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="32dp"
android:text="@string/Recording"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ImageView
android:id="@+id/imageView1"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="37dp"
android:scaleType="fitXY"
android:src="@android:drawable/presence_audio_online" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/imageView1"
android:layout_marginTop="67dp"
android:layout_toLeftOf="@+id/imageView1"
android:onClick="start"
android:text="@string/start" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/button1"
android:layout_alignBottom="@+id/button1"
android:layout_alignRight="@+id/textView1"
android:layout_marginRight="40dp"
android:onClick="stop"
android:text="@string/stop" />
<Button
android:id="@+id/button3"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button2"
android:layout_centerHorizontal="true"
android:onClick="play"
android:text="@string/play" />
TUTORIALS POINT
Simply Easy Learning
</RelativeLayout>
<string name="app_name">AudioCapture</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="Recording">Android Audio Recording Application</string>
<string name="start">start</string>
<string name="stop">stop</string>
<string name="play">play</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.audiocapture"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.audiocapture.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
Let's try to run your AndroidCapture 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, Eclipse will display following window to select an option where
you want to run your Android application.
TUTORIALS POINT
Simply Easy Learning
Select your mobile device as an option and then check your mobile device which will display following screen:
TUTORIALS POINT
Simply Easy Learning
Now by default you will see stop and play button disable. Just press the start button and your application will start
recording the audio. It will display the following screen.
TUTORIALS POINT
Simply Easy Learning
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.
TUTORIALS POINT
Simply Easy Learning
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.
TUTORIALS POINT
Simply Easy Learning
TUTORIALS POINT
Simply Easy Learning
CHAPTER
28
Android AudioManager
Y ou can easily control your ringer volume and ringer profile i-e:(silent,vibrate,loud e.t.c) in android.
In order to use AndroidManager class, you have to first create an object of AudioManager class by calling
the getSystemService() method. Its syntax is given below.
Once you instantiate the object of AudioManager class, you can use setRingerMode method to set the audio or
ringer profile of your device. Its syntax is given below.
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
The method setRingerMode takes an integer number as a parameter. For each mode , an integer number is
assigned that will differentiate between different modes. The possible modes are.
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 availaible in the AudioManager class to control
the volume and other modes. They are listed below.
TUTORIALS POINT
Simply Easy Learning
getMode()
2
This method returns the current audio mode
getStreamMaxVolume(int streamType)
3
This method returns the maximum volume index for a particular stream
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 crates a basic application that allows you to
set differnet ringer modes for your device.
To experiment with this example , you need to run this on an actual device.
Steps Description
You will use Eclipse IDE to create an Android application and name it as AudioManager under a package
1 com.example.audiomanager. While creating this project, make sure you Target SDK and Compile With at
the latest version of Android SDK to use higher levels of APIs.
3 Modify layout XML file res/layout/activity_main.xml add any GUI component if required.
Run the application and choose a running android device and install the application on it and verify the
6
results.
package com.example.audiomanager;
import android.media.AudioManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
TUTORIALS POINT
Simply Easy Learning
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Vibrate = (Button)findViewById(R.id.button2);
Ring = (Button)findViewById(R.id.button4);
Silent = (Button)findViewById(R.id.button3);
Mode = (Button)findViewById(R.id.button1);
Status = (TextView)findViewById(R.id.textView2);
myAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
}
}
@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;
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
TUTORIALS POINT
Simply Easy Learning
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="25dp"
android:text="@string/audio"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/button3"
android:layout_alignBottom="@+id/button3"
android:layout_alignRight="@+id/textView1"
android:onClick="vibrate"
android:text="@string/Vibrate" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="144dp"
android:layout_marginLeft="40dp"
android:layout_toLeftOf="@+id/button2"
android:onClick="silent"
android:text="@string/Silent" />
<Button
android:id="@+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/button1"
android:layout_alignBottom="@+id/button1"
android:layout_toRightOf="@+id/button1"
android:onClick="ring"
android:text="@string/Ring" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/button2"
android:layout_alignLeft="@+id/button3"
android:layout_marginBottom="15dp"
android:onClick="mode"
android:text="@string/Mode" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="46dp"
android:text="@string/Status"
android:textAppearance="?android:attr/textAppearanceMedium" />
TUTORIALS POINT
Simply Easy Learning
</RelativeLayout>
Here is the content of Strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">AudioManager</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="audio">Set Audio Profiles</string>
<string name="Ring">Ring</string>
<string name="Vibrate">Vibrate</string>
<string name="Silent">Silent</string>
<string name="Mode">Current Mode</string>
<string name="Status">Current Status</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.audiomanager"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.audiomanager.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
Let's try to run your Androidmanager 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, Eclipse will display following window to select an option where
you want to run your Android application.
TUTORIALS POINT
Simply Easy Learning
Select your mobile device as an option and then check your mobile device which will display following screen.
TUTORIALS POINT
Simply Easy Learning
Now just select the ring button and then press the current mode button to see that if its status has been set.
TUTORIALS POINT
Simply Easy Learning
Now press the silent button and then press the current mode button to see that if it is set or not.It will display the
following screen.
TUTORIALS POINT
Simply Easy Learning
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.
TUTORIALS POINT
Simply Easy Learning
TUTORIALS POINT
Simply Easy Learning
CHAPTER
29
Android Auto Complete
I f you want to get suggestions, when you type in an editable text field , you can do this via
AutoCompleteTextView. It provides suggestions automatically when the user is typing. The list of suggestions is
displayed in a drop down menu from which the user can choose an item to replace the content of the edit box with.
In order to use AutoCompleteTextView you have to first create an AutoCompletTextView Field in the xml. Its
syntax is given below.
<AutoCompleteTextView
android:id="@+id/autoCompleteTextView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="65dp"
android:ems="10" >
After that , you have to get a reference of this textview in java. Its syntax is given below.
The the next thing you need to do is to specify the list of suggestions items to be dispalyed. You can specify the list
items as a string array in java or in strings.xml. Its syntax is given below.
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 AutoCompelte are listed below.
getAdapter()
1
This method returns a filterable list adapter used for auto completion
TUTORIALS POINT
Simply Easy Learning
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.
Steps Description
You will use Eclipse IDE to create an Android application and name it as AutoComplete under a package
1 com.example.autocomplete. While creating this project, make sure you Target SDK and Compile With at
the latest version of Android SDK to use higher levels of APIs.
3 Modify layout XML file res/layout/activity_main.xml add any GUI component if required.
Run the application and choose a running android device and install the application on it and verify the
6
results.
package com.example.autocomplete;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.MultiAutoCompleteTextView;
TUTORIALS POINT
Simply Easy Learning
private MultiAutoCompleteTextView mactv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
actv.setAdapter(adapter);
mactv.setAdapter(adapter);
mactv.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
@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;
}
<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" >
<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" >
<requestFocus />
</AutoCompleteTextView>
<MultiAutoCompleteTextView
TUTORIALS POINT
Simply Easy Learning
android:id="@+id/multiAutoCompleteTextView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/autoCompleteTextView1"
android:layout_centerVertical="true"
android:ems="10" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="@string/auto_complete"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/multiAutoCompleteTextView1"
android:layout_alignParentLeft="true"
android:layout_marginBottom="19dp"
android:text="@string/multi_auto_complete"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
<string name="app_name">AutoComplete</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="auto_complete">AutoComplete</string>
<string name="multi_auto_complete">Multi AutoComplete</string>
<string-array name="list_of_countries">
<item >USA</item>
<item >Uk</item>
<item >Canada</item>
<item >Australia</item>
<item >France</item>
<item >Italy</item>
<item >China</item>
<item >Japan</item>
<item >Spain</item>
</string-array>
</resources>
TUTORIALS POINT
Simply Easy Learning
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.autocomplete.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
Let's try to run your Androidmanager application. I assume you have connected your AVD while doing environment
setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar.
Ecclipse will install this application in your AVD and your AVD will display following screen.
TUTORIALS POINT
Simply Easy Learning
Now just type in the text view to see suggestions of the country. As i just type two two letters which areca, and it
shows me suggestion of canada.
TUTORIALS POINT
Simply Easy Learning
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.
TUTORIALS POINT
Simply Easy Learning
TUTORIALS POINT
Simply Easy Learning
CHAPTER
30
Android Best Practices
T here are some practices that you can follow while developing android application. These are suggested by
the android itself and they keep on improving with respect to time.
These best practices include interaction design features , performance , security and privacy , compatibility ,
testing , distributing and monetizing tips. They are narrowed down and are listed as below.
<EditText
android:id="@+id/phone"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="phone" />
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:id="@+id/password"
android:hint="@string/password_hint"
android:inputType="textPassword" />
ASYNCTASK VS SERVICES.
Both are used for doing background tasks , but the service is not affected by most user inteface life cycle events,
so it continues to run in circumstances that would shut down an AsyncTask.
TUTORIALS POINT
Simply Easy Learning
Best Practices - Performance
Your application peformance should be upto the mark. But it should perform differently not on the front end , but on
the back end when it the device is connected to a power source or charging. Charging could be of from USB and
from wire cable.
When your device is charging itself , it is recommended to update your application settings if any, such as
maximizing your refresh rate whenver the device is connected. It can be done as this.
1. Use internal storage rather then external for storing applications files
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.
Steps Description
You will use Eclipse IDE to create an Android application and name it as BestPractices under a package
1 com.example.autocomplete. While creating this project, make sure you Target SDK and Compile With at
the latest version of Android SDK to use higher levels of APIs.
3 Modify layout XML file res/layout/activity_main.xml add any GUI component if required.
Run the application and choose a running android device and install the application on it and verify the
6
results.
TUTORIALS POINT
Simply Easy Learning
package com.example.bestpractices;
import android.os.BatteryManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
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
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;
}
<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"
TUTORIALS POINT
Simply Easy Learning
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="22dp"
android:layout_marginTop="20dp"
android:text="@string/username"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="@+id/message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:ems="10"
android:inputType="textCapSentences|textAutoCorrect" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView2"
android:layout_below="@+id/textView2"
android:layout_marginTop="34dp"
android:ems="10"
android:hint="@string/password_hint"
android:inputType="textPassword" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/textView1"
android:layout_below="@+id/message"
android:layout_marginTop="50dp"
android:text="@string/password"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/password"
android:layout_centerHorizontal="true"
android:layout_marginTop="34dp"
android:onClick="check"
android:text="@string/check" />
TUTORIALS POINT
Simply Easy Learning
</RelativeLayout>
<string name="app_name">BestPractices</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="password_hint">Hello world!</string>
<string name="check">Charging check</string>
</resources>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.bestpractices.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
Let's try to run your BestPractices 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, Eclipse will display following window to select an option where
you want to run your Android application.
TUTORIALS POINT
Simply Easy Learning
Select your mobile device as an option and then check your mobile device which will display following screen.
TUTORIALS POINT
Simply Easy Learning
Now jsut type on the username field and you will see the built in android suggestions from the dictionary will start
coming up. This is shown below.
TUTORIALS POINT
Simply Easy Learning
Now you will see the hint in the password field. It would disappera as soon as you start writing in the field. It is
shown below.
TUTORIALS POINT
Simply Easy Learning
In the end , just connect your device to AC cable or USB cable and press on charging check button. In my case , i
connect it with a PC via USB cable so it shows the following message.
TUTORIALS POINT
Simply Easy Learning
TUTORIALS POINT
Simply Easy Learning
CHAPTER
31
Android Bluetooth
A mong many ways, Bluetooth is a way to send or recieve data between two different devices. Android
platform includes support for the Bluetooth framework that allows a device to wirelessly exchange data with other
Bluetooth devices.
Android provides BluetoothAdapter class to communicate with Bluetooth. Create an object of this calling by calling
the static method getDefaultAdapter(). Its syntax is given below.
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 , ther are other constanst provided the API , that supports differnet tasks. They are listed
below.
ACTION_REQUEST_DISCOVERABLE
1
This constant is used for turn on discovering of bluetooth
ACTION_STATE_CHANGED
2
This constant will notify that Bluetooth state has been changed
ACTION_FOUND
3
This constant is used for recieving information about each device that is discovered
TUTORIALS POINT
Simply Easy Learning
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.
private Set<BluetoothDevice>pairedDevices;
pairedDevices = BA.getBondedDevices();
Apart form the pariredDevices , there are other methods in the API that gives more control over Blueetooth. THey
are listed below.
enable()
1
This method enables the adapter if not enabled
isEnabled()
2
This method returns true if adapter is enabled
disable()
3
This method disables the adapter
getName()
4
This method returns the name of the Bluetooth adapter
setName(String name)
5
This method changes the Bluetooth name
getState()
6
This method returns the current state of the Bluetooth Adapter.
startDiscovery()
7
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.
Steps Description
You will use Eclipse IDE to create an Android application and name it as AudioCapture under a package
1 com.example.audiocapture. While creating this project, make sure you Target SDK and Compile With at
the latest version of Android SDK to use higher levels of APIs.
3 Modify layout XML file res/layout/activity_main.xml add any GUI component if required.
Run the application and choose a running android device and install the application on it and verify the
6
results.
TUTORIALS POINT
Simply Easy Learning
package com.example.bluetooth;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import android.os.Bundle;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
lv = (ListView)findViewById(R.id.listView1);
BA = BluetoothAdapter.getDefaultAdapter();
}
TUTORIALS POINT
Simply Easy Learning
(this,android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
}
public void off(View view){
BA.disable();
Toast.makeText(getApplicationContext(),"Turned off" ,
Toast.LENGTH_LONG).show();
}
public void visible(View view){
Intent getVisible = new Intent(BluetoothAdapter.
ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(getVisible, 0);
}
@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;
}
<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" >
<ScrollView
android:id="@+id/scrollView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app_name"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
TUTORIALS POINT
Simply Easy Learning
android:layout_height="wrap_content"
android:onClick="on"
android:text="@string/on" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="visible"
android:text="@string/Visible" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="list"
android:text="@string/List" />
<Button
android:id="@+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="off"
android:text="@string/off" />
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="visible" >
</ListView>
</LinearLayout>
</ScrollView>
</RelativeLayout>
<string name="app_name">Bluetooth</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="on">Turn On</string>
<string name="off">Turn Off</string>
<string name="Visible">Get Visible</string>
<string name="List">List Devices</string>
</resources>
TUTORIALS POINT
Simply Easy Learning
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.bluetooth.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
Let's try to run your AndroidCapture 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, Eclipse will display following window to select an option where
you want to run your Android application.
TUTORIALS POINT
Simply Easy Learning
Select your mobile device as an option and then check your mobile device which will display following screen:
TUTORIALS POINT
Simply Easy Learning
Now select Turn On to turn on the bluetooth. But as you select it , your Bluetooth will not be turned on. Infact , it
will ask your permission to enable the Bluetooth.
TUTORIALS POINT
Simply Easy Learning
Now just select the Get Visible button to turn on your visibiltiy. The following screen would appear asking your
permission to turn on discovery for 120 seconds.
TUTORIALS POINT
Simply Easy Learning
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.
TUTORIALS POINT
Simply Easy Learning
Now just select the Turn off button to switch off the Bluetooth. Following message would appear when you swithc
off the bluetooth indicating the successfull swithching off of Bluetooth.
TUTORIALS POINT
Simply Easy Learning
TUTORIALS POINT
Simply Easy Learning
CHAPTER
32
Android Camera
T hese are the following two ways , in which you can use camera in your application
Apart from the above , there are other availaible Intents provided by MediaStore. They are listed as follows
ACTION_IMAGE_CAPTURE_SECURE
1
It returns the image captured from the camera , when the device is secured
ACTION_VIDEO_CAPTURE
2
It calls the existing video application in android to capture video
EXTRA_SCREEN_ORIENTATION
3
It is used to set the orientation of the screen to vertical or landscape
EXTRA_FULL_SCREEN
4
It is used to control the user interface of the ViewImage
INTENT_ACTION_VIDEO_CAMERA
5
This intent is used to launch the camea in the video mode
EXTRA_SIZE_LIMIT
6
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
TUTORIALS POINT
Simply Easy Learning
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
No matter which function you used to launch the activity , they all return the result. The result can be obtained by
overriding the function onActivityResult.
Example
Here is an example that shows how to launch the exisitng 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.
Steps Description
You will use Eclipse IDE to create an Android application and name it as Camera under a package
1 com.example.camera. While creating this project, make sure you Target SDK and Compile With at the
latest version of Android SDK to use higher levels of APIs.
Modify src/MainActivity.java file to add intent code to launch the activity and result method to recieve the
2
output.
Modify layout XML file res/layout/activity_main.xml add any GUI component if required. Here we add only
3
imageView and a textView.
Run the application and choose a running android device and install the application on it and verify the
5
results.
package com.example.camera;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
TUTORIALS POINT
Simply Easy Learning
import android.graphics.Bitmap;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
ImageView imgFavorite;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgFavorite = (ImageView)findViewById(R.id.imageView1);
imgFavorite.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
open();
}
});
}
public void open(){
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 0);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
Bitmap bp = (Bitmap) data.getExtras().get("data");
imgFavorite.setImageBitmap(bp);
}
@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;
}
}
<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">
<ImageView
android:id="@+id/imageView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="34dp"
TUTORIALS POINT
Simply Easy Learning
android:layout_marginTop="36dp"
android:contentDescription="@string/hello_world"
android:src="@drawable/ic_launcher" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignRight="@+id/imageView1"
android:text="@string/tap"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.camera.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
Let's try to run your Camera 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, Eclipse will display following window to select an option where you want to
run your Android application.
TUTORIALS POINT
Simply Easy Learning
Select your mobile device as an option and then check your mobile device which will display following screen:
TUTORIALS POINT
Simply Easy Learning
Now just tap on the image of android icon and the camera will be opened. Just capture a picture. After capturing it
, two buttons will appear asking you to discard it or keep it
TUTORIALS POINT
Simply Easy Learning
Just press the tic (green) button and you will be brought back to your application with the captured image inplace
of android icon
TUTORIALS POINT
Simply Easy Learning
Directly using Camera API provided by android in our
application
We will be using the camera API to integrate the camera in our application
First you will need to intialize the camera object using the static method provide by the api calledCamera.open. Its
syntax is
Apart from the above function , there are other functions provided by the Camera class that which are listed below
getNumberOfCameras()
2
It returns an integer number defining of cameras availaible on device
TUTORIALS POINT
Simply Easy Learning
lock()
3
It is used to lock the camera , so no other application can access it
release()
4
It is used to release the lock on camera , so other applications can access it
open(int cameraId)
5
It is used to open particular camera when multiple cameras are supported
enableShutterSound(boolean enabled)
6
It is used to enable/disable default shutter sound of image capture
Now you need make an seperate class and extend it with SurfaceView and implements SurfaceHolder interface.
The two classes that have been used have the following purpose
Class Description
Camera It is used to control the camera and take images or capture video from the camera
SurfaceView This class is used to present a live camera preview to the user.
You have to call the preview method of the camera class to start the preview of the camera to the user
Apart from the preview there are other options of the camera that can be set using the other functions provided by
the Camera API
startFaceDetection()
1
This function starts the face detection in the camera
stopFaceDetection()
2
It is used to stop the face detection which is enabled by the above function
startSmoothZoom(int value)
3
It takes an integer value and zoom the camera very smoothly to that value
stopSmoothZoom()
4
It is used to stop the zoom of the camera
stopPreview()
5
It is used to stop the preiview of the camera to the user
TUTORIALS POINT
Simply Easy Learning
takePicture(Camera.ShutterCallback shutter, Camera.PictureCallback raw,
6 Camera.PictureCallback jpeg)
It is used to enable/disable default shutter sound of image capture
Example
Following example demonstrates the usage of the camera API in the application
To experiment with this example, you will need actual Mobile device equipped with latest Android OS, beacuse
camera is not supported by the emulator
Steps Description
You will use Eclipse IDE to create an Android application and name it as Camera under a package
1 com.example.camera1. While creating this project, make sure you Target SDK and Compile With at the
latest version of Android SDK to use higher levels of APIs.
Modify src/MainActivity.java file to add the respective code of camera and get references to the XML
2
components.
Create a new ShowCamera.java file to extend it with SurfaceView and implement the SurfaceHolder
3
interface .
Modify layout XML file res/layout/activity_main.xml add any GUI component if required. Here we add only
4
FrameView and a button and a ImageView.
6 Modify AndroidManifest.xml as shown below to add the necessary permissions for camera
Run the application and choose a running android device and install the application on it and verify the
7
results.
package com.example.camera1;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;
TUTORIALS POINT
Simply Easy Learning
object = Camera.open();
}
catch (Exception e){
}
return object;
}
@Override
public void onPictureTaken(byte[] data, Camera camera) {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pic = (ImageView)findViewById(R.id.imageView1);
cameraObject = isCameraAvailiable();
showCamera = new ShowCamera(this, cameraObject);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(showCamera);
}
public void snapIt(View view){
cameraObject.takePicture(null, null, capturedIt);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Create the new java file called assrc/com.example.camera1/ShowCamera.java. and add the following code
package com.example.camera1;
import java.io.IOException;
import android.content.Context;
import android.hardware.Camera;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
TUTORIALS POINT
Simply Easy Learning
private SurfaceHolder holdMe;
private Camera theCamera;
@Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
try {
theCamera.setPreviewDisplay(holder);
theCamera.startPreview();
} catch (IOException e) {
}
}
@Override
public void surfaceDestroyed(SurfaceHolder arg0) {
}
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="0.30"
android:orientation="vertical" >
<FrameLayout
android:id="@+id/camera_preview"
android:layout_width="fill_parent"
android:layout_height="199dp" />
<Button
android:id="@+id/button_capture"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="snapIt"
android:text="@string/Capture" />
<ImageView
android:id="@+id/imageView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="fitXY"
TUTORIALS POINT
Simply Easy Learning
android:src="@drawable/ic_launcher" />
</LinearLayout>
< /LinearLayout>
<string name="app_name">Camera1</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="Capture">Capture</string>
</resources>
Modify the content of the AndroidManifest.xml and add the necessary permissions as shown below.
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.camera1.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
Let's try to run your SendSMSDemo 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, Eclipse will display following window to select an option where
you want to run your Android application.
TUTORIALS POINT
Simply Easy Learning
Select your mobile device as an option and then check your mobile device which will display following screen:
TUTORIALS POINT
Simply Easy Learning
The camera would start showing its preview in the upper half panel. Just click the capture button. You can now
either store the captured image , upload it to the web or either discard it.
TUTORIALS POINT
Simply Easy Learning
CHAPTER
33
Android Clipboard
A ndroid provides the clipboard framework for copying and pasting different types of data. The data could
Android provides the library of ClipboardManager and ClipData and ClipData.item to use the copying and pasting
framework.In order to use clipboard framework, you need to put data into clip object, and then put that object into
system wide clipboard.
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 Clipbaoard 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.
Text
1 newPlainText(label, text)
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
3 newIntent(label, intent)
Returns a ClipData object whose single ClipData.Item object contains an Intent.
TUTORIALS POINT
Simply Easy Learning
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 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:
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
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.
Steps Description
You will use Eclipse IDE to create an Android application and name it as Clipboard under a package
1 com.example.clipboard. While creating this project, make sure you Target SDK and Compile With at the
latest version of Android SDK to use higher levels of APIs.
Run the application and choose a running android device and install the application on it and verify the
5
results
package com.example.clipboard;
import android.annotation.SuppressLint;
import android.app.Activity;
TUTORIALS POINT
Simply Easy Learning
import android.content.ClipData;
import android.content.ClipboardManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
@SuppressLint("NewApi")
public void copy(View view){
String text = copyField.getText().toString();
myClip = ClipData.newPlainText("text", text);
myClipboard.setPrimaryClip(myClip);
Toast.makeText(getApplicationContext(), "Text Copied",
Toast.LENGTH_SHORT).show();
}
@SuppressLint("NewApi")
public void paste(View view){
ClipData abc = myClipboard.getPrimaryClip();
ClipData.Item item = abc.getItemAt(0);
String text = item.getText().toString();
pasteField.setText(text);
Toast.makeText(getApplicationContext(), "Text Pasted",
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;
}
<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"
TUTORIALS POINT
Simply Easy Learning
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="25dp"
android:layout_marginTop="19dp"
android:text="@string/copytext"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginTop="20dp"
android:ems="10" >
<requestFocus />
</EditText>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText1"
android:layout_centerVertical="true"
android:text="@string/pastetext"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText1"
android:layout_below="@+id/editText1"
android:layout_marginLeft="65dp"
android:layout_marginTop="20dp"
android:onClick="copy"
android:text="@string/copy" />
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView2"
android:layout_below="@+id/textView2"
android:layout_marginTop="39dp"
android:ems="10" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button1"
android:layout_below="@+id/editText2"
android:layout_marginTop="34dp"
TUTORIALS POINT
Simply Easy Learning
android:onClick="paste"
android:text="@string/paste" />
</RelativeLayout>
<string name="app_name">Clipboard</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="copy">Copy Text</string>
<string name="paste">Paste Text</string>
<string name="copytext">Text to copy</string>
<string name="pastetext">Copied Text</string>
</resources>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.clipboard.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
Let's try to run our Clipboard application we just modified. I assume you had created your AVD while doing
environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from
the toolbar. Eclipse 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:
TUTORIALS POINT
Simply Easy Learning
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:
TUTORIALS POINT
Simply Easy Learning
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:
TUTORIALS POINT
Simply Easy Learning
TUTORIALS POINT
Simply Easy Learning
CHAPTER
34
Android Custom Fonts
I n Android, you can define your own custom fonts for the strings in your application. You just need to download
the required font from the internet, and then place it in assets/fonts folder.
After putting fonts in the assets folder under fonts folder, you can access it in your java code through Typeface
class. First , get the reference of the text view in the code. Its syntax is given below:
TextView tx = (TextView)findViewById(R.id.textview1);
The next thing you need to do is to call static method of Typeface class createFromAsset() to get your custom
font from assets. Its syntax is given below:
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 de;fined in the Typeface class , that you can use to handle
Fonts more effectively.
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
getStyle()
5
Returns the Typeface's intrinsic style attributes
TUTORIALS POINT
Simply Easy Learning
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.
Steps Description
You will use Eclipse IDE to create an Android application and name it as CustomFonts under a package
1 com.example.customfonts. While creating this project, make sure you Target SDK and Compile With at
the latest version of Android SDK to use higher levels of APIs.
Run the application and choose a running android device and install the application on it and verify the
6
results
package com.example.customfonts;
import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tx = (TextView)findViewById(R.id.hello);
Typeface custom_font = Typeface.createFromAsset(getAssets(),
"fonts/Erika Type.ttf");
tx.setTypeface(custom_font);
}
@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;
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
TUTORIALS POINT
Simply Easy Learning
<TextView
android:id="@+id/hello"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="70dip"
android:text="@string/hello_world" />
</LinearLayout>
<string name="app_name">CustomFonts</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello</string>
</resources>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.customfonts.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
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 Eclipse, open one of your project's activity files and click Run icon from
the toolbar. Eclipse 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:
TUTORIALS POINT
Simply Easy Learning
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.
TUTORIALS POINT
Simply Easy Learning
CHAPTER
35
Android Data Backup
A ndroid allows you to backup your application data to remote "cloud" storage, in order to provide a restore
point for the application data and settings. You can only backup your application data. In order to access the other
applications data, you need to root your phone.
In order to make a data backup application, you need to register your application with google backup service. This
has been explained in the example. After registering , you have to specify its key in the AndroidManifest.XML
<application
android:allowBackup="true"
android:backupAgent="MyBackupPlace">
<meta-data
android:name="com.google.android.backup.api_key"
android:value="AEdPqrEAAAAIErlxFByGgNz2ywBeQb6TsmLpp5Ksh1PW-ZSexg" />
</application>
Android provides BackUpAgentHelper class to handle all the operations of data backup. In order to use this class
, you have to extend your class with it. Its syntax is given below:
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:
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.
TUTORIALS POINT
Simply Easy Learning
Apart from these methods, there are other methods defined in the BackupAgentHelper class. They are defined
below:
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.
Steps Description
You will use Eclipse IDE to create an Android application and name it as Backup under a package
1 com.example.backup. While creating this project, make sure you Target SDK and Compile With at the
latest version of Android SDK to use higher levels of APIs.
3 Modify the AndroidManifest to add respective necessary key and other compoenets
4 Create backup agent class with the name you specify at AndroidManifest.XML
Register you android application with google backup service. In order to do that , visit this link. You must agree to
the terms of service, and then enter the application package name. It is shown below:
Then click on Register with android backup service. It would give you your key, along with your AndroidManifest
code to copy. Just copy the key. It is shown below:
TUTORIALS POINT
Simply Easy Learning
Once you copy the key , you need to write it in your AndroidManifest.XML file. Its code is given below:
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<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" />
</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);
TUTORIALS POINT
Simply Easy Learning
}
If using a device, the device must be running Android 2.2 or greater and have Google Play built in.
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.
TUTORIALS POINT
Simply Easy Learning
CHAPTER
36
Android Developer Tools
T he Android developer tools let you create interactive and powerful application for android platform. The
1. SDK tools
2. Platform tools
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:
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
TUTORIALS POINT
Simply Easy Learning
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:
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 eclipse click on Window , Open Perspective , Other ... DDMS . Or simple just look on the left most top
corner and click on ddms.
HOW IT WORKS
In android ,each application runs in its own process and each process run in the virtual machine. Each VM
exposes a unique port , that a debugger can attach to.
When DDMS starts, it connects to adb. When a device is connected, a VM monitoring service is created between
adb and DDMS, which notifies DDMS when a VM on the device is started or terminated.
USING DDMS
You can use DDMS for many tasks. For example , here we are using it to make sms , make call , and capture
screenshot.
MAKING SMS
In the DDMS, select the Emulator Control tab. In the emulator control tab , click on SMS and start typing the SMS
and then the incoming number. It is shown in the picture below.
TUTORIALS POINT
Simply Easy Learning
Now click on send button, and you will see an sms notification in the emulator window. It is shown below:
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:
TUTORIALS POINT
Simply Easy Learning
Now click on the call button to make a call to your emulator. It is shown below:
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:
TUTORIALS POINT
Simply Easy Learning
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.
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:
TUTORIALS POINT
Simply Easy Learning
The ecclipse 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
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.
adb pull
Start the sqlite3 tool from the /tools directory, specifying the database file:
TUTORIALS POINT
Simply Easy Learning
sqlite3
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.
TUTORIALS POINT
Simply Easy Learning
CHAPTER
37
Android Emulator
E mulator lets you emulate the real device with all its functionalities without purchasing the real device.
Android emulator lets you emulate different android configurations by creating android virtual devices.
In this chapter we are going to explore different functionalities in the emulator that are present in the real android
device.
Creating AVD
If you want to emulate a real device, first crate an AVD with the same device configurations as real device, then
launch this AVD from AVD manager.
Creating Snapshots
Creating snapshots mean saving an emulator state to a file that enables the emulator to be started quickly the
next time you try to launch it. The one of the biggest advantage of creating snapshots is that it saves the boot up
time.
In order to create snapshot, check mark the option of snapshot while creating your AVD. It is shown below:
The first time you launch the emulator , it will take the ususal time of loading. But when you close it and start it
again, you will see a considerable amount of time reduction in appearing of emulator.
TUTORIALS POINT
Simply Easy Learning
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.
Once it is launched, press Ctrl+F11 key to change its orientation. It is shown below:
TUTORIALS POINT
Simply Easy Learning
Emulator Commands.
Apart from just orientation commands, there are other very usefull commands of emulator that you should keep in
mind while using emulator. They are listed below:
Home
1
Shifts to main screen
F2
2
Toggles context sensitive menu
F3
3
Bring out call log
F4
4
End call
F5
5
Search
F6
6
Toggle trackball mode
F7
7
Power button
F8
8
Toggle data network
Ctrl+F5
9
Ring Volume up
Ctrl+F6
10
Ring Volume down
TUTORIALS POINT
Simply Easy Learning
Emulator - Sending SMS
You can emulate sending SMS to your emulator. There are two ways to do that. You can do that from DDMS which
can be found in Eclipse, or from Telnet.(Network utility found in windows).
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:
TUTORIALS POINT
Simply Easy Learning
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.
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:
TUTORIALS POINT
Simply Easy Learning
Emulator - Transferring files
You can easily transfer files into the emulator and vice versa. In order to do that, you need to select the DDMS
utility in Ecclipse. 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.
TUTORIALS POINT
Simply Easy Learning
CHAPTER
38
Android Facebook Integration
A ndroid allows your application to connect to facebook and share data or any kind of updates on
There are two ways through which you can integrate facebook and share something from your application. These
ways are listed below:
1. Facebook SDK
2. Intent Share
Once you enter it , you will be prompt for password. Give android as the password and then copy the key that is
given to you. It is shown in the image below:
TUTORIALS POINT
Simply Easy Learning
REGISTERING YOUR APPLICATION
Now create a new facebook application at developers.facebook.com/apps and fill all the information. It is shown
below:
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:
TUTORIALS POINT
Simply Easy Learning
// 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:
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:
addCategory(String category)
1
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
TUTORIALS POINT
Simply Easy Learning
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.
Steps Description
You will use Eclipse IDE to create an Android application and name it as IntentShare under a package
1 com.example.intentshare. While creating this project, make sure you Target SDK and Compile With at
the latest version of Android SDK to use higher levels of APIs.
Run the application and choose a running android device and install the application on it and verify the
5
results.
package com.example.intentshare;
import java.io.File;
import java.io.FileOutputStream;
import com.example.intentshare.R;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
@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;
TUTORIALS POINT
Simply Easy Learning
}
public void open(View view){
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, "Hello, from tutorialspoint");
startActivity(Intent.createChooser(shareIntent, "Share your thoughts"));
<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" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="98dp"
android:layout_marginTop="139dp"
android:onClick="open"
android:src="@drawable/tp" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="48dp"
android:text="@string/tap"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
<string name="app_name">IntentShare</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="tap">Tap the button to share something</string>
</resources>
TUTORIALS POINT
Simply Easy Learning
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.intentshare"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.intentshare.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
Let's try to run your IntentShare 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, Eclipse will display following window to select an option where you want to
run your Android application.
TUTORIALS POINT
Simply Easy Learning
Select your mobile device as an option and then check your mobile device which will display your default screen:
TUTORIALS POINT
Simply Easy Learning
Now just tap on the image logo and you will see a list of share providers.
TUTORIALS POINT
Simply Easy Learning
Now just select facebook from that list and then write any message. It is shown in the image below:
TUTORIALS POINT
Simply Easy Learning
Now just select the post button and then it would be post on your wall. It is shown below:
TUTORIALS POINT
Simply Easy Learning
CHAPTER
39
Android Gestures
A ndroid provides special types of touch screen events such as pinch , double tap, scrolls , long presses
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:
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:
TUTORIALS POINT
Simply Easy Learning
}
private class ScaleListener extends
ScaleGestureDetector.SimpleOnScaleGestureListener {
@Override
public boolean onScale(ScaleGestureDetector detector) {
float scale = detector.getScaleFactor();
return true;
}
}
Apart from the pinch gestures , there are other methods avaialible that notify more about touch events. They are
listed below:
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.
Steps Description
You will use Eclipse IDE to create an Android application and name it as Gestures under a package
1 com.example.gestures. While creating this project, make sure you Target SDK and Compile With at the
latest version of Android SDK to use higher levels of APIs.
TUTORIALS POINT
Simply Easy Learning
Run the application and choose a running android device and install the application on it and verify the
5
results
package com.example.gestures;
import android.app.Activity;
import android.graphics.Matrix;
import android.os.Bundle;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.widget.ImageView;
@Override
public boolean onTouchEvent(MotionEvent ev) {
SGD.onTouchEvent(ev);
return true;
}
@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;
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
TUTORIALS POINT
Simply Easy Learning
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<ImageView
android:id="@+id/imageView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/textView1"
android:scaleType="matrix"
android:src="@android:drawable/sym_def_app_icon" />
</RelativeLayout>
<string name="app_name">Gestures</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Pinch to zoom in or out!</string>
</resources>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.gestures.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
TUTORIALS POINT
Simply Easy Learning
</activity>
</application>
</manifest>
Let's try to run your Gestures 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, Eclipse 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 your default screen:
TUTORIALS POINT
Simply Easy Learning
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:
TUTORIALS POINT
Simply Easy Learning
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:
TUTORIALS POINT
Simply Easy Learning
TUTORIALS POINT
Simply Easy Learning
CHAPTER
40
Android Google Maps
A n allows us to integrate google maps in our application. You can show any location on the map , or can
show different routes on the map e.t.c. You can also customize the map according to your choices.
GoogleMap googleMap;
googleMap = ((MapFragment)
getFragmentManager().findFragmentById(R.id.map)).getMap();
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<!--Permissions-->
TUTORIALS POINT
Simply Easy Learning
<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" />
ADDING MARKER
You can place a maker with some text over it displaying your location on the map. It can be done by
viaaddMarker() method. Its syntax is given below:
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
ENABLE/DISABLE ZOOM
You can also enable or disable the zoom gestures in the map by calling
thesetZoomControlsEnabled(boolean) method. Its syntax is given below:
googleMap.getUiSettings().setZoomGesturesEnabled(true);
Apart from these customization, there are other methods availaible in the GoogleMap class , that helps you more
customize the map. They are listed below:
addCircle(CircleOptions options)
1
This method add a circle to the map
addPolygon(PolygonOptions options)
2
This method add a polygon to the map
addTileOverlay(TileOverlayOptions options)
3
This method add tile overlay to the map
TUTORIALS POINT
Simply Easy Learning
animateCamera(CameraUpdate update)
4
This method Moves the map according to the update with an animation
clear()
5
This method removes everything from the map.
getMyLocation()
6
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
setTrafficEnabled(boolean enabled)
8
This method Toggles the traffic layer on or off.
snapshot(GoogleMap.SnapshotReadyCallback callback)
9
This method Takes a snapshot of the map
stopAnimation()
10
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.
Steps Description
You will use Eclipse IDE to create an Android application and name it as GoogleMaps under a package
2 com.example.googlemaps. While creating this project, make sure you Target SDK and Compile With at
the latest version of Android SDK to use higher levels of APIs.
Run the application and choose a running android device and install the application on it and verify the
6
results
TUTORIALS POINT
Simply Easy Learning
2. Obtain API key from google console
Navigate to the extras tab and select the Google play services and click on install this package. It would be like
this.
TUTORIALS POINT
Simply Easy Learning
Obtaining the API key
This part is furthur divided into two steps. First you have to get an SHA1 fingerprint key from your pc and then you
have to get map API key from google console.
Open your command prompt and move to the path where your java jre has been placed. Now type this command.
Replace the percentage part of the command with the path which you will copy from by selecting the window tab
and selecting the preferences tab and then selectng the build option under android from left side.
Copy the default debug keystore path and replace it in the cmmand and hit enter. The following result would
appear.
Copy the SHA1 key because you need it in the next step.
TUTORIALS POINT
Simply Easy Learning
GETTING KEY FROM GOOGLE CONSOLE
Open Google Console and sign in by clicking a new project.
Click on services from the left tab and then navigate to the Google Maps Android API v2. You have to turn them on
like this
Now again go to the left tab and select API access. And click on create new android key. Now paste the key that
you copied and put a semicolon and paste your project name and click create. It would be like this.
Now copy the API key that has been given to your by android , because you have to paste it into your manifest file.
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="API_KEY"/>
In the second line replace API_KEY with your api key and you are done. You need to add some permissions in
your manifest too which are given below in the manifest file.
TUTORIALS POINT
Simply Easy Learning
Adding Google Maps to your application.
Following is the content of the modifed main activity filesrc/com.example.googlemaps/MainActivity.java.
package com.example.googlemaps;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import android.os.Bundle;
import android.app.Activity;
import android.widget.Toast;
} catch (Exception e) {
e.printStackTrace();
}
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
TUTORIALS POINT
Simply Easy Learning
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.googlemaps"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="com.example.googlemaps.permission.MAPS_RECEIVE"
/>
<uses-sdk
android:minSdkVersion="12"
android:targetSdkVersion="17" />
<permission
android:name="com.example.googlemaps.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="android.permission.
ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.googlemaps.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyDKymeBXNeiFWY5jRUejv6zItpmr2MVyQ0" />
</application>
</manifest>
Let's try to run your GoogleMaps 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
TUTORIALS POINT
Simply Easy Learning
toolbar. Before starting your application, Eclipse will display following window to select an option where you want to
run your Android application.
Now what you need to do is to tap on the ballon to see the text.
TUTORIALS POINT
Simply Easy Learning
Now you can customize the google map according to your choice with the functions given in the GoogleMap API.
TUTORIALS POINT
Simply Easy Learning
CHAPTER
41
Android Image Effects
A ndroid 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.
Now we will create bitmap by calling getBitmap() function of BitmapDrawable class. Its syntax is given below:
bmp = abmp.getBitmap();
An image is nothing but a two dimensional matrix. Same way you will handle a bitmap. An image consist of pixels.
So you will get pixels from this bitmap and apply processing to it. Its syntax is as follows:
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.
TUTORIALS POINT
Simply Easy Learning
createBitmap(int width, int height, Bitmap.Config config)
3
Returns a mutable bitmap with the specified width and height
createBitmap(Bitmap src)
4
Returns an immutable bitmap from the source bitmap
extractAlpha()
5
Returns a new bitmap that captures the alpha values of the original
getConfig()
6
This mehtod eturn that config, otherwise return null
getDensity()
7
Returns the density for this bitmap
getRowBytes()
8
Return the number of bytes between rows in the bitmap's pixels
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.
Steps Description
You will use Eclipse IDE to create an Android application and name it as ImageEffects under a package
1 com.example.imageeffects. While creating this project, make sure you Target SDK and Compile With at
the latest version of Android SDK to use higher levels of APIs.
Run the application and choose a running android device and install the application on it and verify the
5
results
package com.example.imageeffects;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
TUTORIALS POINT
Simply Easy Learning
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img = (ImageView)findViewById(R.id.imageView1);
BitmapDrawable abmp = (BitmapDrawable)img.getDrawable();
bmp = abmp.getBitmap();
r = (int) red * r;
g = (int) green * g;
b = (int) blue * b;
r = 100 + r;
g = 100 + g;
b = 100 + b;
alpha = 100 + alpha;
TUTORIALS POINT
Simply Easy Learning
operation.setPixel(i, j, Color.argb(alpha, r, g, b));
}
}
img.setImageBitmap(operation);
}
r = r - 50;
g = g - 50;
b = b - 50;
alpha = alpha -50;
operation.setPixel(i, j, Color.argb(Color.alpha(p), r, g, b));
}
}
img.setImageBitmap(operation);
}
@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;
}
<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" >
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/button1"
android:layout_alignBottom="@+id/button1"
android:layout_alignParentRight="true"
android:layout_marginRight="19dp"
android:onClick="dark"
TUTORIALS POINT
Simply Easy Learning
android:text="@string/dark" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="87dp"
android:layout_marginRight="17dp"
android:layout_toLeftOf="@+id/button3"
android:onClick="gray"
android:text="@string/gray" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/button2"
android:layout_alignBottom="@+id/button2"
android:layout_centerHorizontal="true"
android:onClick="bright"
android:text="@string/bright" />
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="114dp"
android:src="@drawable/ic_launcher" />
</RelativeLayout>
<string name="app_name">ImageEffects</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="gray">Gray</string>
<string name="bright">bright</string>
<string name="dark">dark</string>
</resources>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
TUTORIALS POINT
Simply Easy Learning
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.imageeffects.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
Let's try to run our Image Effects application we just modified. I assume you had created your AVDwhile doing
environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from
the toolbar. Eclipse 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:
TUTORIALS POINT
Simply Easy Learning
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:
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:
TUTORIALS POINT
Simply Easy Learning
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:
TUTORIALS POINT
Simply Easy Learning
TUTORIALS POINT
Simply Easy Learning
CHAPTER
42
Android Image Switcher
S ometimes 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:
<ImageSwitcher
android:id="@+id/imageSwitcher1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" >
</ImageSwitcher>
Now we create an intance of ImageSwithcer in java file and get a reference of this XML component. Its sytnax is
given below:
The next thing we need to do implement the ViewFactory interface and implement unimplemented method that
returns an imageView. Its syntax is below:
imageSwitcher.setImageResource(R.drawable.ic_launcher);
imageSwitcher.setFactory(new ViewFactory() {
public View makeView() {
ImageView myView = new ImageView(getApplicationContext());
return myView;
}
}
The last thing you need to do is to add Animation to the ImageSwitcher. You need to define an object of Animation
class through AnimationUtilities class by calling a static method loadAnimation. Its syntax is given below:
Animation in = AnimationUtils.loadAnimation(this,android.R.anim.slide_in_left);
imageSwitcher.setInAnimation(in);
imageSwitcher.setOutAnimation(out);
TUTORIALS POINT
Simply Easy Learning
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:
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
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.
Steps Description
You will use Eclipse IDE to create an Android application and name it as ImageSwitcher under a
1 package com.example.imageswitcher. While creating this project, make sure you Target SDK and
Compile With at the latest version of Android SDK to use higher levels of APIs.
Run the application and choose a running android device and install the application on it and verify the
4
results
package com.example.imageswitcher;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
TUTORIALS POINT
Simply Easy Learning
import android.widget.ImageButton;
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);
img = (ImageButton)findViewById(R.id.imageButton1);
imageSwitcher = (ImageSwitcher)findViewById(R.id.imageSwitcher1);
imageSwitcher.setFactory(new ViewFactory() {
@Override
public View makeView() {
ImageView myView = new ImageView(getApplicationContext());
myView.setScaleType(ImageView.ScaleType.FIT_CENTER);
myView.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.
FILL_PARENT,LayoutParams.FILL_PARENT));
return myView;
}
});
TUTORIALS POINT
Simply Easy Learning
}
<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" >
<ImageButton
android:id="@+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="54dp"
android:onClick="next"
android:src="@android:drawable/ic_menu_send" />
<ImageSwitcher
android:id="@+id/imageSwitcher1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" >
</ImageSwitcher>
<ImageButton
android:id="@+id/imageButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="85dp"
android:onClick="previous"
android:src="@android:drawable/ic_menu_revert" />
</RelativeLayout>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
TUTORIALS POINT
Simply Easy Learning
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.imageswitcher.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
Let's try to run our Image Switcher application we just modified. I assume you had created your AVDwhile doing
environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from
the toolbar. Eclipse 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 if you will look at your device screen , you will see the two buttons.
TUTORIALS POINT
Simply Easy Learning
Now just select the upper button that right arrow. An image would appear from right and move towards left. It is
shown below:
Now tap on the below button, that will bring back the previous image with some transition. It is shown below:
TUTORIALS POINT
Simply Easy Learning
TUTORIALS POINT
Simply Easy Learning
CHAPTER
43
Android Internal Storage
A ndroid provides many kinds of storage for applications to store their data. Thes storage places are
shared preferences , internal and external storage , SQLite storage , and storage via network connection.
In this chapter we are going to look at the internal storage. Internal storge 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:
The method openFileOutput() returns an instance of FileOutputStream. So you recieve it in the object of
FileInputStream. After that you can call write method to write data on the file. 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 sytanx is given below:
After that, you can callr 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);
}
TUTORIALS POINT
Simply Easy Learning
//string temp contains all the data of the file.
fin.close();
Apart from the the methods of write and close, there are other methods provided by theFileOutputStream class
for better writing files. These methods are listed below:
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 FileInputStreamclass for
better reading files. These methods are listed below:
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
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.
Steps Description
You will use Eclipse IDE to create an Android application and name it as Storage under a package
1 com.example.storage. While creating this project, make sure you Target SDK and Compile With at the
latest version of Android SDK to use higher levels of APIs.
TUTORIALS POINT
Simply Easy Learning
4 Modify the res/values/string.xml to add necessary string components
Run the application and choose a running android device and install the application on it and verify the
5
results
package com.example.storage;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
}catch(Exception e){
TUTORIALS POINT
Simply Easy Learning
}
}
@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;
}
<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" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="182dp"
android:onClick="save"
android:text="@string/save" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button1"
android:layout_alignRight="@+id/button1"
android:layout_below="@+id/button1"
android:layout_marginTop="46dp"
android:onClick="read"
android:text="@string/read" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button1"
android:layout_alignParentTop="true"
android:layout_marginTop="23dp"
android:ems="10"
android:inputType="textMultiLine" >
<requestFocus />
</EditText>
</RelativeLayout>
TUTORIALS POINT
Simply Easy Learning
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Storage</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="save">save to intenal storage</string>
<string name="read">load from intenal storag</string>
</resources>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.storage.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</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 Eclipse, open one of your project's activity files and click Run icon from
the toolbar. Eclipse 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:
TUTORIALS POINT
Simply Easy Learning
Now what you need to do is to enter any text in the field. For example , i have entered soem text. Press the save
button. The following notification would appear in you AVD:
TUTORIALS POINT
Simply Easy Learning
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:
TUTORIALS POINT
Simply Easy Learning
Note you can actually view this file by switching to DDMS tab. In DDMS , select file explorer and navigate this path.
data>data>com.example.storage>files>mydata
TUTORIALS POINT
Simply Easy Learning
CHAPTER
44
Android JetPlayer
T he Android platform includes a JET engine that lets you add interactive playback of JET audio content in
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;
// 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:
clearQueue()
1
Empties the segment queue, and clears all clips that are scheduled for playback
closeJetFile()
2
Closes the resource containing the JET content
getJetPlayer()
3
Factory method for the JetPlayer class
loadJetFile(String path)
4
Loads a .jet file from a given path
TUTORIALS POINT
Simply Easy Learning
pause()
5
Pauses the playback of the JET segment queue
release()
6
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.
Steps Description
You will use Eclipse IDE to create an Android application and name it as JetPlayer under a package
1 com.example.jetplayer. While creating this project, make sure you Target SDK and Compile With at the
latest version of Android SDK to use higher levels of APIs.
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:
TUTORIALS POINT
Simply Easy Learning
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.
TUTORIALS POINT
Simply Easy Learning
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:
TUTORIALS POINT
Simply Easy Learning
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.
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:
TUTORIALS POINT
Simply Easy Learning
CHAPTER
45
Android JSON Parser
J SON 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 differnet classes to manipulate JSON data. These classes
areJSONArray,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 compoents of an JSON file and their
description:
Array([)
1
In a JSON file , square bracket ([) represents a JSON array
TUTORIALS POINT
Simply Easy Learning
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. An JSON file consist of different object with different key/value pair e.t.c. So
JSONObject has a seperate function for parsing each of the component of JSON file. Its syntax is given below:
The method getJSONObject returns the JSON object. The method getString returns the string value of the
specified key.
Apart from the these methods , there are other methods provided by this class for better parsing JSON files. These
methods are listed below:
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
getDouble(String name)
3
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.
TUTORIALS POINT
Simply Easy Learning
Example
Here is an example demonstrating the use of JSONObject class. It creates a basic Weather application that allows
you to parse JSON from google weather api and show the result.
To experiment with this example , you can run this on an actual device or in an emulator.
Steps Description
You will use Eclipse IDE to create an Android application and name it as JSONParser under a package
1 com.example.jsonparser. While creating this project, make sure you Target SDK and Compile With at the
latest version of Android SDK to use higher levels of APIs.
5 Create a new java file under src/HandleJSON.java to fetch and parse XML data
Run the application and choose a running android device and install the application on it and verify the
7
results
package com.example.jsonparser;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
@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;
}
TUTORIALS POINT
Simply Easy Learning
public void open(View view){
String url = location.getText().toString();
String finalUrl = url1 + url;
country.setText(finalUrl);
obj = new HandleJSON(finalUrl);
obj.fetchJSON();
while(obj.parsingComplete);
country.setText(obj.getCountry());
temperature.setText(obj.getTemperature());
humidity.setText(obj.getHumidity());
pressure.setText(obj.getPressure());
}
}
package com.example.jsonparser;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import android.annotation.SuppressLint;
TUTORIALS POINT
Simply Easy Learning
}
@SuppressLint("NewApi")
public void readAndParseJSON(String in) {
try {
JSONObject reader = new JSONObject(in);
pressure = main.getString("pressure");
humidity = main.getString("humidity");
parsingComplete = false;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void fetchJSON(){
Thread thread = new Thread(new Runnable(){
@Override
public void run() {
try {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
InputStream stream = conn.getInputStream();
readAndParseJSON(data);
stream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
static String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
}
TUTORIALS POINT
Simply Easy Learning
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="15dp"
android:text="@string/location"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/textView1"
android:layout_alignParentRight="true"
android:ems="10" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginTop="68dp"
android:text="@string/country"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView2"
android:layout_marginTop="19dp"
android:text="@string/temperature"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView3"
android:layout_below="@+id/textView3"
android:layout_marginTop="32dp"
android:text="@string/humidity"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
TUTORIALS POINT
Simply Easy Learning
android:layout_alignLeft="@+id/textView4"
android:layout_below="@+id/textView4"
android:layout_marginTop="21dp"
android:text="@string/pressure"
android:textAppearance="?android:attr/textAppearanceSmall" />
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/textView3"
android:layout_toRightOf="@+id/textView3"
android:ems="10" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/editText3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView3"
android:layout_alignBottom="@+id/textView3"
android:layout_alignLeft="@+id/editText2"
android:ems="10" />
<EditText
android:id="@+id/editText4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/textView5"
android:layout_alignLeft="@+id/editText1"
android:ems="10" />
<EditText
android:id="@+id/editText5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView5"
android:layout_alignBottom="@+id/textView5"
android:layout_alignRight="@+id/editText4"
android:ems="10" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText2"
android:layout_below="@+id/editText1"
android:onClick="open"
android:text="@string/weather" />
</RelativeLayout>
TUTORIALS POINT
Simply Easy Learning
<string name="hello_world">Hello world!</string>
<string name="location">Location</string>
<string name="country">Country:</string>
<string name="temperature">Temperature:</string>
<string name="humidity">Humidity:</string>
<string name="pressure">Pressure:</string>
<string name="weather">Weather</string>
</resources>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.jsonparser.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
Let's try to run our JSONParser application we just modified. I assume you had created your AVD while doing
environment setup. To run the app from Eclipse, open one of your project's activity files and click Run . icon
from the toolbar. Eclipse 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:
TUTORIALS POINT
Simply Easy Learning
Now what you need to do is to enter any location in the location field. For example , i have entered newyork.
Press the weather button , when you enter the location. The following screen would appear in you AVD:
TUTORIALS POINT
Simply Easy Learning
Now when you press the weather button, the application will contact the Google Weather API and will request for
your necessary JSON location file and will parse it. In case of newyork following file would be returned:
Note that this temperature is in kelvin, so if you want to convert it into more understandble format , you have to
convert it into Celcius.
TUTORIALS POINT
Simply Easy Learning
CHAPTER
46
Android Linkedin Integration
A ndroid allows your application to connect to Linkedin and share data or any kind of updates on Linkedin.
There are two ways through which you can integrate Linkedin and share something from your application. These
ways are listed below.
2. Intent Share
Now fill in your application name , description and your website url. It is shown below:
TUTORIALS POINT
Simply Easy Learning
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:
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:
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:
TUTORIALS POINT
Simply Easy Learning
addCategory(String category)
1
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
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.
Steps Description
You will use Eclipse IDE to create an Android application and name it as IntentShare under a package
1 com.example.intentshare. While creating this project, make sure you Target SDK and Compile With at
the latest version of Android SDK to use higher levels of APIs.
Run the application and choose a running android device and install the application on it and verify the
5
results
package com.example.intentshare;
import java.io.File;
import java.io.FileOutputStream;
import com.example.intentshare.R;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
TUTORIALS POINT
Simply Easy Learning
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
@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;
}
public void open(View view){
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, "Hello, from tutorialspoint");
startActivity(Intent.createChooser(shareIntent, "Share your thoughts"));
<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" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="98dp"
android:layout_marginTop="139dp"
android:onClick="open"
android:src="@drawable/tp" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
TUTORIALS POINT
Simply Easy Learning
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="48dp"
android:text="@string/tap"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
<string name="app_name">IntentShare</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="tap">Tap the button to share something</string>
</resources>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.intentshare.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
Let's try to run your IntentShare 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, Eclipse will display following window to select an option where you want to
run your Android application.
TUTORIALS POINT
Simply Easy Learning
Select your mobile device as an option and then check your mobile device which will display your default screen:
TUTORIALS POINT
Simply Easy Learning
Now just tap on the image logo and you will see a list of share providers.
TUTORIALS POINT
Simply Easy Learning
Now just select Linkedin from that list and then write any message. It is shown in the image below:
TUTORIALS POINT
Simply Easy Learning
Now just select the arrow button and then it would be post on your Linkedin page. It is shown below:
TUTORIALS POINT
Simply Easy Learning
CHAPTER
47
Android Loading Spinner
Y ou can show progress of a task in android through loading progress bar. The progress bar comes in two
shapes. Loading bar and Loading Spinner. In this chapter we will discuss spinner.
Spinner is used to display progress of those tasks whose total time of completion is unknown. In order to use that,
you just need to define it in the xml like this.
<ProgressBar
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.
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
TUTORIALS POINT
Simply Easy Learning
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
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.
Steps Description
You will use Eclipse IDE to create an Android application and name it as Spinner under a package
1 com.example.spinner. While creating this project, make sure you Target SDK and Compile With at the
latest version of Android SDK to use higher levels of APIs.
Run the application and choose a running android device and install the application on it and verify the
5
results
package com.example.spinner;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ProgressBar;
TUTORIALS POINT
Simply Easy Learning
return true;
}
<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" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="103dp"
android:onClick="load"
android:text="@string/hello_world" />
<ProgressBar
android:id="@+id/progressBar1"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button1"
android:layout_centerHorizontal="true" />
</RelativeLayout>
<string name="app_name">Spinner</string>
<string name="action_settings">Settings</string>
<string name="hello_world">load spinner</string>
</resources>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
TUTORIALS POINT
Simply Easy Learning
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.spinner.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
Let's try to run our Loading Spinner application we just modified. I assume you had created your AVDwhile doing
environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from
the toolbar. Eclipse 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 click on the load spinner button to turn on the loading spinner. It is shown in the image below:
TUTORIALS POINT
Simply Easy Learning
TUTORIALS POINT
Simply Easy Learning
CHAPTER
48
Android Localization
A n 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.
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 ofvalues-
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>
TUTORIALS POINT
Simply Easy Learning
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>
<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:
Afrikanns
1
Code: af. Folder name: values-af
Arabic
2
Code: ar. Folder name: values-ar
Bengali
3
Code: bn. Folder name: values-bn
Czech
4
Code: cs. Folder name: values-cs
Chinese
5
Code: zh. Folder name: values-zh
German
6
Code: de. Folder name: values-de
French
7
Code: fr. Folder name: values-fr
Japanese
8
Code: ja. Folder name: values-ja
Example
Here is an example demonstrating the use of Localization of strings. It creates a basic application that allows you
to customize your application according to US and Italy region.
To experiment with this example , you can run this on an actual device or in an emulator.
Steps Description
You will use Eclipse IDE to create an Android application and name it as Locals under a package
1 com.example.locals. While creating this project, make sure you Target SDK and Compile With at the
latest version of Android SDK to use higher levels of APIs.
TUTORIALS POINT
Simply Easy Learning
3 Modify the res/layout/activity_main to add respective XML components
Run the application and choose a running android device and install the application on it and verify the
6
results
package com.example.locals;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@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;
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="174dp"
android:text="@string/hello_world"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
TUTORIALS POINT
Simply Easy Learning
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Locals</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
</resources>
<string name="app_name">Locals</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Ciao mondo!</string>
</resources>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.locals.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
Let's try to run our Localization application we just modified. I assume you had created your AVD while doing
environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from
the toolbar. Eclipse 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:
TUTORIALS POINT
Simply Easy Learning
Now change your device language setting from menu/system-settings/language to italy.
Now opne the application again and this time you will see hello world in italian language. It has been shown
below::
TUTORIALS POINT
Simply Easy Learning
TUTORIALS POINT
Simply Easy Learning
CHAPTER
49
Android Login Screen
A login application is the screen asking your credentials to login to some particular application. You might
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() andtoString() method and match it with the text using equals() function.
TUTORIALS POINT
Simply Easy Learning
//wrong password
}
The last thing you need to do is to provide a security mechanism, so that unwanted attempts should be avoided.
For this intializa a variable and on each false attempt, decrement it. And when it reaches to 0, disable the login
button.
int counter = 3;
counter--;
if(counter==0){
//disble the button, close the application e.t.c
}
Example
Here is an example demonstrating a login application. It creates a basic application that gives you only three
attempts to login to an application.
To experiment with this example , you can run this on an actual device or in an emulator.
Steps Description
You will use Eclipse IDE to create an Android application and name it as LoginScreen under a package
1 com.example.loginscreen. While creating this project, make sure you Target SDK and Compile With at
the latest version of Android SDK to use higher levels of APIs.
Run the application and choose a running android device and install the application on it and verify the
6
results
package com.example.loginscreen;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
TUTORIALS POINT
Simply Easy Learning
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = (EditText)findViewById(R.id.editText1);
password = (EditText)findViewById(R.id.editText2);
attempts = (TextView)findViewById(R.id.textView5);
attempts.setText(Integer.toString(counter));
login = (Button)findViewById(R.id.button1);
}
}
@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;
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="18dp"
android:text="@string/hello_world"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
TUTORIALS POINT
Simply Easy Learning
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView1"
android:layout_marginTop="50dp"
android:text="@string/username"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/textView2"
android:layout_marginLeft="32dp"
android:layout_toRightOf="@+id/textView2"
android:ems="10" >
<requestFocus />
</EditText>
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView2"
android:layout_below="@+id/textView2"
android:layout_marginTop="38dp"
android:text="@string/password"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/textView3"
android:layout_alignLeft="@+id/editText1"
android:ems="10"
android:inputType="textPassword" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText2"
android:layout_centerHorizontal="true"
android:layout_marginTop="94dp"
android:onClick="login"
android:text="@string/Login" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView3"
android:layout_below="@+id/textView3"
android:layout_marginLeft="30dp"
android:layout_marginTop="48dp"
android:text="@string/attempts"
android:textAppearance="?android:attr/textAppearanceMedium" />
TUTORIALS POINT
Simply Easy Learning
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/textView1"
android:layout_alignTop="@+id/textView4"
android:text="TextView" />
</RelativeLayout>
<string name="app_name">LoginScreen</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Login Screen</string>
<string name="username">Username:</string>
<string name="password">Password:</string>
<string name="Login">Login:</string>
<string name="attempts">Attempts Left:</string>
</resources>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.loginscreen.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
Let's try to run our Login application we just modified. I assume you had created your AVD while doing
environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from
the toolbar. Eclipse 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:
TUTORIALS POINT
Simply Easy Learning
Type anything in the username and password field except admin, and then press the login button. I put admin in
the username field and nimda in the password field. I got failed attempt. This is shown below:
TUTORIALS POINT
Simply Easy Learning
Do this two more time, and you will see that you have 0 login attempts left and your login button is disabled.
TUTORIALS POINT
Simply Easy Learning
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.
TUTORIALS POINT
Simply Easy Learning
TUTORIALS POINT
Simply Easy Learning
CHAPTER
50
Android MediaPlayer
A ndroid provides many ways to control playback of audio/video files and streams. One of this way is
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 begininning. 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:
isPlaying()
1
This method just returns true/false indicating the song is playing or not
seekTo(positon)
2
This method takes an integer, and move song to that particular second
getCurrentDuration()
3
This method returns the current position of song in milliseconds
getDuration()
4
This method returns the total time duration of song in milliseconds
TUTORIALS POINT
Simply Easy Learning
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
forwad , 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.
Steps Description
You will use Eclipse IDE to create an Android application and name it as MediaPlayer under a package
1 com.example.mediaplayer. While creating this project, make sure you Target SDK and Compile With at
the latest version of Android SDK to use higher levels of APIs.
Create a new folder under MediaPlayer with name as raw and place an mp3 music file in it with name as
5
song.mp3
Run the application and choose a running android device and install the application on it and verify the
6
results
package com.example.mediaplayer;
import java.util.concurrent.TimeUnit;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
TUTORIALS POINT
Simply Easy Learning
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
TUTORIALS POINT
Simply Easy Learning
private Runnable UpdateSongTime = new Runnable() {
public void run() {
startTime = mediaPlayer.getCurrentPosition();
startTimeField.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);
}
};
public void pause(View view){
Toast.makeText(getApplicationContext(), "Pausing sound",
Toast.LENGTH_SHORT).show();
mediaPlayer.pause();
pauseButton.setEnabled(false);
playButton.setEnabled(true);
}
public void forward(View view){
int temp = (int)startTime;
if((temp+forwardTime)<=finalTime){
startTime = startTime + forwardTime;
mediaPlayer.seekTo((int) startTime);
}
else{
Toast.makeText(getApplicationContext(),
"Cannot jump forward 5 seconds",
Toast.LENGTH_SHORT).show();
}
}
public void rewind(View view){
int temp = (int)startTime;
if((temp-backwardTime)>0){
startTime = startTime - backwardTime;
mediaPlayer.seekTo((int) startTime);
}
else{
Toast.makeText(getApplicationContext(),
"Cannot jump backward 5 seconds",
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;
}
TUTORIALS POINT
Simply Easy Learning
<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" >
<ImageButton
android:id="@+id/imageButton3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="14dp"
android:onClick="forward"
android:src="@android:drawable/ic_media_ff" />
<ImageButton
android:id="@+id/imageButton4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="@+id/imageButton2"
android:layout_marginLeft="22dp"
android:layout_toRightOf="@+id/imageButton2"
android:onClick="rewind"
android:src="@android:drawable/ic_media_rew" />
<ImageButton
android:id="@+id/imageButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/imageButton1"
android:layout_marginLeft="14dp"
android:layout_toRightOf="@+id/imageButton1"
android:onClick="pause"
android:src="@android:drawable/ic_media_pause" />
<ImageButton
android:id="@+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/imageButton3"
android:layout_marginLeft="24dp"
android:layout_toRightOf="@+id/imageButton3"
android:onClick="play"
android:src="@android:drawable/ic_media_play" />
<SeekBar
android:id="@+id/seekBar1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/imageButton3"
android:layout_toLeftOf="@+id/textView2"
android:layout_toRightOf="@+id/textView1" />
<TextView
android:id="@+id/textView1"
TUTORIALS POINT
Simply Easy Learning
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/imageButton3"
android:layout_alignTop="@+id/seekBar1"
android:text="@string/inital_Time"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/imageButton4"
android:layout_alignTop="@+id/seekBar1"
android:text="@string/inital_Time"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/imageButton3"
android:text="@string/hello_world"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ImageView
android:id="@+id/imageView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView3"
android:src="@drawable/ic_launcher" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView3"
android:layout_alignBottom="@+id/textView3"
android:layout_toRightOf="@+id/imageButton1"
android:text="TextView" />
</RelativeLayout>
<string name="app_name">MediaPlayer</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Now Playing:</string>
<string name="inital_Time">0 min, 0 sec</string>
</resources>
TUTORIALS POINT
Simply Easy Learning
package="com.example.mediaplayer"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.mediaplayer.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
Let's try to run your MediaPlayer 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, Eclipse will display following window to select an option where you want to
run your Android application.
TUTORIALS POINT
Simply Easy Learning
Select your mobile device as an option and then check your mobile device which will display your default screen:
TUTORIALS POINT
Simply Easy Learning
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:
TUTORIALS POINT
Simply Easy Learning
Uptill now, the music has been playing. Now press the pause button and see the pause notification. This is shown
below:
TUTORIALS POINT
Simply Easy Learning
Now when you press the play button again, the song will not play from the begining but from where it was paused.
Now press the fast forwad 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:
TUTORIALS POINT
Simply Easy Learning
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.
TUTORIALS POINT
Simply Easy Learning
CHAPTER
51
Android Multitouch
M ulti-touch gesture happens when more then one finger touches the screen at the same time. Android
Android system generates the following touch events whenever multiple fingers touches the screen at the same
time.
ACTION_DOWN
1
For the first pointer that touches the screen. This starts the gesture.
ACTION_POINTER_DOWN
2
For extra pointers that enter the screen beyond the first.
ACTION_MOVE
3
A change has happened during a press gesture.
ACTION_POINTER_UP
4
Sent when a non-primary pointer goes up.
ACTION_UP
5
Sent when the last pointer leaves the screen.
So in order to detect any of the above mention event , you need to override onTouchEvent() method and check
these events manually. Its syntax is given below:
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:
TUTORIALS POINT
Simply Easy Learning
final float x = ev.getX();
final float y = ev.getY();
Apart from these methods, there are other methods provided by this MotionEvent class for better dealing with
multitouch. These methods are listed below:
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.
Steps Description
You will use Eclipse IDE to create an Android application and name it as Multitouch under a package
1 com.example.multitouch. While creating this project, make sure you Target SDK and Compile With at the
latest version of Android SDK to use higher levels of APIs.
Run the application and choose a running android device and install the application on it and verify the
5
results.
package com.example.multitouch;
TUTORIALS POINT
Simply Easy Learning
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MotionEvent;
import android.widget.EditText;
import android.widget.Toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
xText = (EditText)findViewById(R.id.editText2);
yText = (EditText)findViewById(R.id.editText3);
moveX = (EditText)findViewById(R.id.editText1);
moveY = (EditText)findViewById(R.id.editText4);
}
@Override
public boolean onTouchEvent(MotionEvent ev){
final int actionPeformed = ev.getAction();
switch(actionPeformed){
case MotionEvent.ACTION_DOWN:{
final float x = ev.getX();
final float y = ev.getY();
lastXAxis = x;
lastYAxis = y;
xText.setText(Float.toString(lastXAxis));
yText.setText(Float.toString(lastYAxis));
break;
}
case MotionEvent.ACTION_MOVE:{
final float x = ev.getX();
final float y = ev.getY();
final float dx = x - lastXAxis;
final float dy = y - lastYAxis;
xAxis += dx;
yAxis += dy;
moveX.setText(Float.toString(xAxis));
moveY.setText(Float.toString(yAxis));
break;
}
}
return true;
}
@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;
}
TUTORIALS POINT
Simply Easy Learning
}
<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" >
<EditText
android:id="@+id/editText3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText2"
android:layout_below="@+id/editText2"
android:ems="10" />
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginTop="25dp"
android:ems="10" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText3"
android:layout_below="@+id/editText3"
android:ems="10" >
</EditText>
<EditText
android:id="@+id/editText4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText1"
android:layout_below="@+id/editText1"
android:ems="10" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/editText3"
android:layout_alignParentLeft="true"
android:text="@string/xaxis"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="@+id/textView3"
TUTORIALS POINT
Simply Easy Learning
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/editText3"
android:layout_alignRight="@+id/textView2"
android:text="@string/yaxis"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/editText4"
android:layout_alignLeft="@+id/textView3"
android:text="@string/MoveX"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editText4"
android:layout_alignBottom="@+id/editText4"
android:layout_alignRight="@+id/textView4"
android:text="@string/MoveY"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="@+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="109dp"
android:text="@string/perform"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
TUTORIALS POINT
Simply Easy Learning
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.multitouch.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 Multitouch 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, Eclipse will display following window to select an option where you want to
run your Android application.
TUTORIALS POINT
Simply Easy Learning
Select your mobile device as an option and then check your mobile device which will display your default screen:
TUTORIALS POINT
Simply Easy Learning
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:
TUTORIALS POINT
Simply Easy Learning
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:
TUTORIALS POINT
Simply Easy Learning
TUTORIALS POINT
Simply Easy Learning
CHAPTER
52
Android Navigation
I n this chapter, we will see that how you can provide navigation forward and backward between an application.
Providing Up Navigation
The up navigation will allow our application to move to previous activity from the next activity. It can be done like
this.
To implement Up navigation, the first step is to declare which activity is the appropriate parent for each activity.
You can do it by specifying parentActivityName attibute in an activity. Its sytnax is given below:
android:parentActivityName="com.example.test.MainActivity"
After that you need to call setDisplayHomeAsUpEnabled method of getActionBar() in the onCreate method of
the activity. This will enable the back button in the top action bar.
getActionBar().setDisplayHomeAsUpEnabled(true);
The last thing you need to do is to override onOptionsItemSelected method. when the user presses it, your
activity receives a call to onOptionsItemSelected(). The ID for the action is android.R.id.home.Its syntax is given
below:
It can be done by overriding onBackPressed and then calling moveTaskToBack and finish method. Its syntax is
given below:
TUTORIALS POINT
Simply Easy Learning
@Override
public void onBackPressed() {
moveTaskToBack(true);
MainActivity2.this.finish();
}
Apart from this setDisplayHomeAsUpEnabled method, there are other methods availaible in ActionBar API class.
They are listed below:
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
Example
The below example demonstrates the use of Navigation. It crates a basic application that allows you to navigate
withing your application.
To experiment with this example , you need to run this on an actual device or in an emulator.
Steps Description
You will use Eclipse IDE to create an Android application and name it as test under a package
1 com.example.test. While creating this project, make sure you Target SDK and Compile With at the latest
version of Android SDK to use higher levels of APIs.
3 Create a new activity with the name of MainActivity2 and edit it to add activity code.
4 Modify layout XML file res/layout/activity_main.xml add any GUI component if required.
5 Modify layout XML file res/layout/activity_main_activity2.xml add any GUI component if required.
Run the application and choose a running android device and install the application on it and verify the
8
results.
package com.example.test;
TUTORIALS POINT
Simply Easy Learning
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
package com.example.test;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity2);
getActionBar().setDisplayHomeAsUpEnabled(true);
}
@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_activity2, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
TUTORIALS POINT
Simply Easy Learning
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
moveTaskToBack(true);
MainActivity2.this.finish();
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="87dp"
android:text="@string/test1"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:onClick="activity2"
android:text="@string/go2" />
</RelativeLayout>
<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=".MainActivity2" >
TUTORIALS POINT
Simply Easy Learning
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="125dp"
android:text="@string/test2"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
<string name="app_name">test</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="test1">This is activity 1</string>
<string name="test2">This is activity 2</string>
<string name="go1">Go to activity 1</string>
<string name="go2">Go to activity 2</string>
<string name="title_activity_main_activity2">MainActivity2</string>
</resources>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="14" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.test.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
TUTORIALS POINT
Simply Easy Learning
</application>
</manifest>
Let's try to run your Navigation application. I assume you had created your AVD while doing environment setup. To
run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse
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 the go to activity2 button and the following screen will be shown to you.
TUTORIALS POINT
Simply Easy Learning
Now at the top right corner , you will see the back button. Just press the back button and you will be brought to
first activity.
TUTORIALS POINT
Simply Easy Learning
Now again go to activity2 and this time press the device exit button. You will see your application will be closed. It
is shown in the image below:
TUTORIALS POINT
Simply Easy Learning
TUTORIALS POINT
Simply Easy Learning
CHAPTER
53
Android Network Connection
A ndroid 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.
Once you instantiate the object of ConnectivityManager class, you can use getAllNetworkInfo method to get the
information of all the networks. This method returns an array of NetworkInfo. So you have to recieve it like this.
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
TUTORIALS POINT
Simply Easy Learning
4 Suspended
5 Unknown
Android provides HttpURLConnection and URL class to handle these operations. You need to instantiate an
object of URL class by providing the link of website. Its syntax is as follows:
After that you need to call openConnection method of url class and recieve 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
useInputStream and BufferedReader class. Its syntax is given below:
InputStream is = conn.getInputStream();
BufferedReader reader =new BufferedReader(new InputStreamReader(is, "UTF-8"));
String webPage = "",data="";
while ((data = reader.readLine()) != null){
webPage += data + "\n";
}
Apart from this connect method, there are other methods availaible in HttpURLConnection class. They are listed
below:
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
setRequestMethod(String method)
4
This method Sets the request command which will be sent to the remote HTTP server
usingProxy()
5
This method cReturns whether this connection uses a proxy server or not
Example
The below example demonstrates the use of HttpURLConnection class. It crates a basic application that allows
you to download HTML from a given webpage.
TUTORIALS POINT
Simply Easy Learning
To experiment with this example , you need to run this on an actual device on which wifi internet is connected .
Steps Description
You will use Eclipse IDE to create an Android application and name it as NetworkConnection under a
1 package com.example.networkconnection. While creating this project, make sure you Target SDK and
Compile With at the latest version of Android SDK to use higher levels of APIs.
4 Modify layout XML file res/layout/activity_main.xml add any GUI component if required.
Run the application and choose a running android device and install the application on it and verify the
7
results.
package com.example.networkconnection;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
@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;
}
TUTORIALS POINT
Simply Easy Learning
package com.example.networkconnection;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
}
else{
Toast.makeText(context, "not conencted to internet",
Toast.LENGTH_SHORT).show();
}
}
protected void onPreExecute(){
checkInternetConenction();
}
@Override
protected String doInBackground(String... arg0) {
try{
String link = (String)arg0[0];
URL url = new URL(link);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
TUTORIALS POINT
Simply Easy Learning
InputStream is = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader
(is, "UTF-8") );
String data = null;
String webPage = "";
while ((data = reader.readLine()) != null){
webPage += data + "\n";
}
return webPage;
}catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
@Override
protected void onPostExecute(String result){
this.dataField.setText(result);
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:text="@string/url"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="18dp"
android:ems="10" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText1"
android:layout_centerHorizontal="true"
android:layout_marginTop="69dp"
android:onClick="download"
android:text="@string/click" />
TUTORIALS POINT
Simply Easy Learning
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText1"
android:layout_below="@+id/button1"
android:layout_marginTop="56dp"
android:text="@string/google"
android:textAppearance="?android:attr/textAppearanceSmall" />
</RelativeLayout>
<string name="app_name">NetworkConnection</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="url">URL here</string>
<string name="click">Download WebPage</string>
<string name="google">http://www.tutorialspoint.com</string>
</resources>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<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.networkconnection.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
Let's try to run your NetworkConnection 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
TUTORIALS POINT
Simply Easy Learning
icon from the toolbar. Before starting your application, Eclipse 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:
TUTORIALS POINT
Simply Easy Learning
Now just type in your website whose HTML you want to fetch. In my case i am typing tutorialspoint.com. It is shown
in the figure:
TUTORIALS POINT
Simply Easy Learning
Now press the Download WebPage button and wait a few seconds and HTML will be downloaded and will be
shown to you. It is shown in the figure below:
TUTORIALS POINT
Simply Easy Learning
TUTORIALS POINT
Simply Easy Learning
CHAPTER
54
Android NFC Guide
N FC stands for Near Field Communication, and as the name implies it provides a wireless
communication mechanism between two compatabile devices. NFC is a short range wireless technology having a
range of 4cm or less for two devices to share data.
How It Works:
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 complecities. 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:
2. P2P mode:
This mode allows NFC device to exchange data with other NFC peers.
It allows the NFC device itself to act as an NFC card, so it can be accessed by an external NFC reader.
TUTORIALS POINT
Simply Easy Learning
<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.
Android provides a android.nfc package for communicating with another device. This package contains following
classes:
Sr.No Classes
NdefMessage
1
It represents an immutable NDEF Message. .
NdefRecord
2
It represents an immutable NDEF Record.
NfcAdapter
3
It represents the local NFC adapter.
NfcEvent
4
It wraps information associated with any NFC event.
NfcManager
5
It is a high level manager used to obtain an instance of an NfcAdapter.
Tag
6
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:
ACTION_NDEF_DISCOVERED
1
This intent is used to start an Activity when a tag contains an NDEF payload.
ACTION_TECH_DISCOVERED
2
This intent is used to start an activity if the tag does not contain NDEF data, but is of known technology.
ACTION_TAG_DISCOVERED
3 This intent is started if no activities handle the ACTION_NDEF_DISCOVERED or
ACTION_TECH_DISCOVERED intents.
To code an application that uses NFC technology is complex so don't use it in your app unless necessary. The use
of NFC is not common in devices but it is getting popular. Let's see what is the future of this technology:
Future Applications:
With this technology growing day by day and tdue to introduction of contactless payment systems this technology
is gtting 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.
TUTORIALS POINT
Simply Easy Learning
CHAPTER
55
Android PHP/MySQL
I n 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 TABLEstatement 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";
}
?>
TUTORIALS POINT
Simply Easy Learning
INSERTING VALUES IN TABLES
When the database and tables are creted. 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";
}
?>
The first method to pass information is through GET method in which $_GET command is used. The variables are
passed in the url and the record is fetched. Its syntax is given below:
<?php
$con=mysqli_connect("example.com","username","password","database name");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$username = $_GET['username'];
$password = $_GET['password'];
$result = mysqli_query($con,"SELECT Role FROM table1 where Username='$username' and
Password='$password'");
$row = mysqli_fetch_array($result);
$data = $row[0];
if($data){
echo $data;
}
mysqli_close($con);
?>
The second method is to use POST method. The only change in the above script is to replace $_GET
with $_POST. In Post method , the variables are not passed through URL.
After that you need to call execute method of HttpClient class and recieve it in a HttpResponse object. After that
you need to open streams to recieve the data.
TUTORIALS POINT
Simply Easy Learning
HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
The last thing you need to do is to write this data to the link. After writing , you need to open stream to recieve the
responded data.
EXAMPLE
The below example is a complete example of connecting your android application with MYSQL database via PHP
page. It crates 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);
?>
TUTORIALS POINT
Simply Easy Learning
ANDROID PART
To experiment with this example , you need to run this on an actual device on which wifi internet is connected.
Steps Description
You will use Eclipse IDE to create an Android application and name it as PHPMYSQL under a package
1 com.example.phpmysql. While creating this project, make sure you Target SDK and Compile With at the
latest version of Android SDK to use higher levels of APIs.
4 Modify layout XML file res/layout/activity_main.xml add any GUI component if required.
Run the application and choose a running android device and install the application on it and verify the
7
results.
package com.example.phpmysql;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
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);
}
@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;
}
public void login(View view){
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
TUTORIALS POINT
Simply Easy Learning
method.setText("Get Method");
new SigninActivity(this,status,role,0).execute(username,password);
}
public void loginPost(View view){
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
method.setText("Post Method");
new SigninActivity(this,status,role,1).execute(username,password);
package com.example.phpmysql;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.TextView;
}
@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;
TUTORIALS POINT
Simply Easy Learning
URL url = new URL(link);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(link));
HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
TUTORIALS POINT
Simply Easy Learning
<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" >
<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" />
<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" />
TUTORIALS POINT
Simply Easy Learning
<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
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"
TUTORIALS POINT
Simply Easy Learning
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>
<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>
<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>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<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>
TUTORIALS POINT
Simply Easy Learning
<action android:name="android.intent.action.MAIN" />
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 Eclipse, open one of your project's activity files and click Run icon from the
toolbar. Before starting your application, Eclipse 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:
TUTORIALS POINT
Simply Easy Learning
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:
TUTORIALS POINT
Simply Easy Learning
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:
TUTORIALS POINT
Simply Easy Learning
Now again press the POST button and same result woud appear. It is shown in the figure below:
TUTORIALS POINT
Simply Easy Learning
TUTORIALS POINT
Simply Easy Learning
CHAPTER
56
Android Progress Circle
T he 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 donot 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
Apart from these methods, there are other methods that are provided by the ProgressDialog class
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
TUTORIALS POINT
Simply Easy Learning
Example
This example demonstrates the spiining 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.
Steps Description
You will use Eclipse IDE to create an Android application and name it as ProgressDialog under a package
1 com.example.progressdialog. While creating this project, make sure you Target SDK and Compile With at
the latest version of Android SDK to use higher levels of APIs.
2 Modify src/MainActivity.java file to add progress code to display the spinning progress dialog.
Run the application and choose a running android device and install the application on it and verify the
5
results.
package com.example.progressdialog;
import com.example.progressdialog.R;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.view.Menu;
import android.view.View;
@Override
public void run(){
TUTORIALS POINT
Simply Easy Learning
int jumpTime = 0;
while(jumpTime < totalProgressTime){
try {
sleep(200);
jumpTime += 5;
progress.setProgress(jumpTime);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
t.start();
}
@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;
}
}
<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" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="150dp"
android:onClick="open"
android:text="@string/download_button" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="19dp"
android:text="@string/download_text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
TUTORIALS POINT
Simply Easy Learning
Modify the res/values/string.xml to the following
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.progressdialog.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
Let's try to run your ProgressDialog 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, Eclipse will display following window to select an option where
you want to run your Android application.
TUTORIALS POINT
Simply Easy Learning
Select your mobile device as an option and then check your mobile device which will display following screen:
TUTORIALS POINT
Simply Easy Learning
Just press the button to start the Progress Dialog. After pressing , following screen would appear
TUTORIALS POINT
Simply Easy Learning
TUTORIALS POINT
Simply Easy Learning
CHAPTER
57
Android ProgressBar
P rogress bars are used to show progress of a task. For example. When you are uploading or downloading
something from the internet, it is better to show the progress of download/upload to the user.
In android there is a class called ProgressDialog that allow you to create progress bar. 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
Apart from these methods, there are other methods that are provided by the ProgressDialog class
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
TUTORIALS POINT
Simply Easy Learning
Example
This example demonstrates the horizontol use of the progress dialog which is infact 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 on after developing the application
according to the steps below.
Steps Description
You will use Eclipse IDE to create an Android application and name it as ProgressDialog under a
1 package com.example.progressdialog. While creating this project, make sure you Target SDK and
Compile With at the latest version of Android SDK to use higher levels of APIs.
2 Modify src/MainActivity.java file to add progress code to display the progress dialog.
Run the application and choose a running android device and install the application on it and verify the
5
results.
package com.example.progressdialog;
import com.example.progressdialog.R;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.view.Menu;
import android.view.View;
@Override
public void run(){
TUTORIALS POINT
Simply Easy Learning
int jumpTime = 0;
while(jumpTime < totalProgressTime){
try {
sleep(200);
jumpTime += 5;
progress.setProgress(jumpTime);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
t.start();
}
@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;
}
}
<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" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="150dp"
android:onClick="open"
android:text="@string/download_button" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="19dp"
android:text="@string/download_text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
TUTORIALS POINT
Simply Easy Learning
Modify the res/values/string.xml to the following
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.progressdialog.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
Let's try to run your ProgressDialog 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, Eclipse will display following window to select an option where
you want to run your Android application.
TUTORIALS POINT
Simply Easy Learning
Select your mobile device as an option and then check your mobile device which will display following screen:
TUTORIALS POINT
Simply Easy Learning
Just press the button to start the Progress bar. After pressing , following screen would appear
TUTORIALS POINT
Simply Easy Learning
It will continously update itself, and after few seconds , it would appear something like this.
TUTORIALS POINT
Simply Easy Learning
TUTORIALS POINT
Simply Easy Learning
CHAPTER
58
Android Push Notification
A notification is a message you can display to the user outside of your application's normal UI. You can
Android provides NotificationManager class for this purpose. In order to use this class, you need to instantiate an
object of this class by requesting the android system through getSystemService() method. Its syntax is given
below:
NotificationManager NM;
NM=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
After that you will create Notification through Notification class and specify its attributes such as icon,title and time
e.t.c. Its syntax is given below:
Notification notify=new
Notification(android.R.drawable.stat_notify_more,title,System.currentTimeMillis());
The next thing you need to do is to create a PendingIntent by passing context and intent as a parameter. By
giving a PendingIntent to another application, you are granting it the right to perform the operation you have
specified as if the other application was yourself.
The last thing you need to do is to call setLatestEventInfo method of the Notification class and pass the pending
intent along with notfication subject and body details. Its syntax is given below. And then finally call the notify
method of the NotificationManager class.
Apart from the notify method, there are other methods availaible in the NotificationManager class. They are listed
below:
cancel(int id)
1
This method cancel a previously shown notification.
TUTORIALS POINT
Simply Easy Learning
This method also cancel a previously shown notification.
cancelAll()
3
This method cancel all previously shown notifications.
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.
Steps Description
You will use Eclipse IDE to create an Android application and name it as Status under a package
1 com.example.status. While creating this project, make sure you Target SDK and Compile With at the
latest version of Android SDK to use higher levels of APIs.
3 Modify layout XML file res/layout/activity_main.xml add any GUI component if required.
Run the application and choose a running android device and install the application on it and verify the
5
results.
package com.example.status;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
NotificationManager NM;
EditText one,two,three;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
one = (EditText)findViewById(R.id.editText1);
two = (EditText)findViewById(R.id.editText2);
TUTORIALS POINT
Simply Easy Learning
three = (EditText)findViewById(R.id.editText3);
}
@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;
}
@SuppressWarnings("deprecation")
public void notify(View vobj){
String title = one.getText().toString();
String subject = two.getText().toString();
String body = three.getText().toString();
NM=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Notification notify=new Notification(android.R.drawable.
stat_notify_more,title,System.currentTimeMillis());
PendingIntent pending=PendingIntent.getActivity(
getApplicationContext(),0, new Intent(),0);
notify.setLatestEventInfo(getApplicationContext(),subject,body,pending);
NM.notify(0, notify);
}
}
<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" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="86dp"
android:onClick="notify"
android:text="@string/notification" />
<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="53dp"
android:ems="10" />
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
TUTORIALS POINT
Simply Easy Learning
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText1"
android:layout_below="@+id/editText1"
android:layout_marginTop="28dp"
android:ems="10" />
<EditText
android:id="@+id/editText3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText2"
android:layout_below="@+id/editText2"
android:layout_marginTop="23dp"
android:ems="10" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/editText1"
android:layout_marginRight="14dp"
android:layout_toLeftOf="@+id/editText1"
android:text="@string/title" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/editText3"
android:layout_alignRight="@+id/textView1"
android:text="@string/heading" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/editText3"
android:layout_alignLeft="@+id/textView2"
android:text="@string/body" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="@+id/textView2"
android:text="@string/create"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
<string name="app_name">Status</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="notification">Notify</string>
<string name="title">Title</string>
TUTORIALS POINT
Simply Easy Learning
<string name="heading">Subject</string>
<string name="body">Body</string>
<string name="create">Create Notification</string>
</resources>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.status.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
Let's try to run your TextToSpeech 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, Eclipse will display following window to select an option where
you want to run your Android application.
TUTORIALS POINT
Simply Easy Learning
Select your mobile device as an option and then check your mobile device which will display following screen:
TUTORIALS POINT
Simply Easy Learning
Now fill in the field with the title , subject and the body. This has been shown below in the figure:
TUTORIALS POINT
Simply Easy Learning
Now click on the notify button and you will see a notification in the top notification bar. It has been shown below:
TUTORIALS POINT
Simply Easy Learning
Now scroll down the notification bar and see the notification. This has been shown below in the figure:
TUTORIALS POINT
Simply Easy Learning
TUTORIALS POINT
Simply Easy Learning
CHAPTER
59
Android RenderScript
I n this chapter, we will learn about Android RenderScript. Usually the apps on android are designed as to
consume as minimum resources as possible. But some applications like some 3D games need high level
processing on android.
To provide these applications high performance android introduced the RenderScript. It is android based
framework which is used for running applications that perform very highly computational tasks. The development
on this framework is done in Native Development Kit(NDK) provided by android. RenderScript is extremely useful
for applicatons which performs following types of actions:
3D Rendring
Image Processing
Computational Photography
Computer Vision
This parallel distribution of workload frees the programmer from the tension of load balancing and work
scheeduling. 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:
1. A RenderScript Kernel
2. RenderScript APIs
TUTORIALS POINT
Simply Easy Learning
A RENDERSCRIPT KERNEL
A kernel is a program which manages data processing instructions and manage workload on Central Processing
Units.A kernel is a fundamental part of the operating system.
Similarly to run the RenderScript framework we need a written script named as Kernel to manage all the data
processing requests from our app and utilize more features of the android OS provided by the NDK and as
mentioned earlier that the development of RenderScript is done in the Native Development Kit of Android.
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.No Elements
A Language declaration
1
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 RenderScrip in your API, you can do it in following two ways:
Sr.No APIs
android.renderscript
1
This API is available on devices running Android 3.0 and higher.
android.support.v8.renderscript
2
This API is available on devices running Android 2.2 and higher.
TUTORIALS POINT
Simply Easy Learning
Android SDK Build-tools version 18.1.0
renderscript.target=18
renderscript.support.mode=true
sdk.buildtools=18.1.0
Now open your main class which use RenderScript and add an import for the Support Library classes as following:
import android.support.v8.renderscript.*;
Following are the purposes of above mentioned properties that we add in the project.properties file.
renderscript.target
1
It specifies the bytecode version to be generated.
renderscript.support.mode
2
It specifies a compatible version for the generated byteCcode to fall back.
sdk.buildtools
3
It Specifies the versions of Android SDK build tools to use.
Now call your RenderScript Kernel functions and compute complex algorithms in your app.
TUTORIALS POINT
Simply Easy Learning
CHAPTER
60
Android RSS Reader
R SS stands for Really Simple Syndication. RSS is an easy way to share your website updates and content
with your users so that users might not have to visit your site daily for any kind of updates.
RSS Example
RSS is a doucment 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 hyperlink to the channel
description
4
Describes the channel
TUTORIALS POINT
Simply Easy Learning
Parsing RSS
Parsing an RSS dcument 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:
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 seperate function for parsing each of the component of XML file. Its syntax is given below:
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 methodgetAttributeValue 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:
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.
TUTORIALS POINT
Simply Easy Learning
getNamespace()
6
This method rReturns the namespace 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.
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 athttp://tutorialspoint.com/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.
Steps Description
You will use Eclipse IDE to create an Android application and name it as RSSReader under a package
1 com.example.rssreader. While creating this project, make sure you Target SDK and Compile With at the
latest version of Android SDK to use higher levels of APIs.
5 Create a new java file under src/HandleXML.java to fetch and parse XML data.
Run the application and choose a running android device and install the application on it and verify the
7
results.
package com.example.rssreader;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
@Override
protected void onCreate(Bundle savedInstanceState) {
TUTORIALS POINT
Simply Easy Learning
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
title = (EditText)findViewById(R.id.editText1);
link = (EditText)findViewById(R.id.editText2);
description = (EditText)findViewById(R.id.editText3);
}
@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;
}
public void fetch(View view){
obj = new HandleXML(finalUrl);
obj.fetchXML();
while(obj.parsingComplete);
title.setText(obj.getTitle());
link.setText(obj.getLink());
description.setText(obj.getDescription());
}
}
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;
TUTORIALS POINT
Simply Easy Learning
try {
event = myParser.getEventType();
while (event != XmlPullParser.END_DOCUMENT) {
String name=myParser.getName();
switch (event){
case XmlPullParser.START_TAG:
break;
case XmlPullParser.TEXT:
text = myParser.getText();
break;
case XmlPullParser.END_TAG:
if(name.equals("title")){
title = text;
}
else if(name.equals("link")){
link = text;
}
else if(name.equals("description")){
description = text;
}
else{
}
break;
}
event = myParser.next();
}
parsingComplete = false;
} catch (Exception e) {
e.printStackTrace();
}
}
public void fetchXML(){
Thread thread = new Thread(new Runnable(){
@Override
public void run() {
try {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
InputStream stream = conn.getInputStream();
xmlFactoryObject = XmlPullParserFactory.newInstance();
XmlPullParser myparser = xmlFactoryObject.newPullParser();
myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
myparser.setInput(stream, null);
parseXMLAndStoreIt(myparser);
stream.close();
} catch (Exception e) {
}
}
});
thread.start();
}
}
TUTORIALS POINT
Simply Easy Learning
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="26dp"
android:text="@string/hello_world"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_marginTop="48dp"
android:layout_toLeftOf="@+id/textView1"
android:text="@string/title" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView2"
android:layout_below="@+id/textView2"
android:layout_marginTop="27dp"
android:text="@string/link" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView2"
android:layout_alignBottom="@+id/textView2"
android:layout_alignParentRight="true"
android:ems="10" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView3"
android:layout_alignBottom="@+id/textView3"
android:layout_alignLeft="@+id/editText1"
android:ems="10" >
</EditText>
<EditText
android:id="@+id/editText3"
android:layout_width="wrap_content"
TUTORIALS POINT
Simply Easy Learning
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView4"
android:layout_alignBottom="@+id/textView4"
android:layout_alignLeft="@+id/editText2"
android:ems="10" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText3"
android:layout_centerHorizontal="true"
android:layout_marginTop="37dp"
android:onClick="fetch"
android:text="@string/fetch" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="@string/description" />
</RelativeLayout>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.rssreader.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
TUTORIALS POINT
Simply Easy Learning
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your RSSReader application.I assume you had created your AVD while doing environment setup.
To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Eclipse
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:
Just press the Fetch Feed button to fetch RSS feed. After pressing , following screen would appear which would
show the RSS data.
TUTORIALS POINT
Simply Easy Learning
TUTORIALS POINT
Simply Easy Learning
CHAPTER
61
Android Screen Cast
A ndroid Screen cast is a desktop application to control an android device remotely. If your phone is not
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
Install Java run time 5 or later , if you have not installed already. You can install it here.
STEP 5
Finally install the androidScreenCast application. You can download it here.. Once you download it open it by
clicking it. It is shown below:
TUTORIALS POINT
Simply Easy Learning
Just wait a few seconds and application will load and following popup will appear asking your permission to launch
this application. Click on accept check box and click on run. It is shown below:
If everything work fine, you will now see your phone on your pc. Navigate through your phone and you will see
your mobile working on your pc. It is shown below:
TUTORIALS POINT
Simply Easy Learning
You can see the message application in the above picture, that's because i have open the messaging application
in my mobile. Now type something from your mobile.
TUTORIALS POINT
Simply Easy Learning
As you can see , i have written some text in the sms from my mobile and it appears on PC. So this way you can
use this ScreenCast application.
TUTORIALS POINT
Simply Easy Learning
CHAPTER
62
Android SDK Manager
T o download and install latest android APIs and development tools from the internet, android provide us
with android SDK manager. Android SDK Manager seperates the APIs, tools and different platforms into different
packages which you can download.
Android SDK manager comes with the Android SDK bundle. You can't download it seperately. You can download
the android sdk from here.
TUTORIALS POINT
Simply Easy Learning
You can select which package you want to download by selecting the checkboxex and then click Installto 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 availabe but first three are necessary to run your SDK and
others are recommended.
RECOMMENDED PACKAGES
Sr.No Package
SDK Tools
1
This is necessary package to run your SDK.
SDK Platform-tools
2
This package will be installed once when you first run the SDK manager.
SDK Platform
3
Atleast 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.
SDK Samples
5
This will give you some sample codes to learn about android.
TUTORIALS POINT
Simply Easy Learning
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:
TUTORIALS POINT
Simply Easy Learning
Just add the URL of Add-on.xml file and click Ok. Now you can download the Third Party Add-on in your
development environemnt and use it.
TUTORIALS POINT
Simply Easy Learning
CHAPTER
63
Android Sensors
M ost 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.
1. Motion Sensors
2. Environmental sensors
3. 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.
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 sytanx is given below:
Sensor light;
light = sMgr.getDefaultSensor(Sensor.TYPE_LIGHT);
Once that sensor is declared , you need to register its listener and override two methods which are
onAccuracyChanged and onSensorChanged. Its syntax is as follows:
sMgr.registerListener(this, light,SensorManager.SENSOR_DELAY_NORMAL);
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void onSensorChanged(SensorEvent event) {
}
TUTORIALS POINT
Simply Easy Learning
Getting list of sensors supported.
You can get a list of sensors supported by your device by calling the getSensorList method , which will return a list
of sensors containing their name and version number and much more information. You can then iterate the list to
get the information. Its syntax is given below:
sMgr = (SensorManager)this.getSystemService(SENSOR_SERVICE);
List<Sensor> list = sMgr.getSensorList(Sensor.TYPE_ALL);
for(Sensor sensor: list){
}
Apart from the these methods , there are other methods provided by the SensorManager class for managing
sensors framework. These methods are listed below:
getDefaultSensor(int type)
1
This method get the default sensor for a given type.
getInclination(float[] I)
3
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.
Steps Description
You will use Eclipse IDE to create an Android application and name it as Sensors under a package
1 com.example.sensors. While creating this project, make sure you Target SDK and Compile With at the
latest version of Android SDK to use higher levels of APIs.
TUTORIALS POINT
Simply Easy Learning
Run the application and choose a running android device and install the application on it and verify the
5
results.
package com.example.sensors;
import java.util.List;
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
sMgr = (SensorManager)this.getSystemService(SENSOR_SERVICE);
List list = sMgr.getSensorList(Sensor.TYPE_ALL);
}
sensorsData.setText(data);
}
@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;
}
<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" >
<ScrollView
TUTORIALS POINT
Simply Easy Learning
android:id="@+id/scrollView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="16dp"
android:layout_marginTop="16dp" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
</ScrollView>
</RelativeLayout>
<string name="app_name">Sensors</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="list">List of sensors supported</string>
</resources>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.sensors.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
TUTORIALS POINT
Simply Easy Learning
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run our Sensor application we just modified. I assume you had created your AVD while doing
environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from
the toolbar. Eclipse 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 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 differnet because the output depends
upon the number of sensors supported by your device.
TUTORIALS POINT
Simply Easy Learning
CHAPTER
64
Android Session Management
S ession 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 poiting
to the file that contains the values of preferences.
You can save something in the sharedpreferences by using SharedPreferences.Editor class. You will call the edit
method of SharedPreference instance and will recieve it in an editor object. Its syntax is:
Apart from the putString method , there are methods availaible in the editor class that allows manipulation of data
inside shared preferences. They are listed as follows:
Sr.
Mode and description
NO
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
TUTORIALS POINT
Simply Easy Learning
It will save a integer value in a preference editor
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 .
Steps Description
You will use Eclipse IDE to create an Android application and name it as SessionManagement under a
1 package com.example.sessionmanagement. While creating this project, make sure you Target SDK and
Compile With at the latest version of Android SDK to use higher levels of APIs.
3 Create New Activity and it name as Welcome.java.Edit this file to add progress code to add session code.
Run the application and choose a running android device and install the application on it and verify the
7
results.
package com.example.sessionmanagement;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
TUTORIALS POINT
Simply Easy Learning
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = (EditText)findViewById(R.id.editText1);
password = (EditText)findViewById(R.id.editText2);
}
@Override
protected void onResume() {
sharedpreferences=getSharedPreferences(MyPREFERENCES,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(name))
{
if(sharedpreferences.contains(pass)){
Intent i = new Intent(this,com.example.sessionmanagement.
Welcome.class);
startActivity(i);
}
}
super.onResume();
}
package com.example.sessionmanagement;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
}
TUTORIALS POINT
Simply Easy Learning
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.welcome, menu);
return true;
}
public void logout(View view){
SharedPreferences sharedpreferences = getSharedPreferences
(MainActivity.MyPREFERENCES, Context.MODE_PRIVATE);
Editor editor = sharedpreferences.edit();
editor.clear();
editor.commit();
moveTaskToBack(true);
Welcome.this.finish();
}
public void exit(View view){
moveTaskToBack(true);
Welcome.this.finish();
}
}
<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" >
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/editText1"
android:layout_below="@+id/textView2"
android:ems="10"
android:inputType="textPassword" >
</EditText>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="52dp"
android:text="@string/Username"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="@+id/textView1"
android:layout_marginRight="16dp"
android:layout_marginTop="27dp"
TUTORIALS POINT
Simply Easy Learning
android:ems="10" >
<requestFocus />
</EditText>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/textView1"
android:layout_below="@+id/editText1"
android:text="@string/Password"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/editText1"
android:layout_centerHorizontal="true"
android:layout_marginBottom="22dp"
android:text="@string/Signin"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText2"
android:layout_centerHorizontal="true"
android:layout_marginTop="45dp"
android:onClick="login"
android:text="@string/Login" />
</RelativeLayout>
<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=".Welcome" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="146dp"
android:onClick="logout"
android:text="@string/logout" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
TUTORIALS POINT
Simply Easy Learning
android:layout_alignLeft="@+id/button1"
android:layout_alignParentTop="true"
android:layout_marginTop="64dp"
android:text="@string/title_activity_welcome"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button1"
android:layout_centerHorizontal="true"
android:layout_marginTop="43dp"
android:onClick="exit"
android:text="@string/exit" />
</RelativeLayout>
<string name="app_name">SessionManagement</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="Signin">Sign In</string>
<string name="Login">Login</string>
<string name="logout">Logout</string>
<string name="title_activity_welcome">Welcome</string>
<string name="exit">Exit without logout</string>
</resources>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.sessionmanagement.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
TUTORIALS POINT
Simply Easy Learning
</activity>
<activity
android:name="com.example.sessionmanagement.Welcome"
android:label="@string/title_activity_welcome" >
</activity>
</application>
</manifest>
Let's try to run your Session Management application. I assume you had created your AVD while doing
environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from
the toolbar. Eclipse 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:
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:
TUTORIALS POINT
Simply Easy Learning
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.
TUTORIALS POINT
Simply Easy Learning
Now click on Exit without logout button and you will be brought back to the home screen. This is shown in the
image below:
TUTORIALS POINT
Simply Easy Learning
Now Start the application again. And this time you will not be brought to the login screen, but directly to the
welcome screen.This is shown in the image below:
TUTORIALS POINT
Simply Easy Learning
Now click on logout button, and the application will be closed. Now open the application again, and since this time
you logout your session, so you will be brought back to the front login screen. This is shown in the image below:
TUTORIALS POINT
Simply Easy Learning
TUTORIALS POINT
Simply Easy Learning
CHAPTER
65
Android Shared Preferences
A ndroid provides many ways of storing data of an application. One of this way is called Shared
Preferences. Shared Preferences allow you to save and retrieve data in the form of key,value pair.
In order to use shared preferences , you have to call a method getSharedPreferences() that returns a
SharedPreference instance poiting to the file that contains the values of preferences.
The first parameter is the key and the second parameter is the MODE. Apart from private there are other modes
availaible that are listed below:
Sr.
Mode and description
NO
MODE_APPEND
1
This will append the new preferences with the already exisiting preferences
MODE_ENABLE_WRITE_AHEAD_LOGGING
2
Database open flag. When it is set , it would enable write ahead logging by default
MODE_MULTI_PROCESS
3 This method will check for modification of preferences even if the sharedpreference instance has already
been loaded
MODE_PRIVATE
4
By setting this mode , the file can only be accessed using calling application
MODE_WORLD_READABLE
5
This mode allow other application to read the preferences
MODE_WORLD_WRITEABLE
6
This mode allow other application to write the preferences
You can save something in the sharedpreferences by using SharedPreferences.Editor class. You will call the edit
method of SharedPreference instance and will recieve it in an editor object. Its syntax is:
TUTORIALS POINT
Simply Easy Learning
editor.commit();
Apart from the putString method , there are methods availaible in the editor class that allows manipulation of data
inside shared preferences. They are listed as follows:
Sr.
Mode and description
NO
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:
Steps Description
You will use Eclipse IDE to create an Android application and name it as SharedPreferences under a
1 package com.example.sharedpreferences. While creating this project, make sure you Target SDK and
Compile With at the latest version of Android SDK to use higher levels of APIs.
2 Modify src/MainActivity.java file to add progress code to display the spinning progress dialog.
Run the application and choose a running android device and install the application on it and verify the
5
results.
package com.example.sharedpreferences;
import com.example.sharedpreferences.*;
import android.os.Bundle;
import android.app.Activity;
TUTORIALS POINT
Simply Easy Learning
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
TextView name ;
TextView phone;
TextView email;
TextView street;
TextView place;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String Name = "nameKey";
public static final String Phone = "phoneKey";
public static final String Email = "emailKey";
public static final String Street = "streetKey";
public static final String Place = "placeKey";
SharedPreferences sharedpreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedpreferences = getSharedPreferences(MyPREFERENCES,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(Name))
{
name.setText(sharedpreferences.getString(Name, ""));
}
if (sharedpreferences.contains(Phone))
{
phone.setText(sharedpreferences.getString(Phone, ""));
}
if (sharedpreferences.contains(Email))
{
email.setText(sharedpreferences.getString(Email, ""));
}
if (sharedpreferences.contains(Street))
{
street.setText(sharedpreferences.getString(Street, ""));
}
if (sharedpreferences.contains(Place))
{
place.setText(sharedpreferences.getString(Place,""));
TUTORIALS POINT
Simply Easy Learning
}
editor.commit();
}
@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;
}
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".DisplayContact" >
<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>
TUTORIALS POINT
Simply Easy Learning
<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" />
<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"
TUTORIALS POINT
Simply Easy Learning
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"
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>
<string name="app_name">SharedPreferences</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="name">Name</string>
<string name="phone">Phone</string>
<string name="email">Email</string>
<string name="street">Street</string>
<string name="country">City/State/Zip</string>
</resources>
TUTORIALS POINT
Simply Easy Learning
Following is the content default file AndroidManifest.xml.
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.sharedpreferences.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
Let's try to run your SharedPreferences 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, Eclipse will display following window to select an option
where you want to run your Android application.
TUTORIALS POINT
Simply Easy Learning
Select your mobile device as an option and then check your mobile device which will display following screen:
TUTORIALS POINT
Simply Easy Learning
Now just put in some text in the field. Like i put some random name and other information and click on save button.
TUTORIALS POINT
Simply Easy Learning
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.
TUTORIALS POINT
Simply Easy Learning
TUTORIALS POINT
Simply Easy Learning
CHAPTER
66
Android SIP Protocol
S IP 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:
SIP Classes
Here is a summary of the classes that are included in the Android SIP API:
Sr.
Class and description
NO
SipAudioCall
1
Handles an Internet audio call over SIP
SipErrorCode
2
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
TUTORIALS POINT
Simply Easy Learning
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 funcitons.
Components of SIP
SIP has two major components which are listed below.
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 requeste 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.
Class and description
NO
close(String localProfileUri)
1
Closes the specified profile to not make/receive calls
getCallId(Intent incomingCallIntent)
2
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
isSipWifiOnly(Context context)
4
Returns true if SIP is only available on WIFI
TUTORIALS POINT
Simply Easy Learning
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
isVoipSupported(Context context)
6
Returns true if the system supports SIP-based VOIP API
TUTORIALS POINT
Simply Easy Learning
CHAPTER
67
Android Spell Checker
T he Android platform offers a spelling checker framework that lets you implement and access spell
In order to use spelling checker , you need to implement SpellCheckerSessionListener interface and override its
methods. Its syntax is given below:
@Override
public void onGetSentenceSuggestions(SentenceSuggestionsInfo[] arg0) {
// TODO Auto-generated method stub
}
}
Next thing you need to do is to create an object of SpellCheckerSession class. This object can be instantiated by
calling newSpellCheckerSession method of TextServicesManager class. This class handles interaction between
application and text services. You need to request system service to instantiate it. Its sytnax is given below:
The last thing you need to do is to call getSuggestions method to get suggestion for any text , you want. The
suggestions will be passed onto the onGetSuggestions method from where you can do whatever you want.
This method takes two parameters. First parameter is the string in the form of TextInfo object , and second
paramater 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:
TUTORIALS POINT
Simply Easy Learning
Sr.No Method & description
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.br>
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.
Steps Description
You will use Eclipse IDE to create an Android application and name it as HelloSpellCheckerActivity
1 under a package com.example.hellospellchecker. While creating this project, make sure you Target SDK
and Compile With at the latest version of Android SDK to use higher levels of APIs.
Run the application and choose a running android device and install the application on it and verify the
5
results
package com.example.android.hellospellchecker;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.textservice.SentenceSuggestionsInfo;
import android.view.textservice.SpellCheckerSession;
import android.view.textservice.SpellCheckerSession.SpellCheckerSessionListener;
import android.view.textservice.SuggestionsInfo;
import android.view.textservice.TextInfo;
import android.view.textservice.TextServicesManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
TUTORIALS POINT
Simply Easy Learning
public class HelloSpellCheckerActivity extends Activity implements
SpellCheckerSessionListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mMainView = (TextView)findViewById(R.id.main);
editText1 = (EditText)findViewById(R.id.editText1);
}
@Override
public void onResume() {
super.onResume();
final TextServicesManager tsm = (TextServicesManager) getSystemService(
Context.TEXT_SERVICES_MANAGER_SERVICE);
mScs = tsm.newSpellCheckerSession(null, null, this, true);
}
@Override
public void onPause() {
super.onPause();
if (mScs != null) {
mScs.close();
}
}
}
@Override
public void onGetSuggestions(final SuggestionsInfo[] arg0) {
final StringBuilder sb = new StringBuilder();
}
@Override
public void onGetSentenceSuggestions(SentenceSuggestionsInfo[] arg0) {
TUTORIALS POINT
Simply Easy Learning
// TODO Auto-generated method stub
}
}
<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/main"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/pre"
/>
<Button
android:id="@+id/mainbtn"
android:layout_width="150dip"
android:layout_height="50dip"
android:onClick="go"
android:text="@string/suggest" />
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
</LinearLayout>
<resources>
<string name="app_name">HelloSpellChecker</string>
<string name="suggest">suggest</string>
<string name="pre">Suggestions</string>
</resources>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.hellospellchecker"
android:versionCode="1"
android:versionName="1.0" >
TUTORIALS POINT
Simply Easy Learning
<uses-sdk android:minSdkVersion="14" />
<application
android:label="@string/app_name" >
<activity
android:label="@string/app_name"
android:name=".HelloSpellCheckerActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
</manifest>
Let's try to run our Spell Checker application we just modified. I assume you had created your AVDwhile doing
environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from
the toolbar. Eclipse 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:
TUTORIALS POINT
Simply Easy Learning
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:
Now change the text and press the button again , like i did. And this is what comes on screen.
TUTORIALS POINT
Simply Easy Learning
TUTORIALS POINT
Simply Easy Learning
CHAPTER
68
Android SQLite Database
S QLite is a opensource SQL database that stores data to a text file on a device. Android comes in with built
SQLite supports all the relational datbase 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 recieve in your own
object.Its syntax is given below
Apart from this , there are other functions availaible in the databsae package , that does this job. They are listed
below
TUTORIALS POINT
Simply Easy Learning
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
equavilent to file.getPath()
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
Database - Fetching
We can retrieve anything from datbase 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.
There are other functions availaible in the Cursor class that allows us to effectively retrieve the data. That includes
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
TUTORIALS POINT
Simply Easy Learning
isClosed()
7
This method returns true if the cursor is closed and return false otherwise
Example
Here is an example demonstrating the use of SQLite Datbase. 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.
Steps Description
You will use Eclipse IDE to create an Android application and name it as AddressBook under a package
1 com.example.addressbook. While creating this project, make sure you Target SDK and Compile With at
the latest version of Android SDK to use higher levels of APIs.
Modify src/MainActivity.java file to get refrences of all the XML components and populate the contacts on
2
listView.
4 Create a new Activity as DisplayContact.java that will display the contact on the screen
Run the application and choose a running android device and install the application on it and verify the
10
results.
package com.example.addressbook;
import java.util.ArrayList;
import android.os.Bundle;
TUTORIALS POINT
Simply Easy Learning
import android.app.Activity;
import android.content.Intent;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayAdapter arrayAdapter =
new ArrayAdapter(this,android.R.layout.simple_list_item_1, array_list);
obj.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
int id_To_Search = arg2 + 1;
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", id_To_Search);
Intent intent = new
Intent(getApplicationContext(),com.example.addressbook.DisplayContact.class);
intent.putExtras(dataBundle);
startActivity(intent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.mainmenu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
super.onOptionsItemSelected(item);
switch(item.getItemId())
{
case R.id.item1:
TUTORIALS POINT
Simply Easy Learning
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", 0);
Intent intent = new
Intent(getApplicationContext(),com.example.addressbook.DisplayContact.class);
intent.putExtras(dataBundle);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
public boolean onKeyDown(int keycode, KeyEvent event) {
if (keycode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
}
return super.onKeyDown(keycode, event);
}
package com.example.addressbook;
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;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
int from_Where_I_Am_Coming = 0;
private DBHelper mydb ;
TextView name ;
TextView phone;
TextView email;
TextView street;
TextView place;
int id_To_Update = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_contact);
name = (TextView) findViewById(R.id.editTextName);
phone = (TextView) findViewById(R.id.editTextPhone);
email = (TextView) findViewById(R.id.editTextStreet);
street = (TextView) findViewById(R.id.editTextEmail);
place = (TextView) findViewById(R.id.editTextCity);
TUTORIALS POINT
Simply Easy Learning
mydb = new DBHelper(this);
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);
}
TUTORIALS POINT
Simply Easy Learning
else{
getMenuInflater().inflate(R.menu.main, menu);
}
}
return 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:
return true;
default:
TUTORIALS POINT
Simply Easy Learning
return super.onOptionsItemSelected(item);
}
}
package com.example.addressbook;
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;
TUTORIALS POINT
Simply Easy Learning
public class DBHelper extends SQLiteOpenHelper {
@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) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
public boolean insertContact (String name, String phone, String email, String
street,String place)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("phone", phone);
contentValues.put("email", email);
contentValues.put("street", street);
contentValues.put("place", place);
TUTORIALS POINT
Simply Easy Learning
public boolean updateContact (Integer id, String name, String phone, String
email, String street,String place)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("phone", phone);
contentValues.put("email", email);
contentValues.put("street", street);
contentValues.put("place", place);
db.update("contacts", contentValues, "id = ? ", new String[] {
Integer.toString(id) } );
return true;
}
<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" >
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" >
</ListView>
</RelativeLayout>
TUTORIALS POINT
Simply Easy Learning
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".DisplayContact" >
<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" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
TUTORIALS POINT
Simply Easy Learning
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"
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"
TUTORIALS POINT
Simply Easy Learning
android:layout_below="@+id/editTextName"
android:ems="10"
android:inputType="phone|text" />
</RelativeLayout>
</ScrollView>
<string name="name">Name</string>
<string name="phone">Phone</string>
<string name="email">Email</string>
<string name="street">Street</string>
<string name="country">City/State/Zip</string>
</resources>
</menu>
TUTORIALS POINT
Simply Easy Learning
This is the defualt AndroidManifest.xml of this project
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.addressbook.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
Let's try to run your Camera 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, Eclipse will display following window to select an option where you want to
run your Android application.
TUTORIALS POINT
Simply Easy Learning
Select your mobile device as an option and then check your mobile device which will display following screen:
TUTORIALS POINT
Simply Easy Learning
Click on the add button on the top right corner of the menu screen to add a new contact. It will display the following
screen:
TUTORIALS POINT
Simply Easy Learning
It will display the following fields. Please enter the required infromation and click on save contact. It will bring you
back to main screen.
TUTORIALS POINT
Simply Easy Learning
Now our contact john has been added. Tap on this to edit it or delete it.It will bring you to the following screen.
Now select menu from your mobile. And there will be two options there.
TUTORIALS POINT
Simply Easy Learning
Select delete contact and an dialog box would appear asking you about deleting this contact. It would be like this
TUTORIALS POINT
Simply Easy Learning
Select Yes from the above screen that appears and a notification will appear that the contact has been deleted
successfully. It would appear like this
TUTORIALS POINT
Simply Easy Learning
In order to see that where is your database is created. Open your ecclipse, connect your mobile. Go to right corner
and select DDMS. Now browse the file explorer tab. Now browse this
folder/data/data/<your.package.name>/databases<database-name>.
TUTORIALS POINT
Simply Easy Learning
CHAPTER
69
Android Support Library
W hen you develop an app on a latest version of android like 4.0 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
compatability to your code.
To provide this backward compatability android provides you the Android Support Library package. The Android
Support Library package is a set of code libraries that provide backward-compatible versions of Android framework
APIs as well as features that are only available through the library APIs. Each Support Library is backward-
compatible to a specific Android API level.
Including the Support Libraries in your Android project is considered a best practice for application developers,
depending on the range of platform versions your app is targeting and the APIs that it uses.
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.
v4 Support Library
1
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.
v8 Support Library
3
This library is designed to be used with Android (API level 8) and higher.
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.
TUTORIALS POINT
Simply Easy Learning
DOWNLOADING THE SUPPORT LIBRARIES
Please note that before installing the support library packages you should be clear that what feature you want to
use in your app.
The Android Support Library package is available through the Android SDK Manager.
Follow the following steps to download the support library package through the SDK Manager.
2. In the SDK Manager window, scroll to the end of the Packages list, find the Extras folder.
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.
CHANGES IN ANDROID.MANIFEST
If you are increasing the backward compatibility of your existing application to an earlier version of the Android API
with the Support Library, make sure to update your application's manifest. Specifically, you should update
the android:minSdkVersion element of the tag in the manifest to the new, lower version number, as shown
below:
TUTORIALS POINT
Simply Easy Learning
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="17" />
This change tells Google Playstore app that your application can be installed on devices with Android 2.1 (API
level 7) and higher.
API VERSION
Please note that if you are including the v4 support and v7 support libraries in your application, you should specify
a minimum SDK version of "7" (and not "4"). The highest support library level you include in your application
determines the lowest API version in which it can operate.
TUTORIALS POINT
Simply Easy Learning
CHAPTER
70
Android Testing
T he 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.
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.
TUTORIALS POINT
Simply Easy Learning
Testing Tools in android
There are many tools that can be used for testing android applications. Some are official like Junit,Monkey and
some are third party tools that can be used to test android applications. In this chapter we are going to explain
these two tools to test android applications.
1. JUnit
2. Monkey
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:
TUTORIALS POINT
Simply Easy Learning
fValue1= 2.0;
fValue2= 3.0;
}
}
For each test implement a method which interacts with the fixture. Verify the expected results with assertions
specified by calling assertTrue(String, boolean) with a boolean.
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.
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 naviagte to the following directory.
android->sdk->platform-tools
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 inteface on the device that translates our commands to system commands.
monkey - monkey is the testing tool.
v - v stands for verbose method.
100- it is the frequency conut or the number of events to be sent for testing.
TUTORIALS POINT
Simply Easy Learning
This is also shown in the figure:
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.
First run the example code given in the example section in your device. After running , follow the steps of monkey
usage and finally type this command.
This has also been shown in the figure below. By typing this command , you are actually generating 500 random
events for testing.
Example
The below example demonstrates the use of Testing. It crates a basic application which can be used for monkey.
TUTORIALS POINT
Simply Easy Learning
To experiment with this example , you need to run this on an actual device and then follow the monkey steps
explained in the beginning.
Steps Description
You will use Eclipse IDE to create an Android application and name it as Test under a package
1 com.example.test. While creating this project, make sure you Target SDK and Compile With at the latest
version of Android SDK to use higher levels of APIs.
3 Modify layout XML file res/layout/activity_main.xml add any GUI component if required.
5 Modify layout XML file res/layout/activity_main_activity2.xml add any GUI component if required.
Run the application and choose a running android device and install the application on it and verify the
7
results.
package com.example.test;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
package com.example.test;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
TUTORIALS POINT
Simply Easy Learning
import android.view.Menu;
import android.view.View;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity2);
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="87dp"
android:text="@string/test1"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:onClick="activity2"
android:text="@string/go2" />
</RelativeLayout>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
TUTORIALS POINT
Simply Easy Learning
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=".MainActivity2" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="125dp"
android:text="@string/test2"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:onClick="activity1"
android:text="@string/go1" />
</RelativeLayout>
<string name="app_name">test</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="test1">This is activity 1</string>
<string name="test2">This is activity 2</string>
<string name="go1">Go to activity 1</string>
<string name="go2">Go to activity 2</string>
<string name="title_activity_main_activity2">MainActivity2</string>
</resources>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="14" />
<application
android:allowBackup="true"
TUTORIALS POINT
Simply Easy Learning
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.test.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
Let's try to run your Anroid Testing 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, Eclipse will display following window to select an option where
you want to run your Android application.
TUTORIALS POINT
Simply Easy Learning
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 peform testing on this
application.
TUTORIALS POINT
Simply Easy Learning
CHAPTER
71
Android Text to Speech
A ndroid allows you convert your text into voice. Not only you can convert it but it also allows you to speak
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 initListnere. Its syntax is given below:
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 availaible 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:
TUTORIALS POINT
Simply Easy Learning
ttobj.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
Apart from the speak method, there are some other methods availaible in the TextToSpeech class. They are listed
below:
getLanguage()
2
This method returns a Locale instance describing the language.
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.
Steps Description
You will use Eclipse IDE to create an Android application and name it as TextToSpeech under a package
1 com.example.texttospeech. While creating this project, make sure you Target SDK and Compile With at
the latest version of Android SDK to use higher levels of APIs.
3 Modify layout XML file res/layout/activity_main.xml add any GUI component if required.
Run the application and choose a running android device and install the application on it and verify the
5
results.
package com.example.texttospeech;
import java.util.Locale;
import java.util.Random;
import android.app.Activity;
TUTORIALS POINT
Simply Easy Learning
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
TextToSpeech ttobj;
private EditText write;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
write = (EditText)findViewById(R.id.editText1);
ttobj=new TextToSpeech(getApplicationContext(),
new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR){
ttobj.setLanguage(Locale.UK);
}
}
});
}
@Override
public void onPause(){
if(ttobj !=null){
ttobj.stop();
ttobj.shutdown();
}
super.onPause();
}
@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;
}
public void speakText(View view){
String toSpeak = write.getText().toString();
Toast.makeText(getApplicationContext(), toSpeak,
Toast.LENGTH_SHORT).show();
ttobj.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
}
}
<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" >
TUTORIALS POINT
Simply Easy Learning
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="188dp"
android:layout_marginRight="67dp"
android:onClick="speakText"
android:text="@string/text1" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/button1"
android:layout_centerHorizontal="true"
android:layout_marginBottom="81dp"
android:ems="10" >
<requestFocus />
</EditText>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="@string/write"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
TUTORIALS POINT
Simply Easy Learning
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.texttospeech.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
Let's try to run your TextToSpeech 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, Eclipse 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.
TUTORIALS POINT
Simply Easy Learning
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:
TUTORIALS POINT
Simply Easy Learning
Now type something else and repeat the step again with different locale. You will again hear sound. This is shown
below:
TUTORIALS POINT
Simply Easy Learning
TUTORIALS POINT
Simply Easy Learning
CHAPTER
72
Android TextureView
I f you want to display a live video stream or any content stream such as video or an OpenGL scene, you can
In order to use TextureView, all you need to do is get its SurfaceTexture.The SurfaceTexture can then be used to
render content. In order to do this, you just need to do instantiate an object of this class and implement
SurfaceTextureListener interface. Its syntax is given below:
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);
myTexture.setRotation(90.0f);
Apart from these methods, there are other methods availaible in TextureView class. They are listed below:
TUTORIALS POINT
Simply Easy Learning
Sr.No Method & description
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.
Steps Description
You will use Eclipse IDE to create an Android application and name it as TextureView under a package
1 com.example.textureview. While creating this project, make sure you Target SDK and Compile With at
the latest version of Android SDK to use higher levels of APIs.
3 Modify layout XML file res/layout/activity_main.xml add any GUI component if required.
Run the application and choose a running android device and install the application on it and verify the
5
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;
TUTORIALS POINT
Simply Easy Learning
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);
myTexture = new TextureView(this);
myTexture.setSurfaceTextureListener(this);
setContentView(myTexture);
}
@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;
}
@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
}
}
TUTORIALS POINT
Simply Easy Learning
Here is the content of activity_main.xml
<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-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<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" />
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 Eclipse, open one of your project's activity files and click Run icon from the
toolbar. Before starting your application, Eclipse will display following window to select an option where you want to
run your Android application.
TUTORIALS POINT
Simply Easy Learning
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.
TUTORIALS POINT
Simply Easy Learning
This screen has alpha property set to 1.5 and rotation set to 45.
TUTORIALS POINT
Simply Easy Learning
This screen has alpha property set to 1.0 and rotation set to 90.
TUTORIALS POINT
Simply Easy Learning
TUTORIALS POINT
Simply Easy Learning
CHAPTER
73
Android Twitter Integration
A ndroid allows your application to connect to twitter and share data or any kind of updates on twitter.
There are two ways through which you can integrate twitter and share something from your application. These
ways are listed below:
2. Intent Share
TUTORIALS POINT
Simply Easy Learning
Now under setttings tab, change the access to read,write and access messages and save the settings. It is shown
below:
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:
TUTORIALS POINT
Simply Easy Learning
DOWNLOADING SDK AND INTEGRATING IT
Download twitter sdk here. Copy the twitter4J jar into your project libs folder.
In order to update the status , you can call updateStatus() method. Its syntax is given below:
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:
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:
TUTORIALS POINT
Simply Easy Learning
Sr.No Method & description
addCategory(String category)
1
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
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.
Steps Description
You will use Eclipse IDE to create an Android application and name it as IntentShare under a package
1 com.example.intentshare. While creating this project, make sure you Target SDK and Compile With at
the latest version of Android SDK to use higher levels of APIs.
Run the application and choose a running android device and install the application on it and verify the
5
results
package com.example.intentshare;
import java.io.File;
import java.io.FileOutputStream;
import com.example.intentshare.R;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
TUTORIALS POINT
Simply Easy Learning
import android.widget.Toast;
@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;
}
public void open(View view){
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, "Hello, from tutorialspoint");
startActivity(Intent.createChooser(shareIntent, "Share your thoughts"));
<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" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="98dp"
android:layout_marginTop="139dp"
android:onClick="open"
android:src="@drawable/tp" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="48dp"
TUTORIALS POINT
Simply Easy Learning
android:text="@string/tap"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
<string name="app_name">IntentShare</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="tap">Tap the button to share something</string>
</resources>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.intentshare.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
Let's try to run your IntentShare 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, Eclipse will display following window to select an option where you want to
run your Android application.
TUTORIALS POINT
Simply Easy Learning
Select your mobile device as an option and then check your mobile device which will display your default screen:
TUTORIALS POINT
Simply Easy Learning
Now just tap on the image logo and you will see a list of share providers.
TUTORIALS POINT
Simply Easy Learning
Now just select twitter from that list and then write any message. It is shown in the image below:
TUTORIALS POINT
Simply Easy Learning
Now just select the tweet button and then it would be post on your twitter page. It is shown below:
TUTORIALS POINT
Simply Easy Learning
CHAPTER
74
Android UI Design
I n this chapter we will look at the different UI components of android screen. This chapter also covers the tips
UI screen components
A typical user interface of an android application consists of action bar and the application content area.
2. View Control
3. Content Area
TUTORIALS POINT
Simply Easy Learning
Understanding Screen Components
The basic unit of android application is the activity. A UI is defined in an xml file. During compilation, each element
in the XML is compiled into equivalent Android GUI class with attributes represented by methods.
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
TUTORIALS POINT
Simply Easy Learning
LINEARLAYOUT
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.
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” >
<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”
TUTORIALS POINT
Simply Easy Learning
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.
Apart form these attributes, there are other attributes that are common in all views and ViewGroups. They are
listed below:
layout_width
1
Specifies the width of the View or ViewGroup
layout_height
2
Specifies the height of the View or ViewGroup
layout_marginTop
3
Specifies extra space on the top side of the View or ViewGroup
layout_marginBottom
4
Specifies extra space on the bottom side of the View or ViewGroup
layout_marginLeft
5
Specifies extra space on the left side of the View or ViewGroup
layout_marginRight
6
Specifies extra space on the right side of the View or ViewGroup
layout_gravity
7
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
Units of Measurement
When you are specifying the size of an element on an Android UI, you should remember the following units of
measurement.
TUTORIALS POINT
Simply Easy Learning
dp
1
Density-independent pixel. 1 dp is equivalent to one pixel on a 160 dpi screen.
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.
px
4
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.
TUTORIALS POINT
Simply Easy Learning
CHAPTER
75
Android UI Patterns
I n this chapter we will look at the different UI Patterns which are avilable by android to design apps that
UI Patterns components
A good android application should follow following UI patterns:
1. Action Bar
3. Settings
4. Help
5. Selection
Action Bar
The action bar is a dedicated bar at the top of each screen that is generally persistent througout the app. It
provides you several key function which are as following:
TUTORIALS POINT
Simply Easy Learning
These components name and functionality is disussed below :
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.
Action buttons
3
Show the most important actions of your app in the actions section.
Action overflow
4
Move less often used actions to the action overflow.
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:
TUTORIALS POINT
Simply Easy Learning
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
PLACEMENT OF SETTINGS
It is preffered by the android developers to always make "settings" option part of action overfolw 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).
TUTORIALS POINT
Simply Easy Learning
From the CAB bar user can perform following actions:
Trigger an action from the CAB that applies to all highlighted data items
Dismiss the CAB via the navigation bar's Back button or the CAB's checkmark button
TUTORIALS POINT
Simply Easy Learning
CHAPTER
76
Android UI Testing
A ndroid SDK provides the following tools to support automated, functional UI testing on your application.
1. uiautomatorviewer
2. uiautomator
uiautomatorviewer
A GUI tool to scan and analyze the UI components of an Android application.
The uiautomatorviewer tool provides a convenient visual interface to inspect the layout hierarchy and view the
properties of the individual UI components that are displayed on the test device. Using this information, you can
later create uiautomator tests with selector objects that target specific UI components to test.
To analyze the UI components of the application that you want to test, pefrom the following steps after installing
the application given in the example.
uiautomatorviewer
You will see the following window appear. It is the default window of the UI Automator Viewer.
TUTORIALS POINT
Simply Easy Learning
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.
TUTORIALS POINT
Simply Easy Learning
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 parition.
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 parition , its details are shown. Since this button is clickable, thats why its
property of clickable is set to true.
TUTORIALS POINT
Simply Easy Learning
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 screenshot. It is shown in the figure below:
TUTORIALS POINT
Simply Easy Learning
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 peform the following steps:
1. From the Project Explorer, right-click on the new project that you created, then select Properties > Java Build
Path, and do the following:
2. Click Add Library > JUnit then select JUnit3 to add JUnit support.
3. 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.
4. Extend your class with UiAutomatorTestCase
5. Right the necessary test cases.
6. Once you have coded your test, follow these steps to build and deploy your test JAR to your target Android
test device.
7. 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:
The is the name of the project that contains your uiautomator test source files, and the is the path to the
corresponding project directory.
set ANDROID_HOME=<path_to_your_sdk>
9. Go to the project directory where your build.xml file is located and build your test JAR.
ant build
10. Deploy your generated test JAR file to the test device by using the adb push command.
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.
Steps Description
You will use Eclipse IDE to create an Android application and name it as Test under a package
1 com.example.test. While creating this project, make sure you Target SDK and Compile With at the latest
version of Android SDK to use higher levels of APIs.
TUTORIALS POINT
Simply Easy Learning
3 Modify layout XML file res/layout/activity_main.xml add any GUI component if required.
5 Modify layout XML file res/layout/activity_main_activity2.xml add any GUI component if required.
Run the application and choose a running android device and install the application on it and verify the
7
results.
package com.example.test;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
package com.example.test;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity2);
}
TUTORIALS POINT
Simply Easy Learning
public void activity1(View view){
Intent intent = new Intent(this,com.example.test.MainActivity.class);
startActivity(intent);
}
@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_activity2, menu);
return true;
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="87dp"
android:text="@string/test1"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:onClick="activity2"
android:text="@string/go2" />
</RelativeLayout>
<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=".MainActivity2" >
<TextView
android:id="@+id/textView1"
TUTORIALS POINT
Simply Easy Learning
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="125dp"
android:text="@string/test2"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:onClick="activity1"
android:text="@string/go1" />
</RelativeLayout>
<string name="app_name">test</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="test1">This is activity 1</string>
<string name="test2">This is activity 2</string>
<string name="go1">Go to activity 1</string>
<string name="go2">Go to activity 2</string>
<string name="title_activity_main_activity2">MainActivity2</string>
</resources>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="14" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.test.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
TUTORIALS POINT
Simply Easy Learning
<activity
android:name="com.example.test.MainActivity2"
android:label="@string/title_activity_main_activity2" >
</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 Eclipse, open one of your project's activity files and click Run icon from
the toolbar. Before starting your application, Eclipse 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 uiautomatorviewer section in order to peform uitesting
on this application.
TUTORIALS POINT
Simply Easy Learning
CHAPTER
77
Android WebView Layout
W ebView is a view that display web pages inside your application. You can also specify HTML string
and can show it inside your application using WebView. WebView makes turns your application to a web
application.
In order to add WebView to your application , you have to add <WebView> element to your xml layout file. Its
syntax is as follows:
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
In order to use it, you have to get a refrence 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("http://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:
canGoBack()
1
This method specify that wether the WebView has a back history item.
canGoForward()
2
This method specify that wether the WebView has a forward history item.
clearHistory()
3
This method will clear the WebView forwad and backward history.
destroy()
4
This method destory the internal state of WebView.
TUTORIALS POINT
Simply Easy Learning
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 intenet is running.
Steps Description
You will use Eclipse IDE to create an Android application and name it as WebView under a package
1 com.example.webview. While creating this project, make sure you Target SDK and Compile With at the
latest version of Android SDK to use higher levels of APIs.
Run the application and choose a running android device and install the application on it and verify the
6
results.
package com.example.webview;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.webkit.WebSettings;
TUTORIALS POINT
Simply Easy Learning
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.TextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
field = (EditText)findViewById(R.id.urlField);
browser = (WebView)findViewById(R.id.webView1);
browser.setWebViewClient(new MyBrowser());
}
}
private class MyBrowser extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
@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;
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
TUTORIALS POINT
Simply Easy Learning
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<EditText
android:id="@+id/urlField"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/textView1"
android:layout_centerHorizontal="true"
android:ems="10" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/urlField"
android:layout_centerHorizontal="true"
android:onClick="open"
android:text="@string/browse" />
<WebView
android:id="@+id/webView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_alignParentBottom="true"
android:layout_below="@+id/button1" />
</RelativeLayout>
<string name="app_name">WebView</string>
<string name="action_settings">Settings</string>
<string name="hello_world">URL:</string>
<string name="browse">Browse</string>
</resources>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
TUTORIALS POINT
Simply Easy Learning
<activity
android:name="com.example.webview.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
Let's try to run your WebView 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, Eclipse 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 your default screen:
TUTORIALS POINT
Simply Easy Learning
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:
TUTORIALS POINT
Simply Easy Learning
Note. By just changing the url in the url field , your WebView will open your desired website.
TUTORIALS POINT
Simply Easy Learning
CHAPTER
78
Android Wi-Fi
A ndroid allows applications to access to view the access the state of the wirless connections at very low
level. Application can access almost all the information of a wifi connection.
The information that an application can access includes connected network's link speed,IP address, negotiation
state, other networks information. Applications can also scan, add, save, terminate and initiate Wi-Fi connections.
Android provides WifiManager API to manage all aspects of WIFI connectivity. We can instantiate this class by
calling getSystemService method. Its syntax is given below:
WifiManager mainWifiObj;
mainWifiObj = (WifiManager) getSystemService(Context.WIFI_SERVICE);
In order to scan a list of wireless networks, you also need to register your BroadcastReceiver. It can be registered
using registerReceiver method with argument of your reciever class object. Its sytanx 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:
addNetwork(WifiConfiguration config)
1
This method add a new network description to the set of configured networks.
createWifiLock(String tag)
2
This method creates a new WifiLock.
TUTORIALS POINT
Simply Easy Learning
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 scans a list of wirless
networks and populate them in a list view.
To experiment with this example , you need to run this on an actual device on which wifi is turned on.
Steps Description
You will use Eclipse IDE to create an Android application and name it as WIFI under a package
1 com.example.wifi. While creating this project, make sure you Target SDK and Compile With at the latest
version of Android SDK to use higher levels of APIs.
Run the application and choose a running android device and install the application on it and verify the
5
results.
package com.example.wifi;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
TUTORIALS POINT
Simply Easy Learning
import android.widget.Toast;
WifiManager mainWifiObj;
WifiScanReceiver wifiReciever;
ListView list;
String wifis[];
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView)findViewById(R.id.listView1);
mainWifiObj = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifiReciever = new WifiScanReceiver();
mainWifiObj.startScan();
}
list.setAdapter(new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_list_item_1,wifis));
}
}
<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" >
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
TUTORIALS POINT
Simply Easy Learning
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:drawSelectorOnTop="false"
android:background="@android:color/background_dark"
android:listSelector="@android:color/darker_gray" >
</ListView>
</RelativeLayout>
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.wifi.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
Let's try to run your WIFI 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, Eclipse will display following window to select an option where you want to
run your Android application.
TUTORIALS POINT
Simply Easy Learning
Select your mobile device as an option and then check your mobile device which will display your mobile screen
filled with wireless networks around you. It is shown below:
TUTORIALS POINT
Simply Easy Learning
Note the information that has been returned to you. It contains much information about each of the wireless
network detected.
TUTORIALS POINT
Simply Easy Learning
CHAPTER
79
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 homescreen in order to quickly access
them. You have probably seen some common widgets , such as music widget , weather widget , clock widget e.t.c
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>
TUTORIALS POINT
Simply Easy Learning
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.activity_main);
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:
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.
Example
Here is an example demonstrating the use of appliction Widget. It creates a basic widget applications that will open
this current website in the browser.
To experiment with this example , you need to run this on an actual device on which intenet is running.
Steps Description
You will use Eclipse IDE to create an Android application and name it as Widget under a package
1 com.example.widget. While creating this project, make sure you Target SDK and Compile With at the
latest version of Android SDK to use higher levels of APIs.
4 Create a new folder and xml file under res/xml/mywidget.xml to add respective XML components
TUTORIALS POINT
Simply Easy Learning
6 Modify the AndroidManifest.xml to add the necessary permissions
Run the application and choose a running android device and install the application on it and verify the
7
results.
package com.example.widget;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.webkit.WebView.FindListener;
import android.widget.Button;
import android.widget.RemoteViews;
import android.widget.Toast;
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
for(int i=0; i<appWidgetIds.length; i++){
int currentWidgetId = appWidgetIds[i];
String url = "http://www.tutorialspoint.com";
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setData(Uri.parse(url));
PendingIntent pending = PendingIntent.getActivity(context, 0,
intent, 0);
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.activity_main);
views.setOnClickPendingIntent(R.id.button1, pending);
appWidgetManager.updateAppWidget(currentWidgetId,views);
Toast.makeText(context, "widget added", Toast.LENGTH_SHORT).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:gravity="top"
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" >
TUTORIALS POINT
Simply Easy Learning
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="@string/website"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginLeft="18dp"
android:text="@string/app_name" />
</RelativeLayout>
<string name="app_name">Widget</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="website">TutorialsPoint.com</string>
</resources>
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
TUTORIALS POINT
Simply Easy Learning
android:theme="@style/AppTheme" >
<receiver android:name="MainActivity" >
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data android:name="android.appwidget.provider"
android:resource="@xml/mywidget" />
</receiver>
</application>
</manifest>
Let's try to run your Widget 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, Eclipse 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 your default screen:
Go to your widget section and add your created widget to the dsktop or homescreen. It would look something like
this:
TUTORIALS POINT
Simply Easy Learning
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:
TUTORIALS POINT
Simply Easy Learning
Note. By just changing the url in the java file , your widget will open your desired website in the browser.
TUTORIALS POINT
Simply Easy Learning
CHAPTER
80
Android XML Parsers
X ML stands for Extensible Markup Language.XML is a very popular format and commonly used for
sharing data on the internet. This chapter explains how to parse the XML file and extract necessary information
from it.
Android provides three types of XML parsers which are DOM,SAX and XMLPullParser. Among all of them
android recommend XMLPullParser because it is efficent and easy to use. So we are going to use XMLPullParser
for parsing XML
The first step is to identify the fields in the XML data in which you are interested in. For example. In the XML given
below we interested in getting temperature only.
<?xml version="1.0"?>
<current>
<city id="2643743" name="London">
<coord lon="-0.12574" lat="51.50853"/>
<country>GB</country>
<sun rise="2013-10-08T06:13:56" set="2013-10-08T17:21:45"/>
</city>
<temperature value="289.54" min="289.15" max="290.15" unit="kelvin"/>
<humidity value="77" unit="%"/>
<pressure value="1025" unit="hPa"/>
</country>
XML - Elements
An xml file consist of many components. Here is the table defining the compoents of an XML file and their
description.
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.
TUTORIALS POINT
Simply Easy Learning
Attributes
4
Attributes are the additional properties of a tag such as value e.t.c
XML - Parsing
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 seperate function for parsing each of the component of XML file. Its syntax is given below:
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 methodgetAttributeValue 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:
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.
TUTORIALS POINT
Simply Easy Learning
getLineNumber()
5
Returns the current line number, starting from 1.
getNamespace()
6
This method rReturns the namespace 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.
Example
Here is an example demonstrating the use of XMLPullParser class. It creates a basic Weather application that
allows you to parse XML from google weather api and show the result.
To experiment with this example , you can run this on an actual device or in an emulator.
Steps Description
You will use Eclipse IDE to create an Android application and name it as XMLParser under a package
1 com.example.xmlparser. While creating this project, make sure you Target SDK and Compile With at the
latest version of Android SDK to use higher levels of APIs.
5 Create a new java file under src/HandleXML.java to fetch and parse XML data
Run the application and choose a running android device and install the application on it and verify the
7
results
package com.example.xmlparser;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
TUTORIALS POINT
Simply Easy Learning
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
@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;
}
package com.example.xmlparser;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
TUTORIALS POINT
Simply Easy Learning
import org.apache.http.util.EntityUtils;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
case XmlPullParser.END_TAG:
if(name.equals("country")){
country = text;
}
else if(name.equals("humidity")){
humidity =
myParser.getAttributeValue(null,"value");
}
else if(name.equals("pressure")){
pressure =
myParser.getAttributeValue(null,"value");
TUTORIALS POINT
Simply Easy Learning
}
else if(name.equals("temperature")){
temperature =
myParser.getAttributeValue(null,"value");
}
else{
}
break;
}
event = myParser.next();
}
parsingComplete = false;
} catch (Exception e) {
e.printStackTrace();
}
}
public void fetchXML(){
Thread thread = new Thread(new Runnable(){
@Override
public void run() {
try {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection)
url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
InputStream stream = conn.getInputStream();
xmlFactoryObject = XmlPullParserFactory.newInstance();
XmlPullParser myparser =
xmlFactoryObject.newPullParser();
myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES
, false);
myparser.setInput(stream, null);
parseXMLAndStoreIt(myparser);
stream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
}
<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"
TUTORIALS POINT
Simply Easy Learning
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="15dp"
android:text="@string/location"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/textView1"
android:layout_alignParentRight="true"
android:ems="10" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginTop="68dp"
android:text="@string/country"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView2"
android:layout_marginTop="19dp"
android:text="@string/temperature"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView3"
android:layout_below="@+id/textView3"
android:layout_marginTop="32dp"
android:text="@string/humidity"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView4"
android:layout_below="@+id/textView4"
android:layout_marginTop="21dp"
android:text="@string/pressure"
android:textAppearance="?android:attr/textAppearanceSmall" />
TUTORIALS POINT
Simply Easy Learning
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/textView3"
android:layout_toRightOf="@+id/textView3"
android:ems="10" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/editText3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView3"
android:layout_alignBottom="@+id/textView3"
android:layout_alignLeft="@+id/editText2"
android:ems="10" />
<EditText
android:id="@+id/editText4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/textView5"
android:layout_alignLeft="@+id/editText1"
android:ems="10" />
<EditText
android:id="@+id/editText5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView5"
android:layout_alignBottom="@+id/textView5"
android:layout_alignRight="@+id/editText4"
android:ems="10" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText2"
android:layout_below="@+id/editText1"
android:onClick="open"
android:text="@string/weather" />
</RelativeLayout>
<string name="app_name">XMLParser</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="location">Location</string>
<string name="country">Country:</string>
<string name="temperature">Temperature:</string>
<string name="humidity">Humidity:</string>
TUTORIALS POINT
Simply Easy Learning
<string name="pressure">Pressure:</string>
<string name="weather">Weather</string>
</resources>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.xmlparser.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
Let's try to run our XMLParser application we just modified. I assume you had created your AVD while doing
environment setup. To run the app from Eclipse, open one of your project's activity files and click Run icon from
the toolbar. Eclipse 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:
TUTORIALS POINT
Simply Easy Learning
Now what you need to do is to enter any location in the location field. For example , i have entered London. Press
the weather button , when you enter the location. The following screen would appear in you AVD:
TUTORIALS POINT
Simply Easy Learning
Now when you press the weather button, the application will contact the Google Weather API and will request for
your necessary XML location file and will parse it. In case of London following file would be returned:
TUTORIALS POINT
Simply Easy Learning
Note that this temperature is in kelvin, so if you want to convert it into more understandble format , you have to
convert it into Celcius.
TUTORIALS POINT
Simply Easy Learning