Android Emulator Unit2
Android Emulator Unit2
UNIT – II Emulator-Android Virtual Device, Launching emulator, Editing emulator settings, Emulator
shortcuts, Logcat usage, Introduction to DDMS, Second App:- (switching between activities) , Develop an
app for demonstrating the communication between Intents, Basic UI design, Form widgets, Text Fields,
Layouts, [dip, dp, sip,sp] versus px.
The Android emulator comes with predefined configurations for several Android
phones, Wear OS, tablet, Android TV devices.
The Android emulator takes additional requirements beyond the basic system
requirement for Android Studio. These requirements are given below:
The Android emulator is installed while installing the Android Studio. However
some components of emulator may or may not be installed while installing
Android Studio. To install the emulator component, select the Android
Emulator component in the SDK Tools tab of the SDK Manager.
We can run an Android app form the Android Studio project, or we can run an app
which is installed on the Android Emulator as we run any app on a device.
1.1 Open the AVD Manager by clicking Tools > AVD Manager.
1.2 Click on Create Virtual Device, at the bottom of the AVD Manager dialog.
Then Select Hardware page appears.
1.3 Select a hardware profile and then click Next. If we don?t see the hardware
profile we want, then we can create or import a hardware profile. The System
Image page appears.
1.4 Select the system image for the particular API level and click Next. This leads
to open a Verify Configuration page.
1.5 Change AVD properties if needed, and then click Finish.
2. In the toolbar, choose the AVD, which we want to run our app from the target
device from the drop-down menu.
3. Click Run.
While the emulator is running, we can run the Android Studio project and select
the emulator as the target device. We can also drag an APKs file to install on an
emulator, and then run them.
The Android SDK includes the Android device emulator. Android emulator lets
you develop and test out the application without using a physical device.
or
For example, if we execute the emulator from Android Studio on a Mac, the
default command line will be similar as follows:
1. $ emulator -list-avds
Run and stop an emulator, and clear data
From the Virtual Device page, we can perform the following operation on
emulator:
Graphics acceleration uses your computer's hardware (typically the GPU) to make
screen rendering faster. Android devices use OpenGL for Embedded Systems
(OpenGL ES or GLES) for rendering both 2D and 3D graphics on the screen.
When you create an Android Virtual Device (AVD) in the AVD Manager, you can
specify whether the emulator should use hardware or software to emulate the GPU
of the AVD. Hardware acceleration is recommended and is typically faster.
However, you might need to use software acceleration if your computer uses
graphics drivers that aren't compatible with the emulator.
If you start the emulator from the command line, you can also override the
graphics acceleration setting in the AVD for that virtual device instance.
Requirements
To specify a graphics acceleration type when you run an AVD from the command
line, include the -gpu option, as shown in the following example:
SHORTCUT IN EMULATOR
1. Main Device Keys
LogCat: LogCat usually outputs the messages that we print out using the Log class
accompanied by other system messages. LogCat is integrated to DDMS. We can
filter certain messages when we use LogCat of DDMS and they are:
o Verbose { v (String, String) }
o Info { I (String, String) }
o Debug { d (String, String) }
o Error { e (String, String) }
o Warn { w (String, String) }
Phone Operations: Using DDMS we can simulate the phone operations like
incoming call or sending SMS, etc. These are:
o Voice
o SMS
Location: Using DDMS we can also simulate location co-ordinates. We can send
mock location to simulate the actual location coordinates and test the application.
The geo-location flavors of data available to us are:
o Manual
o GPX (GPS exchange file)
o KML (Keyhole Markup Language)
Using LogCats
Introduction to DDMS
DDMS stands for Dalvik Debug Monitoring Service is basically a graphical user
interface application which is meant for debugging. This application is shipped
with the Android SDK. It provides process examination capabilities, log cat, screen
capture, thread and heap information on device, emulating location information,
emulating incoming call etc. In the tools/ directory DDMS is shipped. DDMS can
function for both connected device and emulator. Although, if you have an
emulator up and running, in that case DDMS would communicated with emulator
by default.
Figure DDMS in tools directory
DDMS usually works as a bridge between integrated development environment
and applications running on device. Now, android application runs on separate
virtual machine. To be more specific every application has its own virtual machine
that’s the simple reason why failure of one application does not hampers the
performance of other application running on same device. So every application has
its own process which runs into a separate a virtual machine. Each process listens
for a debugger but in a different port. For running DDMS we have two ways and
they are as follows:
Command line: We have to type ddms (./ddms on Linux) from tools/ directory
Eclipse: In case of Eclipse we have to navigate through the following
path: Window-> Open Perspective->Other.. DDMS
After DDMS initializes, it connects to adb (android debug bridge) and as soon as a
device is connected, VM monitoring service is created between DDMS and adb.
When VM (virtual machine) on device is started or terminated, it notifies DDMS
about the current status. When VM starts running, DDMS would retrieve the pid
i.e., process ID of VM and it establishes a connection to debugger of VM. These
things are possible as DDMS retrieves the information through adb. The adb
daemon on device helps to open the connection. Thus DDMS can communicate
with VM now.
Heap Memory and Threads: DDMS can be used to view the amount of heap
memory used by current process. We can track heap usage at any point of
execution of android application. As far as threads are concerned, DDMS shows
the current threads which are running for our application.
Tracking objects: DDMS also facilitates the tracking of objects. In other words,
the objects which are allocated to memory and also the threads or classes attached
to the objects respectively. This is very useful when we talk about the performance
of application in terms of memory usage.
File system: DDMS also provides a file explorer with which we can play around
the file system of attached device (emulator or connected device). We can view,
copy and delete files on device. This is very helpful when we intend to transfer file
from one device to another. This is also useful to keep track of files created by our
application on device.
Method profiling: DDMS also facilitates method profiling. It is like keeping an
eye on the number of calls to the method, time of execution, etc. In other words,
keeping track of metrics of method.
Network traffic tool: DDMS includes a Network usage tool which gives a
detailed track of application making network requests. We can easily monitor the
activities of application and can optimize the code as and when required. We can
monitor how frequently the data is being transferred. By keeping track on this, we
can make our application more battery efficient.
LogCat: LogCat usually outputs the messages that we print out using the Log class
accompanied by other system messages. LogCat is integrated to DDMS. We can
filter certain messages when we use LogCat of DDMS and they are:
o Verbose { v (String, String) }
o Info { I (String, String) }
o Debug { d (String, String) }
o Error { e (String, String) }
o Warn { w (String, String) }
Phone Operations: Using DDMS we can simulate the phone operations like
incoming call or sending SMS, etc. These are:
o Voice
o SMS
Location: Using DDMS we can also simulate location co-ordinates. We can send
mock location to simulate the actual location coordinates and test the application.
The geo-location flavors of data available to us are:
o Manual
o GPX (GPS exchange file)
o KML (Keyhole Markup Language)
Using LogCats
1. Devices: This displays the connected devices. It includes real devices and
emulators as well.
2. Emulator Control: Various controls for injecting events and data into the
emulator is possible. It includes Telephony status, Telephony Action and Location
Control. Telephony status specifies the voice and data format, latency and network
speed. With Telephony Action we can make false calls or send SMS. Even the
message content in SMS can be specified. With Location Control it is possible to
send fake GPS signal to the GPS (Global Positioning System) provider in the
emulator.
3. Device Status Panel: This is used to analyze the process. It includes Thread,
Heap, Allocation Tracker, and File Explorer.
Logcat
Android Studio has a logcat tab inside Android Monitor that prints system events,
such as when a garbage collection occurs, as well as messages your app prints with
the Log class, to assist with debugging. Logcat displays messages in real time and
also keeps a history so you can view older messages.
Log.d(tag, message) Debug Show debug log messages that are useful during developm
3. If more than one device is attached, then the device must be identified. For
example, adb -d logcat shows the log of the only physical device connected,
while adb -e logcat shows the log of the only emulator running.
4.
In order to switch between Activities in Android you will need to follow these
steps:
Add a new method called “switchActivities()”, inside this method we will create an
Intent passing a parameters of the current activity and the new activity class. Then
use the startActivity(Intent) method to passing the Intent that was just created.
Inside the onCreate method, add an OnClickListener to the Button used for
switching the new Activity. When selected call the switchActivities() method.
}
Using the finish() method to preserve the back button functionality
Making the following changes to the Second Activity class.
Inside the onCreate method, add an OnClickListener to the Button used for going
back to the previous Activity. When selected call the finish() method will will
remove the Second Activity and take you back to the First Activity.
User Interface of the Second Activity
Button backButton;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
backButton = findViewById(R.id.activity_second_button);
backButton.setOnClickListener(new View.OnClickListener() {
@Override
finish();
}
});
}}
UI screen components
A typical user interface of an android application consists of action bar and the
application content area.
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.
An activity is consist of views. A view is just a widget that appears on the screen. It
could be button e.t.c. One or more views can be grouped together into one GroupView.
Example of ViewGroup includes layouts.
Android Layout Design Tutorial: Views
A View is considered as a basic building block for a proper user interface that is
actually created from the View class. This occupies a rectangular area on the screen and
is eventually takes care of drawing and event handling.
A View is the base class for widgets, which are used to create interactive UI
components like buttons, text fields, etc. Now talking about the rectangle area or a box,
It can either be an image, a piece of text, a button or anything that an android
application can display. The rectangle here is actually invisible, but every view
occupies a rectangle shape.
Now let’s point out the major differences between View and the ViewGroup.
View
1. View objects are the basic building blocks of the UI elements in Android.
2. A View is a simple rectangle box which response to the user’s actions.
3. View refers to the android.view. View class, which is the base class of all UI
classes.
4. Examples are EditText, Button, CheckBox, etc..
ViewGroup
A layout defines the structure for a User Interface in the application. All elements in
the layout are built using a hierarchy of View and ViewGroup objects.
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
Linear Layout
Linear layout is further divided into horizontal and vertical layout. It means it can
arrange views in a single column or in a single row. Here is the code of linear
layout(vertical) that includes a text view.
<?xml version=”1.0” encoding=”utf-8”?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:orientation=”vertical” >
<TextView
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”@string/hello” />
</LinearLayout>
AbsoluteLayout
The AbsoluteLayout enables you to specify the exact location of its children. It can be
declared like this.
<AbsoluteLayout
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
xmlns:android=”http://schemas.android.com/apk/res/android” >
<Button
android:layout_width=”188dp”
android:layout_height=”wrap_content”
android:text=”Button”
android:layout_x=”126px”
android:layout_y=”361px” />
</AbsoluteLayout>
TableLayout
The TableLayout groups views into rows and columns. It can be declared like this.
<TableLayout
xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_height=”fill_parent”
android:layout_width=”fill_parent” >
<TableRow>
<TextView
android:text=”User Name:”
android:width =”120dp”
/>
<EditText
android:id=”@+id/txtUserName”
android:width=”200dp” />
</TableRow>
</TableLayout>
RelativeLayout
The RelativeLayout enables you to specify how child views are positioned relative to
each other. It can be declared like this.
<RelativeLayout
android:id=”@+id/RLayout”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
xmlns:android=”http://schemas.android.com/apk/res/android” >
</RelativeLayout>
FrameLayout
The FrameLayout is a placeholder on screen that you can use to display a single view.
It can be declared like this.
<?xml version=”1.0” encoding=”utf-8”?>
<FrameLayout
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_alignLeft=”@+id/lblComments”
android:layout_below=”@+id/lblComments”
android:layout_centerHorizontal=”true” >
<ImageView
android:src = “@drawable/droid”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content” />
</Image view>
</FrameLayout>
Apart form these attributes, there are other attributes that are common in all views and
ViewGroups. They are listed below −
1 layout_width
Specifies the width of the View or ViewGroup
2 layout_height
Specifies the height of the View or ViewGroup
3 layout_marginTop
Specifies extra space on the top side of the View or ViewGroup
4 layout_marginBottom
Specifies extra space on the bottom side of the View or
ViewGroup
5 layout_marginLeft
Specifies extra space on the left side of the View or ViewGroup
6 layout_marginRight
Specifies extra space on the right side of the View or ViewGroup
7 layout_gravity
Specifies how child Views are positioned
8 layout_weight
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.
1 Dp
Density-independent pixel. 1 dp is equivalent to one pixel on a
160 dpi screen.
2 Sp
Scale-independent pixel. This is similar to dp and is recommended
for specifying font sizes
3 Pt
Point. A point is defined to be 1/72 of an inch, based on the
physical screen size.
4 Px
Pixel. Corresponds to actual pixels on the screen
Screen Densities
Optimizing layouts
Widgets
Widgets enable users to interact with an Android Studio application page. There
are various kinds of widgets, such as Buttons and TextViews.
To see all the widgets at your disposal, create a new application project called
“Widgets” and select "empty activity". Call your activity “MainActivity”.
There are two components of each Android activity: the XML (Extensible Markup
Language) design (the beauty) and the Java text (the brains).
On the activity_main.xml page, you can see the full widgets palette underneath the
various layout options.
As you can see, there are 20 widgets available for you to use. In this guide, we’ll
discuss TextViews and Buttons, which are probably the most common widgets in
Android development.
Creating a Widget
Your default activity comes with a TextView containing “Hello World”. So you’ve
technically created a widget before this tutorial without even knowing it!
To create another widget, we simply drag and drop the desired widget onto the
desired location on the Android application page.
For example, let’s create a Button at the center of our page. Android Studio will
help us align our widget automatically. Keep in mind that we can also align the
widget by changing its properties, which appear on the XML text page.
Changing Button Text
By default, the Button will have “New Button” as its text element. You can change
the Button’s text by either double-clicking its text or modifying it on the design
page or by scrolling through the Button properties on the right and finding
the text property. Lastly, you can change its text by switching to the XML text tab
and modifying its android:text property.
Let’s make our button say “Change Background Color” by changing the Button
properties on the XML text page to read android:text = “Change Background
Color”
String Resources
You will find that the code is highlighted in yellow after you make the change.
Widget: onClick
If you switch over to the Design page, select the Button widget that we created,
and scroll through its properties, you’ll find the onClick property. onClick allows
you to choose a Java method that the application will call once the Button is
clicked.
Let’s change the onClick properties of our Button to call the method
“changeColor”. Keep in mind that we have to create the changeColor() method in
our Java Class for this onClick command to work.
Component IDs
To have our changeColor method function, we’ll need to assign IDs to our Layout
and our TextView. By default, our “Hello World” TextView object does not have
an ID and neither does our Layout (which is a RelativeLayout, meaning that it
allows widgets and other components to be aligned relative to each other).
Select the TextView in the top right box, which is titled “Component Tree”. Scroll
through its properties until you see “id”. Change its ID to “text”.
Do the same thing for the RelativeLayout component, but set its ID to “layout”.
You should be able to see the corresponding ID next to each component in the
Component Tree.
Let’s move onto the actual changeColor method. Go to your MainActivity.java tab.
In this tab, you’ll see a method called onCreate. This runs whenever the app first
starts up.
We’ll create our “changeColor” method right after the onCreate. Add the following
to your MainActivity.java class:
1
2
3
4
5
6
7
8
public void changeColor(View view)
{
RelativeLayout layout = (RelativeLayout)findViewById(R.id.layout);
TextView text = (TextView)findViewById(R.id.text);
layout.setBackgroundColor(Color.RED);
text.setText(R.string.PageIsRed);
}
Our method will turn the color of our layout to red once the button is clicked. It
will also set the TextView object to say “Page is Red”.
For the beginner to Android Studio, there are many things in the code block above
that you should notice.
First, check out our method signature: public void changeColor(View view).
Android requires onClick methods to take a View as a parameter; failure to do so
can cause your app to crash.
This Android tutorial is to explain the difference between dp, dip, sp, px, in, mm,
pt and what we should use when. This is to enable design a consistent UI across
different Android screen sizes. Before going into the difference let us understand
some basic terminologies. Screen size in Android is grouped into categories small,
medium, large, extra large, double-extra and triple-extra. Screen density is the
amount of pixels within an area (like inch) of the screen. Generally it is measured
in dots-per-inch (dpi). Screen density is grouped as low, medium, high and extra
high. Resolution is the total number of pixels in the screen.
dp: Density Independent Pixel, it varies based on screen density . In 160 dpi
screen, 1 dp = 1 pixel. Except for font size, use dp always.
dip: dip == dp. In earlier Android versions dip was used and later changed
to dp.
sp: Scale Independent Pixel, scaled based on user’s font size preference.
Fonts should use sp.
px: our usual standard pixel which maps to the screen pixel.
in: inches, with respect to the physical screen size.
mm: millimeters, with respect to the physical screen size.
pt: 1/72 of an inch, with respect to the physical screen size.
Always use dp and sp only. sp for font sizes and dp for everything else. It will
make UI compatible for Android devices with different densities.
px = dp * (dpi / 160)
dp to px in device
Following example may help understand better. The scaling occurs based on
bucket size of 120(ldpi), 160(mdpi), 240(hdpi), 320(xhdpi), 480(xxhdpi) and
640(xxxhdpi). The Google suggested ratio for designing is 3:4:6:8:12 for
ldpi:mdpi:hdpi:xhdpi:xxhdpi
You may use the following DPI calculator to fix your image sizes and other
dimensions when you wish to have an uniform UI design in all Android devices.
Note: When designing an image for Android in Photoshop or other image editing
tools, have the resolution as 72 pixels/inch.