Lect 4-Building Your First Mobile App
Lect 4-Building Your First Mobile App
This chapter describes how to develop applications using Android Studio, which is an integrated development
environment (IDE) for Android.
When you are ready to start coding, you use Android Studio to go through the following steps:
app.
When choosing a unique Company domain, keep in mind that apps published to Google Play must have a unique
package name. Because domains are unique, prepending the app's name with your name, or your company's domain
name, should provide an adequately unique package name. If you don't plan to publish the app, you can accept the
default example domain. Be aware that changing the package name later is extra work.
Choosing target devices and the minimum SDK
When choosing Target Android Devices, Phone and Tablet are selected by default, as shown in the figure below. The
choice shown in the figure for the Minimum SDK—API 15: Android 4.0.3 (IceCreamSandwich)—makes your app
compatible with 97% of Android-powered devices active on the Google Play Store.
Different devices run different versions of the Android system, such as Android 4.0.3 or Android 4.4. Each successive
version often adds new APIs not available in the previous version. To indicate which set of APIs are available, each
version specifies an API level. For instance, Android 1.0 is API level 1 and Android 4.0.3 is API level 15.
The Minimum SDK declares the minimum Android version for your app. Each successive version of Andr oid provides
compatibility for apps that were built using the APIs from previous versions. That means your app should always be
compatible with future versions of Android, if you use the documented Android APIs.
Generate Layout file: Leave this checkbox selected to create the layout resource connected to this Activity, which is
usually named activity_main. The layout defines the UI for the Activity.
Backwards Compatibility (AppCompat): Leave this checkbox selected to include the AppCompat library. Use
the AppCompat library to make sure that the app is compatible with previous versions of Android, even if the app uses
features found only in newer Android versions.
Android Studio creates a folder for your projects, and builds the project with Gradle.
Tip: See the Configure your build developer page for detailed information.
Exploring a project
An Android Studio project contains all of the source code and all resources for an app. The resources include layouts,
strings, colors, dimensions, and images. The Android Studio main window is made up of several logical areas,
or panes, as shown in the figure below.
1. Toolbar: Provides a wide range of actions, including running the Android app and launching Android tools.
2. Navigation bar: Navigate through the project and open files for editing.
3. Project pane: Displays project files in a hierarchy. The selected hierarchy in the figure above is Android.
4. Editor: The contents of a selected file in the project. For example, after you select a layout (as shown in the figu re
above), the editor pane shows the layout editor with tools to edit the layout. After you select a Java code file, the editor
pane shows the Java code with tools for editing the code.
5. Tabs along the left, right, and bottom of the window: You can click tabs to open other panes, such as Logcat to open
the Logcat pane with log messages, or TODO to manage tasks.
The status bar at the bottom of the Android Studio window displays the status of the project and Android Studio itself,
as well as any warnings or messages. You can watch the build progress in the status bar.
Tip: You can organize the main window to give yourself more screen space by hiding or moving panes. You can also
use keyboard shortcuts to access most features. See Keyboard Shortcuts for a complete list.
The Project pane appears. To view the project in the standard Android project hierarchy, select Android from the
Gradle files
When you first create an app project, the Project > Android pane appears with the Gradle Scripts folder expanded as
shown below. If the Gradle Scripts folder is not expanded, click the triangle to expand it. This folder contains all the
App code
To view and edit the Java code, expand the app folder, the java folder, and the com.example.android.helloworld folder.
com.example.hello.helloworld (or the domain name you have specified): All the files for a package are in a folder
named after the package. For your Hello World app, there is one package, and it contains only MainActivity.java. The
first Activity (screen) that the user sees, which also initializes app-wide resources, is customarily called MainActivity.
(The file extension is omitted in the Project > Android pane.)
com.example.hello.helloworld(androidTest): This folder is for your instrumented tests, and starts out with a skeleton
test file.
com.example.hello.helloworld(test): This folder is for your unit tests and starts out with an automatically created
skeleton unit test file.
Layout files
To view and edit a layout file, expand the res folder and the layout folder to see the layout file. In the figure below, the
layout file is called activity_main.xml .
Double-click the file to open it in the layout editor. Layout files are written in XML.
Resource files
The res folder holds resources, such as layouts, strings, and images. An Activity is usually associated with a layout of
UI views that are defined as an XML file. This XML file is usually named after its Activity. The res folder includes
these subfolders:
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
Android namespace and application tag
The Android Manifest is coded in XML and always uses the Android namespace:
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.helloworld">
The package expression shows the unique package name of the new app. Do not change the package expression after
the app is published.
The <application> tag, with its closing </application> tag, defines the manifest settings for the entire app.
Automatic backup
The android:allowBackup attribute enables automatic app data backup:
android:allowBackup="true"
Setting the android:allowBackup attribute to true enables the app to be backed up automatically and restored as
needed. Users invest time and effort to configure apps. Switching to a new device can cancel out all that careful
configuration. The system performs this automatic backup for nearly all app data by default, and does so without the
developer having to write any additional app code.
For apps whose target SDK version is Android 6.0 (API level 23) and higher, devices running Android 6.0 and higher
automatically create backups of app data to the cloud because the android:allowBackup attribute defaults to true if
omitted. For apps < API level 22 you have to explicitly add the android:allowBackup attribute and set it to true.
Tip: To learn more about the automatic backup for apps, see Configuring Auto Backup for Apps.
App theme
The android:theme attribute sets the app's theme, which defines the appearance of UI elements such as text:
android:theme="@style/AppTheme">
The theme attribute is set to the standard theme AppTheme. Themes are described in a separate lesson.
The API level allows a developer to declare the minimum version with which the app is compatible, using the <uses-
sdk> manifest tag and its minSdkVersion attribute. For example, the Calendar Provider APIs were added in Android 4.0
(API level 14). If your app can't function without these APIs, declare API level 14 as the a pp's minimum supported
version like this:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.helloworld">
<uses-sdk android:minSdkVersion="14" android:targetSdkVersion="19" />
// ... Rest of manifest information
</manifest>
The minSdkVersion attribute declares the minimum version for the app, and the targetSdkVersion attribute declares the
highest (newest) version which has been optimized within the app. Each successive version of Android provides
compatibility for apps that were built using the APIs from previous versions, so the app should always be compatible
with future versions of Android while using the documented Android APIs.
The targetSdkVersion attribute does not prevent an app from being installed on Android versions that are higher
(newer) than the specified value. Even so, the target attribute is important, because it indicates to the system whether
the app should inherit behavior changes in newer versions.
If you don't update the targetSdkVersion to the latest version, the system assumes that your app requires backward-
compatible behaviors when it runs on the latest version. For example, among the behavior changes in Android 4.4,
alarms created with the AlarmManager APIs are now inexact by default so that the system can batch app alarms and
preserve system power. If your target API level is lower than "19", the system retains the previous API's behavior for
your app.
Android Studio uses Gradle as the foundation of the build system, with more Android-specific capabilities provided by
the Android Plugin for Gradle. This build system runs as an integrated tool from the Android Studio menu.
android {
compileSdkVersion 26
defaultConfig {
applicationId "com.example.android.helloworld"
minSdkVersion 15
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner
"android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation
'com.android.support.test.espresso:espresso-core:3.0.1'
}
The build.gradle files use Gradle syntax. Gradle is a Domain Specific Language (DSL) for describing and
manipulating the build logic using Groovy, which is a dynamic language for the Java Virtual Machine (JVM). You don't
need to learn Groovy to make changes, because the Android Plugin for Gradle introduces most of the DSL elements
you need.
Tip: To learn more about the Android plugin DSL, read the DSL reference documentation.
android {
compileSdkVersion 26
// ... Rest of android block.
}
The android { } block specifies the target SDK version for compiling the app code ( compileSdkVersion 26) and several
blocks of information.
Build types
Build types for the app are specified in a buildTypes { } block, which controls how the app is built and packaged.
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
}
}
The build type specified is release for the app's release. Another common build type is debug. Configuring build types is
described in a separate lesson.
Dependencies
Dependencies for the app are defined in the dependencies { } block, which is the part of the build.gradle file that is
most likely to change as you start developing code that depends on other libraries. The block is part of the standard
Gradle API and belongs outside the android { } block.
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation
'com.android.support.test.espresso:espresso-core:3.0.1'
}
In the snippet above, the statement implementation fileTree(dir: 'libs', include: ['*.jar']) adds a dependency of
all ".jar" files inside the libs folder.
Syncing your project
When you make changes to the build configuration files in a project, Android Studio requires that you sync the project
files. During the sync, Android Studio imports the build configuration changes and runs checks to make sur e the
configuration won't create build errors.
To sync the project files, click Sync Now in the notification bar that appears when making a change (as shown in the
figure below), or click the Sync Project with Gradle Files button in the menu bar.
If Android Studio notices any errors with the configuration — for example, if the source code uses API features that are
only available in an API level higher than the compileSdkVersion—the Messages window appears to describe the issue.
The Android Virtual Device (AVD) manager creates a virtual device or emulator that simulates the configuration for a
particular type of Android-powered device. Use the AVD Manager to define the hardware characteristics of a device
and its API level, and to save it as a virtual device configuration. When you start the Android emulator, it reads a
specified configuration and creates an emulated device on your computer that behaves exactly like a physical version
of that device.
Creating a virtual device
To run an emulator on your computer, use the AVD Manager to create a configuration that describes the virtual de vice.
Select Tools > Android > AVD Manager, or click the AVD Manager icon in the toolbar.
The Your Virtual Devices screen appears showing all of the virtual devices created previously. Click the +Create
Virtual Device button to create a new virtual device.
You can select a device from a list of predefined hardware devices. For each device, the table provides a column for
its diagonal display size (Size), screen resolution in pixels (Resolution), and pixel density (Density). For example, the
pixel density of the Nexus 5 device is xxhdpi, which means the app uses the icons in the xxhdpi folder of
the mipmap folder. Likewise, the app uses layouts and drawables from folders defined for that density.
After you click Next, the System Image screen appears for choosing the version of the Android system for the device.
The Recommended tab shows the recommended systems for the device. More versions are available under the x86
Images and Other Images tabs. If a Download link is visible next to a system image version, it is not installed yet.
Click the link to start the download, and click Finish when it's done.
1. In Android Studio, select Run > Run app or click the Run icon in the toolbar.
2. In the Select Deployment Target window, under Available Emulators, select the virtual device you created, and
click OK.
The emulator starts and boots just like a physical device. Depending on the speed of your computer, the startup
process might take a while. The app builds, and once the emulator is ready, Android Studio uploads the app to the
emulator and runs it.
You should see the app created from the Empty Activity template ("Hello World") as shown in the following figure,
which also shows Android Studio's Run pane that displays the actions performed to run the app on the emulator.
Tip: When testing on a virtual device, it is a good practice to start it up once, at the very beginning of your session. Do
not close it until you are done testing your app, so that your app doesn't have to go through the device startup process
again. To close the virtual device, select Quit from the menu or press Control-Q in Windows or Command-Q in
macOS.
The figure above shows the emulator and the run log:
To let Android Studio communicate with your Android-powered device, you must turn on USB Debugging on the
device. You enable USB Debugging in the device's Developer options settings. (Note that enabling USB Debugging
is not the same as rooting your device.)
On Android 4.2 and higher, the Developer options screen is hidden by default. To show developer options and
enable USB Debugging:
1. On your device, open Settings > About phone and tap Build number seven times.
2. Return to the previous screen (Settings). Developer options appears at the bottom of the list. Tap Developer
options.
3. Select USB Debugging.
4. Connect the device and run the app from Android Studio.
1. The Logcat tab for opening and closing the Logcat pane, which displays information about your app as it is running. If
you add Log statements to your app, Log messages appear here.
2. The Log level menu set to Verbose (the default), which shows all Log messages. Other settings
include Debug, Error, Info, and Warn.
Log: The Log class for sending log messages to the Logcat pane.
d: The Debug Log level setting to filter log message display in the Logcat pane. Other log levels
are e for Error, w for Warn, and i for Info. You assign a log level so that you can filter the log messages using the
drop-down menu in the center of the Logcat pane.
"MainActivity": The first argument is a tag which can be used to filter messages in the Logcat pane. This tag is
commonly the name of the Activity from which the message originates. However, you can name the tag anything that
is useful to you for debugging.
"Hello world": The second argument is the actual message.
1. If the Logcat pane is not already open, click the Logcat tab at the bottom of Android Studio to open it.
2. Change the Log level in the Logcat pane to Debug. (You can also leave the Log level as Verbose, because there are
so few log messages.)
3. Run your app on a virtual device.