Android – Loading Spinner

Android – Loading Spinner ”; Previous Next You can show progress of a task in android through loading progress bar. The progress bar comes in two shapes. Loading bar and Loading Spinner. In this chapter we will discuss spinner. Spinner is used to display progress of those tasks whose total time of completion is unknown. In order to use that, you just need to define it in the xml like this. <ProgressBar android:id=”@+id/progressBar1″ style=”?android:attr/progressBarStyleLarge” android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:layout_centerHorizontal=”true” /> After defining it in xml, you have to get its reference in java file through ProgressBar class. Its syntax is given below − private ProgressBar spinner; spinner = (ProgressBar)findViewById(R.id.progressBar1); After that you can make its disappear , and bring it back when needed through setVisibility Method. Its syntax is given below − spinner.setVisibility(View.GONE); spinner.setVisibility(View.VISIBLE); Apart from these Methods, there are other methods defined in the ProgressBar class , that you can use to handle spinner more effectively. Sr.No Method & description 1 isIndeterminate() Indicate whether this progress bar is in indeterminate mode 2 postInvalidate() Cause an invalidate to happen on a subsequent cycle through the event loop 3 setIndeterminate(boolean indeterminate) Change the indeterminate mode for this progress bar 4 invalidateDrawable(Drawable dr) Invalidates the specified Drawable 5 incrementSecondaryProgressBy(int diff) Increase the progress bar”s secondary progress by the specified amount 6 getProgressDrawable() 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 1 You will use Android studio to create an Android application under a package com.example.sairamkrishna.myapplication. 2 Modify src/MainActivity.java file to add necessary code. 3 Modify the res/layout/activity_main to add respective XML components 4 Need to create a xml file in drawable folder.it contains shape and rotate information about the progress bar 5 Run the application and choose a running android device and install the application on it and verify the results Following is the content of the modified main activity file src/MainActivity.java. package com.example.sairamkrishna.myapplication; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; public class MainActivity extends Activity { Button b1; private ProgressBar spinner; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); b1=(Button)findViewById(R.id.button); spinner=(ProgressBar)findViewById(R.id.progressBar); spinner.setVisibility(View.GONE); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { spinner.setVisibility(View.VISIBLE); } }); } } Following is the modified content of the xml res/layout/activity_main.xml. In the following code abc indicates the logo of tutorialspoint.com <?xml version=”1.0″ encoding=”utf-8″?> <RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android” xmlns:tools=”http://schemas.android.com/tools” android:layout_width=”match_parent” android:layout_height=”match_parent” android:paddingLeft=”@dimen/activity_horizontal_margin” android:paddingRight=”@dimen/activity_horizontal_margin” android:paddingTop=”@dimen/activity_vertical_margin” android:paddingBottom=”@dimen/activity_vertical_margin” tools:context=”.MainActivity”> <TextView android:text=”Progress Dialog” android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/textview” android:textSize=”35dp” android:layout_alignParentTop=”true” android:layout_centerHorizontal=”true” /> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Tutorials point” android:id=”@+id/textView” android:layout_below=”@+id/textview” android:layout_centerHorizontal=”true” android:textColor=”#ff7aff24″ android:textSize=”35dp” /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”download” android:id=”@+id/button” android:layout_below=”@+id/imageView” android:layout_centerHorizontal=”true” /> <ImageView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/imageView” android:src=”@drawable/abc” android:layout_below=”@+id/textView” android:layout_centerHorizontal=”true” /> <ProgressBar style=”?android:attr/progressBarStyleLarge” android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/progressBar” android:progressDrawable=”@drawable/circular_progress_bar” android:layout_below=”@+id/button” android:layout_alignRight=”@+id/textView” android:layout_alignEnd=”@+id/textView” android:layout_alignLeft=”@+id/textview” android:layout_alignStart=”@+id/textview” android:layout_alignParentBottom=”true” /> </RelativeLayout> Following is the content of the res/drawable/circular_progress_bar.xml. <?xml version=”1.0″ encoding=”utf-8″?> <rotate xmlns:android=”http://schemas.android.com/apk/res/android” android:fromDegrees=”90″ android:pivotX=”50%” android:pivotY=”50%” android:toDegrees=”360″> <shape android:innerRadiusRatio=”3″ android:shape=”ring” android:thicknessRatio=”7.0″> <gradient android:centerColor=”#007DD6″ android:endColor=”#007DD6″ android:startColor=”#007DD6″ android:angle=”0″ android:type=”sweep” android:useLevel=”false” /> </shape> </rotate> Following is the content of AndroidManifest.xml file. <?xml version=”1.0″ encoding=”utf-8″?> <manifest xmlns:android=”http://schemas.android.com/apk/res/android” package=”com.example.sairamkrishna.myapplication” > <application android:allowBackup=”true” android:icon=”@drawable/ic_launcher” android:label=”@string/app_name” android:theme=”@style/AppTheme” > <activity android:name=”com.example.sairamkrishna.myapplication.MainActivity” android:label=”@string/app_name” > <intent-filter> <action android:name=”android.intent.action.MAIN” /> <category android:name=”android.intent.category.LAUNCHER” /> </intent-filter> </activity> </application> </manifest> Let”s try to run our application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project”s activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window − Now click on the load spinner button to turn on the loading spinner. It is shown in the image below − Print Page Previous Next Advertisements ”;

Android – Styles and Themes

Android – Styles and Themes ”; Previous Next A style resource defines the format and look for a UI. A style can be applied to an individual View (from within a layout file) or to an entire Activity or application (from within the manifest file). Defining Styles A style is defined in an XML resource that is separate from the XML that specifies the layout. This XML file resides under res/values/ directory of your project and will have <resources> as the root node which is mandatory for the style file. The name of the XML file is arbitrary, but it must use the .xml extension. You can define multiple styles per file using <style> tag but each style will have its name that uniquely identifies the style. Android style attributes are set using <item> tag as shown below − <?xml version=”1.0″ encoding=”utf-8″?> <resources> <style name=”CustomFontStyle”> <item name=”android:layout_width”>fill_parent</item> <item name=”android:layout_height”>wrap_content</item> <item name=”android:capitalize”>characters</item> <item name=”android:typeface”>monospace</item> <item name=”android:textSize”>12pt</item> <item name=”android:textColor”>#00FF00</item>/> </style> </resources> The value for the <item> can be a keyword string, a hex color, a reference to another resource type, or other value depending on the style property. Using Styles Once your style is defined, you can use it in your XML Layout file using style attribute as follows − <?xml version=”1.0″ encoding=”utf-8″?> <LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android” android:layout_width=”fill_parent” android:layout_height=”fill_parent” android:orientation=”vertical” > <TextView android:id=”@+id/text_id” style=”@style/CustomFontStyle” android:text=”@string/hello_world” /> </LinearLayout> To understand the concept related to Android Style, you can check Style Demo Example. Style Inheritance Android supports style Inheritance in very much similar way as cascading style sheet in web design. You can use this to inherit properties from an existing style and then define only the properties that you want to change or add. To implement a custom theme create or edit MyAndroidApp/res/values/themes.xml and add the following − <resources> … <style name=”MyCustomTheme” parent=”android:style/Theme”> <item name=”android:textColorPrimary”>#ffff0000</item> </style> … </resources> In your AndroidManifest.xml apply the theme to the activities you want to style − <activity android:name=”com.myapp.MyActivity” … android:theme=”@style/MyCustomTheme” /> Your new theme will be applied to your activity, and text is now bright red. Applying Colors to Theme Attributes Your color resource can then be applied to some theme attributes, such as the window background and the primary text color, by adding <item> elements to your custom theme. These attributes are defined in your styles.xml file. For example, to apply the custom color to the window background, add the following two <item> elements to your custom theme, defined in MyAndroidApp/res/values/styles.xml file − <resources> … <style name=”MyCustomTheme” …> <item name=”android:windowBackground”>@color/my_custom_color</item> <item name=”android:colorBackgroundCacheHint”>@color/my_custom_color</item> </style> … </resources> Using a Custom Nine-Patch With Buttons A nine-patch drawable is a special kind of image which can be scaled in width and height while maintaining its visual integrity. Nine-patches are the most common way to specify the appearance of Android buttons, though any drawable type can be used. a Sample of Nine-Patch button Steps to create Nine-Patch Buttons Save this bitmap as /res/drawable/my_nine_patch.9.png Define a new style Apply the new button style to the buttonStyle attribute of your custom theme Define a new Style <resources> … <style name=”MyCustomButton” parent=”android:Widget.Button”> <item name=”android:background”>@drawable/my_nine_patch</item> </style> … </resources> Apply the theme <resources> … <style name=”MyCustomTheme” parent=…> … <item name=”android:buttonStyle”>@style/MyCustomButton</item> </style> … </resources> Android Themes Hope you understood the concept of Style, so now let”s try to understand what is a Theme. A theme is nothing but an Android style applied to an entire Activity or application, rather than an individual View. Thus, when a style is applied as a theme, every View in the Activity or application will apply each style property that it supports. For example, you can apply the same CustomFontStyle style as a theme for an Activity and then all text inside that Activity will have green monospace font. To set a theme for all the activities of your application, open the AndroidManifest.xml file and edit the <application> tag to include the android:theme attribute with the style name. For example − <application android:theme=”@style/CustomFontStyle”> But if you want a theme applied to just one Activity in your application, then add the android:theme attribute to the <activity> tag only. For example − <activity android:theme=”@style/CustomFontStyle”> There are number of default themes defined by Android which you can use directly or inherit them using parent attribute as follows − <style name=”CustomTheme” parent=”android:Theme.Light”> … </style> To understand the concept related to Android Theme, you can check Theme Demo Example. Styling the colour palette The layout design can implementable based on them based colours, for example as following design is designed based on them colour(blue) Above layout has designed based on style.xml file,Which has placed at res/values/ <resource> <style name=”AppTheme” parent=”android:Theme.Material”> <item name =”android:color/primary”>@color/primary</item> <item name =”android:color/primaryDark”>@color/primary_dark</item> <item name =”android:colorAccent/primary”>@color/accent</item> </style> <resource> Default Styles & Themes The Android platform provides a large collection of styles and themes that you can use in your applications. You can find a reference of all available styles in the R.style class. To use the styles listed here, replace all underscores in the style name with a period. For example, you can apply the Theme_NoTitleBar theme with “@android:style/Theme.NoTitleBar”. You can see the following source code for Android styles and themes − Android Styles (styles.xml) Android Themes (themes.xml) Print Page Previous Next Advertisements ”;

Android – Event Handling

Android – Event Handling ”; Previous Next Events are a useful way to collect data about a user”s interaction with interactive components of Applications. Like button presses or screen touch etc. The Android framework maintains an event queue as first-in, first-out (FIFO) basis. You can capture these events in your program and take appropriate action as per requirements. There are following three concepts related to Android Event Management − Event Listeners − An event listener is an interface in the View class that contains a single callback method. These methods will be called by the Android framework when the View to which the listener has been registered is triggered by user interaction with the item in the UI. Event Listeners Registration − Event Registration is the process by which an Event Handler gets registered with an Event Listener so that the handler is called when the Event Listener fires the event. Event Handlers − When an event happens and we have registered an event listener for the event, the event listener calls the Event Handlers, which is the method that actually handles the event. Event Listeners & Event Handlers Event Handler Event Listener & Description onClick() OnClickListener() This is called when the user either clicks or touches or focuses upon any widget like button, text, image etc. You will use onClick() event handler to handle such event. onLongClick() OnLongClickListener() This is called when the user either clicks or touches or focuses upon any widget like button, text, image etc. for one or more seconds. You will use onLongClick() event handler to handle such event. onFocusChange() OnFocusChangeListener() This is called when the widget looses its focus ie. user goes away from the view item. You will use onFocusChange() event handler to handle such event. onKey() OnFocusChangeListener() This is called when the user is focused on the item and presses or releases a hardware key on the device. You will use onKey() event handler to handle such event. onTouch() OnTouchListener() This is called when the user presses the key, releases the key, or any movement gesture on the screen. You will use onTouch() event handler to handle such event. onMenuItemClick() OnMenuItemClickListener() This is called when the user selects a menu item. You will use onMenuItemClick() event handler to handle such event. onCreateContextMenu() onCreateContextMenuItemListener() This is called when the context menu is being built(as the result of a sustained “long click) There are many more event listeners available as a part of View class like OnHoverListener, OnDragListener etc which may be needed for your application. So I recommend to refer official documentation for Android application development in case you are going to develop a sophisticated apps. Event Listeners Registration Event Registration is the process by which an Event Handler gets registered with an Event Listener so that the handler is called when the Event Listener fires the event. Though there are several tricky ways to register your event listener for any event, but I”m going to list down only top 3 ways, out of which you can use any of them based on the situation. Using an Anonymous Inner Class Activity class implements the Listener interface. Using Layout file activity_main.xml to specify event handler directly. Below section will provide you detailed examples on all the three scenarios − Touch Mode Users can interact with their devices by using hardware keys or buttons or touching the screen.Touching the screen puts the device into touch mode. The user can then interact with it by touching the on-screen virtual buttons, images, etc.You can check if the device is in touch mode by calling the View class’s isInTouchMode() method. Focus A view or widget is usually highlighted or displays a flashing cursor when it’s in focus. This indicates that it’s ready to accept input from the user. isFocusable() − it returns true or false isFocusableInTouchMode() − checks to see if the view is focusable in touch mode. (A view may be focusable when using a hardware key but not when the device is in touch mode) android:foucsUp=”@=id/button_l” onTouchEvent() public boolean onTouchEvent(motionEvent event){ switch(event.getAction()){ case TOUCH_DOWN: Toast.makeText(this,”you have clicked down Touch button”,Toast.LENTH_LONG).show(); break(); case TOUCH_UP: Toast.makeText(this,”you have clicked up touch button”,Toast.LENTH_LONG).show(); break; case TOUCH_MOVE: Toast.makeText(this,”you have clicked move touch button”Toast.LENTH_LONG).show(); break; } return super.onTouchEvent(event) ; } Event Handling Examples Event Listeners Registration Using an Anonymous Inner Class Here you will create an anonymous implementation of the listener and will be useful if each class is applied to a single control only and you have advantage to pass arguments to event handler. In this approach event handler methods can access private data of Activity. No reference is needed to call to Activity. But if you applied the handler to more than one control, you would have to cut and paste the code for the handler and if the code for the handler is long, it makes the code harder to maintain. Following are the simple steps to show how we will make use of separate Listener class to register and capture click event. Similar way you can implement your listener for any other required event type. Step Description 1 You will use Android studio IDE to create an Android application and name it as myapplication under a package com.example.myapplication as explained in the Hello World Example chapter. 2 Modify src/MainActivity.java file to add click event listeners and handlers for the two buttons defined. 3 Modify the detault content of res/layout/activity_main.xml file to include Android UI controls. 4 No need to declare default string constants.Android studio takes care default constants. 5 Run the application to launch Android emulator and verify the result of the changes done in the aplication. Following is the content of the modified main activity file src/com.example.myapplication/MainActivity.java. This file can include each of the fundamental lifecycle methods. package com.example.myapplication; import android.app.ProgressDialog; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends ActionBarActivity { private ProgressDialog progress; Button b1,b2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); progress = new

Android – Localization

Android – Localization ”; Previous Next An android application can run on many devices in many different regions. In order to make your application more interactive, your application should handle text,numbers,files e.t.c in ways appropriate to the locales where your application will be used. The way of changing string into different languages is called as localization In this chapter we will explain , how you can localize your application according to different regions e.t.c. We will localize the strings used in the application, and in the same way other things can be localized. Localizing Strings In order to localize the strings used in your application , make a new folder under res with name of values-local where local would be the replaced with the region. For example, in the case of italy, the values-it folder would be made under res. It is shown in the image below − Once that folder is made, copy the strings.xmlfrom default folder to the folder you have created. And change its contents. For example, i have changed the value of hello_world string. Italy, res/values-it/strings.xml <;?xml version=”1.0″ encoding=”utf-8″?> <resources> <string name=”hello_world”>Ciao mondo!</string> </resources> Spanish, res/values-it/strings.xml <;?xml version=”1.0″ encoding=”utf-8″?> <resources> <string name=”hello_world”>Hola Mundo!</string> </resources> French, res/values-it/strings.xml <;?xml version=”1.0″ encoding=”utf-8″?> <resources> <string name=”hello_world”>Bonjour le monde !</string> </resources> Apart from these languages, the region code of other languages have been given in the table below − Sr.No Language & code 1 Afrikanns Code: af. Folder name: values-af 2 Arabic Code: ar. Folder name: values-ar 3 Bengali Code: bn. Folder name: values-bn 4 Czech Code: cs. Folder name: values-cs 5 Chinese Code: zh. Folder name: values-zh 6 German Code: de. Folder name: values-de 7 French Code: fr. Folder name: values-fr 8 Japanese Code: ja. Folder name: values-ja Example To experiment with this example , you can run this on an actual device or in an emulator. Steps Description 1 You will use Android studio to create an Android application under a package com.example.sairamkrishna.myapplication. 2 Modify the res/layout/activity_main to add respective XML components 3 Modify the res/values/string.xml to add necessary string components 4 Run the application and choose a running android device and install the application on it and verify the results Following is the modified content of the xml res/layout/activity_main.xml. <?xml version=”1.0″ encoding=”utf-8″?> <RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android” xmlns:tools=”http://schemas.android.com/tools” android:layout_width=”match_parent” android:layout_height=”match_parent” android:paddingLeft=”@dimen/activity_horizontal_margin” android:paddingRight=”@dimen/activity_horizontal_margin” android:paddingTop=”@dimen/activity_vertical_margin” android:paddingBottom=”@dimen/activity_vertical_margin” tools:context=”.MainActivity”> <TextView android:text=”Wifi” android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/textview” android:textSize=”35dp” android:layout_alignParentTop=”true” android:layout_centerHorizontal=”true” /> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Tutorials point” android:id=”@+id/textView” android:layout_below=”@+id/textview” android:layout_centerHorizontal=”true” android:textColor=”#ff7aff24″ android:textSize=”35dp” /> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”@string/hindi” android:id=”@+id/textView2″ android:layout_below=”@+id/textView” android:layout_centerHorizontal=”true” android:layout_marginTop=”50dp” android:textColor=”#ff59ff1a” android:textSize=”30dp” /> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”@string/marathi” android:id=”@+id/textView3″ android:textSize=”30dp” android:textColor=”#ff67ff1e” android:layout_centerVertical=”true” android:layout_centerHorizontal=”true” /> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”@string/arabic” android:id=”@+id/textView4″ android:layout_below=”@+id/textView3″ android:layout_centerHorizontal=”true” android:layout_marginTop=”42dp” android:textColor=”#ff40ff08″ android:textSize=”30dp” /> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”@string/chinese” android:id=”@+id/textView5″ android:layout_below=”@+id/textView4″ android:layout_alignLeft=”@+id/textView3″ android:layout_alignStart=”@+id/textView3″ android:layout_marginTop=”42dp” android:textSize=”30dp” android:textColor=”#ff56ff12″ android:layout_alignRight=”@+id/textView3″ android:layout_alignEnd=”@+id/textView3″ /> </RelativeLayout> Following is the content of the res/values/string.xml. <resources> <string name=”app_name”>My Application</string> <string name=”hello_world”>Hello world!</string> <string name=”action_settings”>Settings</string> <string name=”hindi”>ట్యుటోరియల్స్ పాయింట్</string> <string name=”marathi”>शिकवण्या बिंदू</string> <string name=”arabic”>نقطة الدروس7</string> <string name=”chinese”>教程点</string> </resources> Let”s try to run our application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project”s activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window − Print Page Previous Next Advertisements ”;

Location Based Services

Android – Location Based Services ”; Previous Next Android location APIs make it easy for you to build location-aware applications, without needing to focus on the details of the underlying location technology. This becomes possible with the help of Google Play services, which facilitates adding location awareness to your app with automated location tracking, geofencing, and activity recognition. This tutorial shows you how to use Location Services in your APP to get the current location, get periodic location updates, look up addresses etc. The Location Object The Location object represents a geographic location which can consist of a latitude, longitude, time stamp, and other information such as bearing, altitude and velocity. There are following important methods which you can use with Location object to get location specific information − Sr.No. Method & Description 1 float distanceTo(Location dest) Returns the approximate distance in meters between this location and the given location. 2 float getAccuracy() Get the estimated accuracy of this location, in meters. 3 double getAltitude() Get the altitude if available, in meters above sea level. 4 float getBearing() Get the bearing, in degrees. 5 double getLatitude() Get the latitude, in degrees. 6 double getLongitude() Get the longitude, in degrees. 7 float getSpeed() Get the speed if it is available, in meters/second over ground. 8 boolean hasAccuracy() True if this location has an accuracy. 9 boolean hasAltitude() True if this location has an altitude. 10 boolean hasBearing() True if this location has a bearing. 11 boolean hasSpeed() True if this location has a speed. 12 void reset() Clears the contents of the location. 13 void setAccuracy(float accuracy) Set the estimated accuracy of this location, meters. 14 void setAltitude(double altitude) Set the altitude, in meters above sea level. 15 void setBearing(float bearing) Set the bearing, in degrees. 16 void setLatitude(double latitude) Set the latitude, in degrees. 17 void setLongitude(double longitude) Set the longitude, in degrees. 18 void setSpeed(float speed) Set the speed, in meters/second over ground. 19 String toString() Returns a string containing a concise, human-readable description of this object. Get the Current Location To get the current location, create a location client which is LocationClient object, connect it to Location Services using connect() method, and then call its getLastLocation() method. This method returns the most recent location in the form of Location object that contains latitude and longitude coordinates and other information as explained above. To have location based functionality in your activity, you will have to implement two interfaces − GooglePlayServicesClient.ConnectionCallbacks GooglePlayServicesClient.OnConnectionFailedListener These interfaces provide following important callback methods, which you need to implement in your activity class − Sr.No. Callback Methods & Description 1 abstract void onConnected(Bundle connectionHint) This callback method is called when location service is connected to the location client successfully. You will use connect() method to connect to the location client. 2 abstract void onDisconnected() This callback method is called when the client is disconnected. You will use disconnect() method to disconnect from the location client. 3 abstract void onConnectionFailed(ConnectionResult result) This callback method is called when there was an error connecting the client to the service. You should create the location client in onCreate() method of your activity class, then connect it in onStart(), so that Location Services maintains the current location while your activity is fully visible. You should disconnect the client in onStop() method, so that when your app is not visible, Location Services is not maintaining the current location. This helps in saving battery power up-to a large extent. Get the Updated Location If you are willing to have location updates, then apart from above mentioned interfaces, you will need to implement LocationListener interface as well. This interface provide following callback method, which you need to implement in your activity class − Sr.No. Callback Method & Description 1 abstract void onLocationChanged(Location location) This callback method is used for receiving notifications from the LocationClient when the location has changed. Location Quality of Service The LocationRequest object is used to request a quality of service (QoS) for location updates from the LocationClient. There are following useful setter methods which you can use to handle QoS. There are equivalent getter methods available which you can check in Android official documentation. Sr.No. Method & Description 1 setExpirationDuration(long millis) Set the duration of this request, in milliseconds. 2 setExpirationTime(long millis) Set the request expiration time, in millisecond since boot. 3 setFastestInterval(long millis) Explicitly set the fastest interval for location updates, in milliseconds. 4 setInterval(long millis) Set the desired interval for active location updates, in milliseconds. 5 setNumUpdates(int numUpdates) Set the number of location updates. 6 setPriority(int priority) Set the priority of the request. Now for example, if your application wants high accuracy location it should create a location request with setPriority(int) set to PRIORITY_HIGH_ACCURACY and setInterval(long) to 5 seconds. You can also use bigger interval and/or other priorities like PRIORITY_LOW_POWER for to request “city” level accuracy or PRIORITY_BALANCED_POWER_ACCURACY for “block” level accuracy. Activities should strongly consider removing all location request when entering the background (for example at onPause()), or at least swap the request to a larger interval and lower quality to save power consumption. Displaying a Location Address Once you have Location object, you can use Geocoder.getFromLocation() method to get an address for a given latitude and longitude. This method is synchronous, and may take a long time to do its work, so you should call the method from the doInBackground() method of an AsyncTask class. The AsyncTask must be subclassed to be used and the subclass will override doInBackground(Params…) method to perform a task in the background and onPostExecute(Result) method is invoked on the UI thread after the background computation finishes and at the time to display the result. There is one more important method available in AyncTask which is execute(Params… params), this method executes the task with the specified parameters. Example Following example shows you in practical how to to use Location Services in your app to get the current location and its equivalent addresses etc. To experiment with this

Android – JetPlayer

Android – JetPlayer ”; Previous Next The Android platform includes a JET engine that lets you add interactive playback of JET audio content in your applications. Android provides JetPlayer class to handle this stuff. In order to Jet Content , you need to use the JetCreator tool that comes with AndroidSDK. The usage of jetCreator has been discussed in the example. In order to play the content created by JetCreator, you need JetPlayer class supported by android. In order to use JetPlayer , you need to instantiate an object of JetPlayer class. Its syntax is given below − JetPlayer jetPlayer = JetPlayer.getJetPlayer(); The next thing you need to do is to call loadJetFile method and pass in the path of your Jet file. After that you have to add this into the Queue of JetPlayer. Its syntax is given below − jetPlayer.loadJetFile(“/sdcard/level1.jet”); byte segmentId = 0; // queue segment 5, repeat once, use General MIDI, transpose by -1 octave jetPlayer.queueJetSegment(5, -1, 1, -1, 0, segmentId++); The method queueJetSegment Queues the specified segment in the JET Queue. The last thing you need to is to call the play method to start playing the music. Its syntax is given below − jetPlayer.play(); Apart from these methods, there are other methods defined in the JetPlayer class. They are defined below − Sr.No Method & description 1 clearQueue() Empties the segment queue, and clears all clips that are scheduled for playback 2 closeJetFile() Closes the resource containing the JET content 3 getJetPlayer() Factory method for the JetPlayer class 4 loadJetFile(String path) Loads a .jet file from a given path 5 pause() Pauses the playback of the JET segment queue 6 release() Stops the current JET playback, and releases all associated native resources Example The following example demonstrates the use of JetCreator tool to create Jet content. Once that content is created, you can play it through JetPlayer. To experiment with this example , you need to run this on an actual device or in an emulator. Steps Description 1 You will use Android studio IDE to create an Android application and name it as JetPlayer under a package com.example.jetplayer. 2 Install Python and WxPython on your computer from internet. 3 Run the jet creator from command prompt 4 Create Jet content and then save it 5 Run the application and verify the results Using JetCreator Installing python The first step that you need while using JetCreator is to install the python. The python can be installed from its official website here or from any where else on the internet. Please keep in mind the version number of the python should either be 2.6 or 2.7 because this example follows that. Once you download python install it. After installing you have to set path to the python. Open your command prompt and type the following command.It is shown in the image below − Once path is set , you can verify it by typing python and hit enter. It is shown below − Installing WxPython The next thing you need to do is to install the wxPython. It can be downloaded here. Once downloaded , you will install it. It will be automatically installed in the python directory. Ruuning JetCreator The next thing you need to is to move to the path where JetCreator is present. It is in the tools,SDK folder of the android. It is shown below − Once in the folder type this command and hit enter. python JetCreator.py It is shown in the figure below − As soon as you hit enter, Jet Creator window will open. It would be something like this. 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 − 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 − JetPlayer jetPlayer = JetPlayer.getJetPlayer(); jetPlayer.loadJetFile(“/sdcard/level1.jet”); byte segmentId = 0; // queue segment 5, repeat once, use General MIDI, transpose by -1 octave jetPlayer.queueJetSegment(5, -1, 1, -1, 0, segmentId++); jetPlayer.play(); Print Page Previous Next Advertisements ”;

Android – Support Library

Android – Support Library ”; Previous Next When you develop an app on a latest version of android like 5.x and you also want it to run on those devices which are running older versions of android like 3.2 e.t.c. you can”t do that until you add backward compatibility to your code. To provide this backward compatibility android provides you the Android Support Library package. The Android Support Library package is a set of code libraries that provide backward-compatible versions of Android framework APIs as well as features that are only available through the library APIs. Each Support Library is backward-compatible to a specific Android API level. Including the Support Libraries in your Android project is considered a best practice for application developers, depending on the range of platform versions your app is targeting and the APIs that it uses. Support Library Features The Android Support Library package contains several libraries that can be included in your application. Each of these libraries supports a specific range of Android platform versions and set of features. In order to effectively use the libraries, it is important to consider that which API level you want to target as each library supports different API level. Following is a brief description of android support libraries and API level they support. Sr.No Version & Features 1 v4 Support Library This library is designed to be used with Android 1.6 (API level 4) and higher. 2 v7 Support Library There are several libraries designed to be used with Android 2.1 (API level 7) and higher. 3 v8 Support Library This library is designed to be used with Android (API level 8) and higher. 4 v13 Support Library This library is designed to be used for Android 3.2 (API level 13) and higher. Please Remember that use of Android Support Library in your app code is encouraged and preferred. By using these libraries you can increase your target market and target audience. Downloading the Support Libraries Please note that before installing the support library packages you should be clear that what feature you want to use in your app. The Android Support Library package is available through the Android SDK Manager. Follow the following steps to download the support library package through the SDK Manager. Start the android SDK Manager. In the SDK Manager window, scroll to the end of the Packages list, find the Extras folder. Select the Android Support Library item. Click the Install packages button. After downloading, the tool installs the Support Library files to your existing Android SDK directory. The library files are located in the following subdirectory of your SDK: /extras/android/support/ directory. Choosing Support Libraries Before adding a Support Library to your application, decide what features you want to include and the lowest Android versions you want to support. Changes in Android build.gradle If you are increasing the backward compatibility of your existing application to an earlier version of the Android API with the Support Library, make sure to update your application”s build.gradle. Specifically, you should update the compileSdkVersion element in the build.gradle to the new, lower version number, as shown below − android { compileSdkVersion 24 buildToolsVersion “24.0.1” defaultConfig { applicationId “com.example.tutorialspoint7.myapplication” minSdkVersion 23 targetSdkVersion 24 versionCode 1 versionName “1.0” } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile(”proguard-android.txt”), ”proguard-rules.pro” } } } This change tells Google Playstore app that your application can be installed on devices with Android minimum version of 23. Print Page Previous Next Advertisements ”;

Android – WebView Layout

Android – WebView ”; Previous Next WebView is a view that display web pages inside your application. You can also specify HTML string and can show it inside your application using WebView. WebView makes turns your application to a web application. In order to add WebView to your application, you have to add <WebView> element to your xml layout file. Its syntax is as follows − <WebView xmlns:android=”http://schemas.android.com/apk/res/android” android:id=”@+id/webview” android:layout_width=”fill_parent” android:layout_height=”fill_parent” /> In order to use it, you have to get a reference of this view in Java file. To get a reference, create an object of the class WebView. Its syntax is − WebView browser = (WebView) findViewById(R.id.webview); In order to load a web url into the WebView, you need to call a method loadUrl(String url) of the WebView class, specifying the required url. Its syntax is: browser.loadUrl(“https://www.tutorialspoint.com”); Apart from just loading url, you can have more control over your WebView by using the methods defined in WebView class. They are listed as follows − Sr.No Method & Description 1 canGoBack() This method specifies the WebView has a back history item. 2 canGoForward() This method specifies the WebView has a forward history item. 3 clearHistory() This method will clear the WebView forward and backward history. 4 destroy() This method destroy the internal state of WebView. 5 findAllAsync(String find) This method find all instances of string and highlight them. 6 getProgress() This method gets the progress of the current page. 7 getTitle() This method return the title of the current page. 8 getUrl() This method return the url of the current page. If you click on any link inside the webpage of the WebView, that page will not be loaded inside your WebView. In order to do that you need to extend your class from WebViewClient and override its method. Its syntax is − private class MyBrowser extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } } Example Here is an example demonstrating the use of WebView Layout. It creates a basic web application that will ask you to specify a url and will load this url website in the WebView. To experiment with this example, you need to run this on an actual device on which internet is running. Steps Description 1 You will use Android studio to create an Android application under a package com.example.sairamkrishna.myapplication. 2 Modify src/MainActivity.java file to add WebView code. 3 Modify the res/layout/activity_main to add respective XML components 4 Modify the AndroidManifest.xml to add the necessary permissions 5 Run the application and choose a running android device and install the application on it and verify the results. Following is the content of the modified main activity file src/MainActivity.java. package com.example.sairamkrishna.myapplication; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.EditText; public class MainActivity extends Activity { Button b1; EditText ed1; private WebView wv1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); b1=(Button)findViewById(R.id.button); ed1=(EditText)findViewById(R.id.editText); wv1=(WebView)findViewById(R.id.webView); wv1.setWebViewClient(new MyBrowser()); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String url = ed1.getText().toString(); wv1.getSettings().setLoadsImagesAutomatically(true); wv1.getSettings().setJavaScriptEnabled(true); wv1.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); wv1.loadUrl(url); } }); } private class MyBrowser extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } } } Following is the modified content of the xml res/layout/activity_main.xml. In the following code abc indicates the logo of tutorialspoint.com <?xml version=”1.0″ encoding=”utf-8″?> <RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android” xmlns:tools=”http://schemas.android.com/tools” android:layout_width=”match_parent” android:layout_height=”match_parent” android:paddingLeft=”@dimen/activity_horizontal_margin” android:paddingRight=”@dimen/activity_horizontal_margin” android:paddingTop=”@dimen/activity_vertical_margin” android:paddingBottom=”@dimen/activity_vertical_margin” tools:context=”.MainActivity”> <TextView android:text=”WebView” android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/textview” android:textSize=”35dp” android:layout_alignParentTop=”true” android:layout_centerHorizontal=”true” /> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Tutorials point” android:id=”@+id/textView” android:layout_below=”@+id/textview” android:layout_centerHorizontal=”true” android:textColor=”#ff7aff24″ android:textSize=”35dp” /> <EditText android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/editText” android:hint=”Enter Text” android:focusable=”true” android:textColorHighlight=”#ff7eff15″ android:textColorHint=”#ffff25e6″ android:layout_marginTop=”46dp” android:layout_below=”@+id/imageView” android:layout_alignParentLeft=”true” android:layout_alignParentStart=”true” android:layout_alignRight=”@+id/imageView” android:layout_alignEnd=”@+id/imageView” /> <ImageView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/imageView” android:src=”@drawable/abc” android:layout_below=”@+id/textView” android:layout_centerHorizontal=”true” /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Enter” android:id=”@+id/button” android:layout_alignTop=”@+id/editText” android:layout_toRightOf=”@+id/imageView” android:layout_toEndOf=”@+id/imageView” /> <WebView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/webView” android:layout_below=”@+id/button” android:layout_alignParentLeft=”true” android:layout_alignParentStart=”true” android:layout_alignParentRight=”true” android:layout_alignParentEnd=”true” android:layout_alignParentBottom=”true” /> </RelativeLayout> Following is the content of the res/values/string.xml. <resources> <string name=”app_name”>My Application</string> </resources> Following is the content of AndroidManifest.xml file. <?xml version=”1.0″ encoding=”utf-8″?> <manifest xmlns:android=”http://schemas.android.com/apk/res/android” package=”com.example.sairamkrishna.myapplication” &gt <uses-permission android:name=”android.permission.INTERNET” /> <application android:allowBackup=”true” android:icon=”@mipmap/ic_launcher” android:label=”@string/app_name” android:theme=”@style/AppTheme” > <activity android:name=”.MainActivity” android:label=”@string/app_name” > <intent-filter> <action android:name=”android.intent.action.MAIN” /> <category android:name=”android.intent.category.LAUNCHER” /> </intent-filter> </activity> </application> </manifest> Let”s try to run your WebView application. To run the app from Android studio, open one of your project”s activity files and click Run icon from the toolbar. Android studio will display as shown below Now just specify a url on the url field and press the browse button that appears,to launch the website. But before that please make sure that you are connected to the internet. After pressing the button, the following screen would appear − Note. By just changing the url in the url field, your WebView will open your desired website. Above image shows webview of tutorialspoint.com Print Page Previous Next Advertisements ”;

Android – Testing

Android – Testing ”; Previous Next The Android framework includes an integrated testing framework that helps you test all aspects of your application and the SDK tools include tools for setting up and running test applications. Whether you are working in Eclipse with ADT or working from the command line, the SDK tools help you set up and run your tests within an emulator or the device you are targeting. Test Structure Android”s build and test tools assume that test projects are organized into a standard structure of tests, test case classes, test packages, and test projects. Testing Tools in android There are many tools that can be used for testing android applications. Some are official like Junit,Monkey and some are third party tools that can be used to test android applications. In this chapter we are going to explain these two tools to test android applications. JUnit Monkey JUnit You can use the JUnit TestCase class to do unit testing on a class that doesn”t call Android APIs. TestCase is also the base class for AndroidTestCase, which you can use to test Android-dependent objects. Besides providing the JUnit framework, AndroidTestCase offers Android-specific setup, teardown, and helper methods. In order to use TestCase, extend your class with TestCase class and implement a method call setUp(). Its syntax is given below − public class MathTest extends TestCase { protected double fValue1; protected double fValue2; protected void setUp() { fValue1= 2.0; fValue2= 3.0; } } For each test implement a method which interacts with the fixture. Verify the expected results with assertions specified by calling assertTrue(String, boolean) with a boolean. public void testAdd() { double result= fValue1 + fValue2; assertTrue(result == 5.0); } The assert methods compare values you expect from a test to the actual results and throw an exception if the comparison fails. Once the methods are defined you can run them. Its syntax is given below − TestCase test= new MathTest(“testAdd”); test.run(); Monkey The UI/Application Exerciser Monkey, usually called “monkey”, is a command-line tool that sends pseudo-random streams of keystrokes, touches, and gestures to a device. You run it with the Android Debug Bridge (adb) tool. You use it to stress-test your application and report back errors that are encountered. You can repeat a stream of events by running the tool each time with the same random number seed. Monkey features Monkey has many features, but it can be all be summed up to these four categories. Basic configuration options Operational constraints Event types and frequencies Debugging options Monkey Usage In order to use monkey, open up a command prompt and just navigate to the following directory. android ->sdk ->platform-tools Once inside the directory, attach your device with the PC , and run the following command. adb shell monkey -p your.package.name -v 500 This command can be broken down into these steps. adb – Android Debug Bridge. A tool used to connect and sends commands to your Android phone from a desktop or laptop computer. shell – shell is just an interface on the device that translates our commands to system commands. monkey – monkey is the testing tool. v – v stands for verbose method. 500- it is the frequency conut or the number of events to be sent for testing. This is also shown in the figure − In the above command, you run the monkey tool on the default android UI application. Now in order to run it to your application , here what you have to do. finally you will get finish as shown bellow This has also been shown in the figure below. By typing this command , you are actually generating 500 random events for testing. Example The below example demonstrates the use of Testing. It crates a basic application which can be used for monkey. To experiment with this example, you need to run this on an actual device and then follow the monkey steps explained in the beginning. Steps Description 1 You will useAndroid studio to create an Android application under a package com.tutorialspoint.myapplication. 2 Modify src/MainActivity.java file to add Activity code. 3 Modify layouta XML file res/layout/activity_main.xml add any GUI component if required. 4 Create src/second.java file to add Activity code. 5 Modify layout XML file res/layout/view.xml add any GUI component if required. 6 Run the application and choose a running android device and install the application on it and verify the results. Here is the content of MainActivity.java. package com.tutorialspoint.myapplication; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { Button b1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); b1=(Button)findViewById(R.id.button); } public void button(View v){ Intent in =new Intent(MainActivity.this,second.class); startActivity(in); } } Here is the content of second.java. package com.tutorialspoint.myapplication; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; public class second extends Activity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.view); Button b1=(Button)findViewById(R.id.button2); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(second.this,”Thanks”,Toast.LENGTH_SHORT).show(); } }); } } Here is the content of activity_main.xml. In the below code abc indicates the logo of tutorialspoint.com <?xml version=”1.0″ encoding=”utf-8″?> <RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android” xmlns:tools=”http://schemas.android.com/tools” android:layout_width=”match_parent” android:layout_height=”match_parent” android:paddingLeft=”@dimen/activity_horizontal_margin” android:paddingRight=”@dimen/activity_horizontal_margin” android:paddingTop=”@dimen/activity_vertical_margin” android:paddingBottom=”@dimen/activity_vertical_margin” tools:context=”.MainActivity”> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”UI Animator Viewer” android:id=”@+id/textView” android:textSize=”25sp” android:layout_centerHorizontal=”true” /> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Tutorials point” android:id=”@+id/textView2″ android:layout_below=”@+id/textView” android:layout_alignRight=”@+id/textView” android:layout_alignEnd=”@+id/textView” android:textColor=”#ff36ff15″ android:textIsSelectable=”false” android:textSize=”35dp” /> <ImageView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/imageView” android:src=”@drawable/abc” android:layout_below=”@+id/textView2″ android:layout_centerHorizontal=”true” /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Button” android:onClick=”button” android:id=”@+id/button” android:layout_below=”@+id/imageView” android:layout_centerHorizontal=”true” android:layout_marginTop=”100dp” /> </RelativeLayout> Here is the content of view.xml <?xml version=”1.0″ encoding=”utf-8″?> <RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android” android:layout_width=”match_parent” android:layout_height=”match_parent”> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”button” android:id=”@+id/button2″ android:layout_centerVertical=”true” android:layout_centerHorizontal=”true” /> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Tutorials point ” android:id=”@+id/textView3″ android:textColor=”#ff3aff22″ android:textSize=”35dp” android:layout_above=”@+id/button2″ android:layout_centerHorizontal=”true” android:layout_marginBottom=”90dp” /> </RelativeLayout> Here is the content of Strings.xml. <resources> <string name=”app_name”>My Application</string> </resources> Here is the content of AndroidManifest.xml. <?xml version=”1.0″ encoding=”utf-8″?> <manifest xmlns:android=”http://schemas.android.com/apk/res/android” package=”com.tutorialspoint.myapplication” > <application android:allowBackup=”true” android:icon=”@mipmap/ic_launcher” android:label=”@string/app_name” android:theme=”@style/AppTheme” > <activity android:name=”.MainActivity” android:label=”@string/app_name” > <intent-filter> <action android:name=”android.intent.action.MAIN” /> <category android:name=”android.intent.category.LAUNCHER” /> </intent-filter> </activity> <activity android:name=”.second”></activity> </application> </manifest> Let”s try to run your Android Testing application. I assume you have connected your actual Android

Android – UI Testing

Android – UI Testing ”; Previous Next Android SDK provides the following tools to support automated, functional UI testing on your application. uiautomatorviewer uiautomator uiautomatorviewer A GUI tool to scan and analyse the UI components of an Android application. The uiautomatorviewer tool provides a convenient visual interface to inspect the layout hierarchy and view the properties of the individual UI components that are displayed on the test device. Using this information, you can later create uiautomator tests with selector objects that target specific UI components to test. To analyse the UI components of the application that you want to test, perform the following steps after installing the application given in the example. Connect your Android device to your development machine Open a terminal window and navigate to <android-sdk>/tools/ Run the tool with this command uiautomatorviewer Commands would be followed as shown below You will see the following window appear. It is the default window of the UI Automator Viewer. 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. On the right side of this window, you will see two partitions. The upper partition explains the Nodes structure, the way the UI components are arranged and contained. Clicking on each node gives detail in the lower partition. As an example, consider the below figure. When you click on the button, you can see in the upper partition that Button is selected, and in the lower partition, its details are shown. Since this button is click able, that”s why its property of click able is set to true. UI Automator Viewer also helps you to examine your UI in different orientations. For example, just change your device orientation to landscape, and again capture the screen shot. It is shown in the figure below − uiautomator Now you can create your own test cases and run it with uiautomatorviewer to examine them. In order to create your own test case, you need to perform the following steps − From the Project Explorer, right-click on the new project that you created, then select Properties > Java Build Path, and do the following − Click Add Library > JUnit then select JUnit3 to add JUnit support. Click Add External JARs… and navigate to the SDK directory. Under the platforms directory, select the latest SDK version and add both the uiautomator.jar and android.jar files. Extend your class with UiAutomatorTestCase Right the necessary test cases. Once you have coded your test, follow these steps to build and deploy your test JAR to your target Android test device. Create the required build configuration files to build the output JAR. To generate the build configuration files, open a terminal and run the following command: <android-sdk>/tools/android create uitest-project -n <name> -t 1 -p <path> The <name> is the name of the project that contains your uiautomator test source files, and the <path> is the path to the corresponding project directory. From the command line, set the ANDROID_HOME variable. set ANDROID_HOME=<path_to_your_sdk> Go to the project directory where your build.xml file is located and build your test JAR. ant build Deploy your generated test JAR file to the test device by using the adb push command. adb push <path_to_output_jar> /data/local/tmp/ Run your test by following command − adb shell uiautomator runtest LaunchSettings.jar -c com.uia.example.my.LaunchSettings 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 1 You will use Android studio to create an Android application under a package com.tutorialspoint.myapplication. 2 Modify src/MainActivity.java file to add Activity code. 3 Modify layout XML file res/layout/activity_main.xml add any GUI component if required. 4 Create src/second.java file to add Activity code. 5 Modify layout XML file res/layout/view.xml add any GUI component if required. 6 Run the application and choose a running android device and install the application on it and verify the results. Here is the content of MainActivity.java. package com.tutorialspoint.myapplication; import android.content.Intent; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends ActionBarActivity { Button b1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); b1=(Button)findViewById(R.id.button); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent in =new Intent(MainActivity.this,second.class); startActivity(in); } }); } } Here is the content of second.java. package com.tutorialspoint.myapplication; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; public class second extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.view); Button b1=(Button)findViewById(R.id.button2); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(second.this,”Thanks”,Toast.LENGTH_LONG).show(); } }); } } Here is the content of activity_main.xml In the following code abc indicates the logo of tutorialspoint.com <?xml version=”1.0″ encoding=”utf-8″?> <RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android” xmlns:tools=”http://schemas.android.com/tools” android:layout_width=”match_parent” android:layout_height=”match_parent” android:paddingLeft=”@dimen/activity_horizontal_margin” android:paddingRight=”@dimen/activity_horizontal_margin” android:paddingTop=”@dimen/activity_vertical_margin” android:paddingBottom=”@dimen/activity_vertical_margin” tools:context=”.MainActivity”> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”UI Animator Viewer” android:id=”@+id/textView” android:textSize=”25sp” android:layout_centerHorizontal=”true” /> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Tutorials point” android:id=”@+id/textView2″ android:layout_below=”@+id/textView” android:layout_alignRight=”@+id/textView” android:layout_alignEnd=”@+id/textView” android:textColor=”#ff36ff15″ android:textIsSelectable=”false” android:textSize=”35dp” /> <ImageView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/imageView” android:src=”@drawable/abc” android:layout_below=”@+id/textView2″ android:layout_centerHorizontal=”true” /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Button” android:id=”@+id/button” android:layout_marginTop=”98dp” android:layout_below=”@+id/imageView” android:layout_centerHorizontal=”true” /> </RelativeLayout> Here is the content of view.xml. <?xml version=”1.0″ encoding=”utf-8″?> <RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android” android:orientation=”vertical” android:layout_width=”match_parent” android:layout_height=”match_parent”> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=” Button” android:id=”@+id/button2″ android:layout_gravity=”center_horizontal” android:layout_centerVertical=”true” android:layout_centerHorizontal=”true” /> </RelativeLayout> Here is the content of Strings.xml. <resources> <string name=”app_name”>My Application</string> </resources> Here is the content of AndroidManifest.xml. <?xml version=”1.0″ encoding=”utf-8″?> <manifest xmlns:android=”http://schemas.android.com/apk/res/android” package=”com.tutorialspoint.myapplication” > <application android:allowBackup=”true” android:icon=”@mipmap/ic_launcher” android:label=”@string/app_name” android:theme=”@style/AppTheme” > <activity android:name=”.MainActivity” android:label=”@string/app_name” > <intent-filter> <action android:name=”android.intent.action.MAIN” /> <category android:name=”android.intent.category.LAUNCHER” /> </intent-filter> </activity> <activity android:name=”.second”></activity> </application> </manifest> Let”s try to run your UI Testing application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Android studio, open one of your project”s activity files and click Run icon from the tool bar. Before starting your application, Android studio will display following