Android Studio Cookbook - Sample Chapter
Android Studio Cookbook - Sample Chapter
Android Studio Cookbook - Sample Chapter
ee
This book starts with an introduction to Android Studio. You will learn how to create an Android app
that can send and receive data using Parse as a backend. It also shows you how to build an app that runs
on an Android wearable device. It explains how to test applications using Genymotion. It elaborates on
applying patterns, unit testing, and code analysis tools.
By the end of the book, you will be able to develop better apps using less code. You will benefit from the
Android Studio IDE that provides you with all the options to accomplish this.
your applications
Use memory monitoring tools to improve
performance
Build applications for Android Wearables
Capture and preview images using the new
Camera2 API
Android Studio is a new IDE for the Android platform based on IntelliJ IDEA. Using Android Studio,
you will discover value patterns to develop high quality apps using various technologies.
problems efficiently
observe data
real-world problems
P U B L I S H I N G
pl
e
and problems
Android Studio
Cookbook
Design, debug, and test your apps using Android Studio
P U B L I S H I N G
Sa
Preface
Android Studio is the best IDE for developing Android apps, and it is available for free to
anyone who wants to develop professional Android apps.
Now with Android Studio, we have a stable and faster IDE, and it comes with a lot of cool stuff
such as Gradle, better refactoring methods, and a much better layout editor. If you have used
Eclipse, then you will love this IDE.
In short, Android Studio has really brought back the fun of mobile development, and in this
book, we will see how.
Preface
Chapter 7, Content Providers and Observers, explains how you can benefit from using content
providers to display and observe persisting data.
Chapter 8, Improving Quality, elaborates on applying patterns, unit testing, and code
analysis tools.
Chapter 9, Improving Performance, covers how the Device Monitor can be used to optimize
your apps' memory management and how the developer options on your phone can be used
to detect overdraw and other performance issues.
Chapter 10, Beta Testing Your Apps, guides you through some of the final steps such as using
build variants (types and flavors) and beta distribution on the Google Play Store. In addition to
this, it covers how the run time permissions that come with Android Marshmallow (6.0) differ
from the install permissions.
Welcome to
Android Studio
In this chapter, we will cover some basic tasks related to Android Studio. While reading this
and the other chapters, you will learn how to use Android Studio efficiently.
In this chapter, you will learn the following recipes:
Introduction
This chapter is an introduction to Android Studio and provides a helicopter view of the
different tools that come with this Integrated Development Environment (IDE). In addition
to this, some other important tools will be discussed here, such as Genymotion, the emulator
that I highly recommend you to use to test your app on different kinds of devices.
Using Android Studio, you can create any app you like. Apps for phones, phablets, tablets,
watches and other wearables, Google Glass, TV apps, and even auto apps.
If you already have mobile programming experience or even have worked with Android apps
and Eclipse before and you want to discover how to create apps that take pictures, play
media, work on any device, connect to a cloud, or anything else that you can think of,
then this book is for you!
Fragmentation
What has remained is the fragmentation challenge that you need to deal with when it comes to
Android development. There are many devices running on many Android flavors and versions.
There are a lot of Android versions, resulting in fragmentation. Because of this, you cannot
expect that all devices will run on the latest Android version. In fact, most do not. Many
devices still run on Android 4.x (or even older versions), for example.
Chapter 1
Here, you can see a table with all the relevant Android versions and distribution numbers. The
numbers in this table indicate that if you decide to support Android 4.0 and later releases,
you will reach 88.7 percent of all Android users. In this example, the numbers for Q2 2015 are
shown, which explains why Android Marshmallow (6.0) is not being listed here. If you create
a new project in Android Studio, you can get the actual numbers by clicking on a Help me
Choose link in the Create New project wizard dialog, as we will find out in the next chapters.
Let's have a look at the following screenshot which describes the cumulative distribution of
different Android platform version along with their API level:
In addition to software fragmentation, there is also a lot of hardware fragmentation that you
should be aware of. Writing an Android app is not that hard but writing an app that functions
well on any Android device actually is.
A good app should be able to run on as many different devices as possible. For example,
think of an app that takes pictures. Android devices do have a camera or multiple ones or no
camera at all. Depending on other functionalities that your app provides, you might need to
worry about other things as well, such as whether a device is able to record sound or not.
I can imagine you want to reach an audience as large as possible so you should always ask
yourself which of your app feature demands will or will not have to be mandatory. If a device
does not have a camera, the user might not be able to take pictures, but should that really be
a reason for not allowing the user to use the app at all?
Getting ready
To go through this recipe, you will need a running Android Studio IDE, an Android Software
Development Kit (SDK), and an Android device. No other prerequisites are required.
How to do it...
Let's create our first Android app using Android Studio to check whether everything works fine
with the help of the following steps:
1. Start Android Studio. The Welcome to Android Studio dialog will be shown to you
after a few seconds.
2. Select the Start a new Android Studio project option. Then, the Configure your new
project dialog appears.
3. For Application name, enter HelloAndroidStudio; and for the Company domain
field, enter packtpub.com (or use the domain name of your own company if you
prefer to do so).
Chapter 1
4. Package names such as packtpub.com and helloandroidstudio are suggested
and updated while you type. If you wish, you can edit the Project location before you
click on the Next button.
5. In the Target Android Devices dialog box, check the Phone and Tablet option. Leave
the other options unchecked. We will create some of those other interesting targets,
such as an Android Wear app, later. For the Minimum SDK, choose API 14. If that
one is not (yet) available, click on any of the other available SDKs. We will install more
SDKs later. Click on the Next button to continue.
6. In the next dialog box, Add an activity to Mobile, choose the Blank Activity option
and click on the Next button.
7.
The final dialog Customize the activity will be displayed after this. Leave all the
values the way they are and click on the Finish button.
8. Android Studio is now going to create this new app for you. After a while, the project
view, a MainActivity class, and an activity_main.xml layout are displayed. If you
change the perspective of the project view on the left-hand side of your Android
Studio by clicking on the button, that displays the little green Android guy and the text
that reads Android, from Android to Project, the layout will look a little bit more like
you are used to, that is, if you have used Eclipse before.
9. Double-click on the app folder to expand it. You will notice a file called the
build.gradle file (note that this file also exists on the root level).
10. Double-click on the build.gradle file to open it and have a look at the values for
compileSdkVersion, minSdkVersion, and targetSdkVersion. By default, the
compileSdkVersion value is always related to the latest (available) SDK. The value
for minSdkVersion is the one that you have chosen in the Target Android devices
dialog box.
If you want, use a different SDK to compile against; you must
change the value for compileSdkVersion. The version you
choose might need to be installed first. If you are happy with the
current configuration, go to step 14 right away.
12. The Android SDK Manager dialog box displays which SDKs are installed. If you need
to install a different SDK, you can check the elements you need and click on the
Install n packages button.
13. After installing the SDKs that you need and having configured your build.gradle
file, you can now run your app.
14. If you are using a physical device for Android development, you need to unlock the
developer options first. On your device, start the Settings app and go to the Device
info option. (This option may be on the General tab or section or at another place,
depending on the version and flavor of Android that your device is running on).
Chapter 1
If you do not have a real device, I strongly recommend you get one as soon
as possible. To get started, you can use an emulator for now. You can use
the emulator that comes with the Android SDK or you can read the recipe
about Genymotion first to find out how to use emulated devices.
15. In the Device Info view, scroll all the way down until you see the Build number option.
Now, click seven (7) times on Build number to unlock (enable) the developer mode.
(No, this is not a joke). You now have the developer's menu unlocked.
On older Android versions (below 4.2), this step may be skipped,
or if the developer options are already available as a menu item
in the settings app, this step may be skipped.
16. Now that you have got a new option in your Settings app, called Developer options,
click on it and have a look at it. It is important that you enable the USB debugging
option within this menu. In addition, you might want to enable or disable some of the
other options.
17. Connect your device and run your app from Android Studio by clicking on the green
triangle next to the drop-down box that reads the app. Or, choose the Run... option
from the Run menu. Then, the Choose Device dialog box appears. Your device should
now appear in the list of the Choose a running device option. ( If your device does
not appear in the list, reconnect your device).
18. Click on the OK button. (For Windows, before you are able to connect your device, it is
often necessary to install a driver first.)
19. On your device, a dialog box may pop up, requiring you to accept the finger print.
Choose Allow in order to continue.
The app is now being deployed on your device. If everything goes well, your new app is
now shown on your device that says Hello world! Hurrah! I admit this is not really a very
exciting app, but at least we know now that Android Studio and your device have been
configured correctly.
How it works...
Android Studio will take care of the basic parts of your app setup. All you need to do is choose
the target and minimal SDK for your app. Using the API level 14 (Android 4.0) is currently the
best option, as this will allow your app to run on most Android devices.
The app will be compiled against the chosen (compile) SDK by Android Studio.
The app will be copied to your device. Having the USB debugging option enabled will help you
troubleshoot any issues, as we will find out later.
7
The Gradle build system is not something that you need to worry too much about right now.
In later recipes, we will see what the real power of it will be. The system is also designed to
support complex scenarios that may be faced while creating Android applications, such as
handling customized versions of the same app for various customers (build flavors) or creating
multiple APK files for different device types or different Android OS versions.
For now, it is ok just to know that this is the place where we will define compileSdkVersion,
targetSdkVersion, and minSdkVersion, just like we did in the manifest file previously in
case you have been using Eclipse.
Also, this is the place where we define versionCode and versionName, which reflect the
version of your app that is useful if someone is going to update the app you wrote.
8
Chapter 1
Another interesting key element of the Gradle functionality is that of dependencies.
Dependencies can be local or remote libraries and JAR files. The project depends on them
in order to be able to compile and run. In the build.gradle file that you will find in the
previous folder the app folder you will find the defined repository in which the libraries reside.
jCenter is the default repository.
If for example you wish to add the Parse functionality, which is something that we will do in
the recipes found in the next chapter, the following dependency declaration will add the local
Parse library to your project:
dependencies {
compile fileTree(dir: 'libs', include: 'Parse-*.jar')
compile project(':Parse-1.9.1')
}
Using external libraries has become much easier. For example, if you want to add
UniversalImageLoader, a well-known library to load images from the Internet, or if you
want to use the functionality from the Gson library, which basically is an object wrapper
for JSON data, to your app, the following dependency declaration will make these libraries
available to the project:
dependencies {
compile 'com.google.code.gson:gson:2.3+'
compile 'com.nostra13.universalimageloader:universal-imageloader:1.9.3'
}
There's more...
Some other Gradle concepts will be explained in the recipes of the next chapters. Gradle
is a topic that one could write a book about on, and you can find many interesting in-depth
tutorials on the Internet if you would like to know more about it.
See also
For more information about Gradle build scripts, refer to Chapter 2, Applications with
a Cloud-based Backend
Getting ready
Make sure you have Internet access and sufficient space on your hard drive. We will need to
download both VirtualBox and Genymotion. After this, you are ready to create your first virtual
device. Let the magic begin.
How to do it...
Let's install Genymotion to prepare Android Studio to work with smoothly running
emulated devices:
1. Both Oracle's VirtualBox and the Genymotion app need to be installed. This
is because Genymotion virtualizes various Android operating systems using
the virtualization techniques of Oracle Virtual Machine (VM) VirtualBox in the
background. If you do not already have Oracle VM VirtualBox installed on your
computer (or if you have a version of VirtualBox that is below 4.1.1 which is not
compatible with Genymotion), you need to install it first.
Download VirtualBox for OS X hosts (or for Windows) from the VirtualBox download
page at https://www.virtualbox.org/wiki/Downloads.
Install VirtualBox, and after that, reboot your computer.
Download Genymotion from its web page at https://www.genymotion.com/#!/
download.
Chapter 1
4. Select the Android OS version from the drop-down list on the left-hand side of
dialog box.
5. Select a virtual device (brand and model) from the drop-down list on the center and
click on the Next button.
6. Name your device. It's recommended that you include both the device and the OS
version in your device name so what you are testing on can be easily recognized
when you want to use it later.
7.
Click on the Next button to confirm the name. Your virtual device will be created, and
it will appear in the list on the main screen of Genymotion. Create as many virtual
devices as you need.
8. To run a virtual device, select it and click on the Play button. It will launch the
Genymotion emulator so that you can use it together with Android Studio. When it is
launched, you can unlock the device so that it is ready to use.
9. If you hit the Run button in Android Studio again, you will notice that the running
virtual device is shown in the list of available devices in the Choose Device dialog
box. Just click on the OK button to let the magic begin. Your Android app will be
launched on the emulator.
And it is running fast and smooth! Pretty cool, isn't it?
The following is an example of the main screen of Genymotion listing a couple of virtual
devices that have been created:
11
There's more...
Genymotion comes with emulated front and/or backend cameras, depending on the chosen
configuration. To enable them, click on the camera icon. A new dialog box appears in which
you can change the slider to On and choose a real camera for the front and backend camera
of your virtual device.
After selecting a camera, you can close the dialog box. A green checkbox will now appear next
to the Camera button. Now, whenever an app needs to use a camera, it will use the selected
camera, which in my case is the webcam on the laptop. To check whether this is working,
choose the Camera app on the virtual device.
The paid version of Genymotion has additional features available, including emulated
sensors such as GPS and accelerometers. If you like, you can check out the differences
at https://www.genymotion.com/#!/store.
Remember that although using virtual devices for testing purposes works really great with
Genymotion, it is important to always test it on multiple real devices. Some issues, in particular
the ones that are related to memory management that we will see later in this book, are easy to
reproduce on real devices, but may be somewhat harder to reproduce on virtual devices.
In addition to this, real devices are much more pixel perfect and some issues may appear only
on a particular device so when it comes to see how the artwork looks, you are going to need a
couple of them.
By the time your app is nearly complete, you might be interested in the (paid) services from
Testdroid, a cloud-based service that allows to run (automated) tests on many real devices.
Visit www.testdroid.com to learn more about this great service!
12
Chapter 1
The following screenshot provides an example of the Hello Android Studio app running on a
virtual Nexus 5 device using Genymotion:
How to do it
The following steps describe how to rename a method in the Refactor submenu:
1. Highlight the name of the method you would like to rename.
2. From the context menu, choose Refactor.
3. From the submenu, choose Rename (or use the shortcut Shift + F6).
4. Now, you can rename your method or member in place and apply the changes by
hitting the Enter button. Android Studio provides you with some suggestions that you
can accept or you can type the name you want.
If you repeat step 2 and 3, a dialog box appears in which you
can edit the name. (Or use the shortcut Shift + F6 twice).
5. Click on the Preview button to see what the effect of the renaming will be.
6. At the bottom of your screen, a new view appears, which shows you the impact of the
renaming in each file (class, resource, or otherwise).
7.
14
Click on the Do refactor button in that view to apply all the changes.
Chapter 1
The following screenshot shows an example of an in-place refactoring (renaming).
How it works...
Android Studio will take care of renaming a method or member and any references to it
everywhere in the project. This includes Java classes, layouts, drawables, and anything else
that you can think of.
There are many other interesting options available from the Refactor menu that you can use.
Some of them will be discussed in the next chapters in the recipes where they will come
in handy.
Now, let's move on to the next chapter and build a real app, shall we?
See also
For more information about refactoring code, refer to Chapter 8, Improving quality.
15
www.PacktPub.com
Stay Connected: