34,79 €
Kotlin is a programming language intended to be a better Java, and it's designed to be usable and readable across large teams with different levels of knowledge. As a language, it helps developers build amazing Android applications in an easy and effective way.
This book begins by giving you a strong grasp of Kotlin's features in the context of Android development and its APIs. Moving on, you'll take steps towards building stunning applications for Android. The book will show you how to set up the environment, and the difficulty level will grow steadily with the applications covered in the upcoming chapters.
Later on, the book will introduce you to the Android Studio IDE, which plays an integral role in Android development. We'll use Kotlin's basic programming concepts such as functions, lambdas, properties, object-oriented code, safety aspects, type parameterization, testing, and concurrency, which will guide you through writing Kotlin code in production. We'll also show you how to integrate Kotlin
into any existing Android project.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 299
Veröffentlichungsjahr: 2017
BIRMINGHAM - MUMBAI
Copyright © 2017 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: November 2017
Production reference: 1061117
ISBN 978-1-78847-369-9
www.packtpub.com
Author
Miloš Vasić
Copy Editor
Zainab Bootwala
Reviewer
Vanja Petkovic
Project Coordinator
Prajakta Naik
Commissioning Editor
Richa Tripathi
Proofreader
Safis Editing
Acquisition Editor
Sandeep Mishra
Indexer
Francy Puthiry
ContentDevelopmentEditor
Akshada Iyer
Graphics
Jason Monteiro
Technical Editor
Supriya Thabe
Production Coordinator
Arvindkumar Gupta
Miloš Vasić is a software engineer, author, and open source enthusiast. He holds a bachelor's degree in the programming of computer graphics and a master's degree in the field of Android programming; both degrees were gained at Singidunum University. He published his first book, Fundamental Kotlin, in October 2016, thus achieving his dream of becoming an author. He's currently employed at the Robert Bosch company, where he's working on SDKs for the auto-industry. When he is not working on new books, Miloš works on his open source projects.
This book has been a long and fun journey that I would not have manage to accomplish without help. So I think it's only polite to give gratitude.
First of all, I would like to thank my girlfriend and personal assistant, Maja. She was the one who supported me and helped me while writing my first book Fundamental Kotlin and continued to do so with this one. She improved this book greatly by helping me write coherent text that is understandable even for those who are not experienced in programming.
Next I would like to thank my editor at Packt Akshada. She was the best editor I could ask for and she helped me immensely with excellent advices and endless patience. The whole team at Packt that stands behind was book was incredibly supportive and helpful.
Big thanks also to my friends who tolerated me and constantly filled me up with large amounts of coffee. Especially to my friend Vanja Petkovic. He was the technical editor for this book and it wouldn't be the same without him.
And last but not least I would like to thank to my family for supporting me in my dream of becoming software engineer. They were with me and they were patient during all my phases! But, the most important of all, they believed in me!
None of this would be possible if there weren't people who read my first book. I am forever grateful for their support. See you in my next book!
Best wishes,
Miloš
Vanja Petkovic studied math and computer science at Belgrade University, Serbia. There, he also obtained his MSc in computer science. He has been working as a software engineer for more than 13 years. Currently, he lives in Switzerland and works for Leica Geosystems in the 3D scanning department. He has specialized in software development for mobile devices and backend services. He started with software development for Palm OS, through Windows Mobile OS and Blackberry OS to Android OS and iOS today. His preferred weapons for developing backend services are Java and Spring.
For support files and downloads related to your book, please visit www.PacktPub.com.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/1788473698. If you'd like to join our team of regular reviewers, you can e-mail us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
Starting with Android
Why Kotlin?
Kotlin for Android - it's official
Downloading and configuring Android Studio
Setting up Android emulators
Creating a new AVD instance
Duplicating an existing AVD and modifying it by need
Android Debug Bridge
Other important tools
Initializing a Git repository
Creating an Android project
Setting up Gradle
Explaining directory structure
Defining build types and flavors
Additional libraries
Getting familiar with Android Manifest
Main Application class
Your first screen
Summary
Building and Running
Running your first Android application
Meet the Logcat
First case
Using the Gradle build tool
Debug your application
Summary
Screens
Analyzing the mockup plan
Defining application activities
Android layouts
Using EditText views
The margins attribute
The padding attribute
Checking out the gravity attribute
Looking at other attributes
Understanding Android Context
Understanding fragments
Fragment manager
Fragments stack
Creating View Pager
Making animations with transitions
Dialog fragments
Notifications
Other important UI components
Summary
Connecting Screen Flow
Creating an application bar
Using the navigation drawer
Connecting activities
Looking deeper into Android Intents
Passing information between activities and fragments
Summary
Look and Feel
Themes in the Android Framework
Styles in Android
Working with assets
Using custom fonts
Applying coloring
Make your buttons look pretty
Setting animations
Animation sets in Android
Summary
Permissions
Permissions from Android Manifest
Requesting permissions
Doing it the Kotlin way
Summary
Working with Databases
Introduction to SQLite
Benefits
Describing our database
CRUD operations
Insert CRUD operation
Update CRUD operation
Delete CRUD operation
Select CRUD operation
Tying things together
Summary
Android Preferences
What are Android preferences?
How can you use them?
Editing (storing) preferences
Removing preferences
Defining your own preferences manager
Summary
Concurrency in Android
Introduction to Android concurrency
Main thread
Handlers and threads
AsyncTask
Understanding Android Looper
Preparing the Looper
Delayed execution
Summary
Android Services
Service categorization
Foreground Android services
Background Android services
Bound Android services
Android service basics
Declaring your service
Starting the service
Stopping the service
Binding to Android service
Stopping the service
Service lifecycle
Defining the main application service
Defining the intent service
Summary
Messaging
Understanding Android broadcasts
System broadcasts
Listening for broadcasts
Registering from the context
Receivers execution
Sending broadcasts
Creating your own broadcast messages
Using on boot and on shutdown broadcasts
Listening for network events
Summary
Backend and API
Identifying entities used
Working with data classes
Connect data models to a database
Introduction to Retrofit
Defining Retrofit service
Building a Retrofit service instance
Introduction to Gson with Kotson library
What else is available?
Retrofit alternative
Gson alternative
Executing our first API call
Content providers
Android adapters
Content loaders
Data binding
Using lists
Using grids
Implementing drag and drop
Summary
Tuning Up for High Performance
Optimizing layouts
Optimizing battery life
Keeping your application responsive
Summary
Testing
Adding dependencies
Updating folder structure
Writing your first test
Using test suites
How to test UI
Running tests
Running unit tests
Running instrumentation tests
Summary
Migration to Kotlin
Preparing the migration
Danger signs
Updating dependencies
Converting classes
Refactoring and cleanup
Summary
Deploying Your Application
Preparing for deployment
Code obfuscation
Signing your application
Publishing to Google Play
Summary
Android is the most popular platform for mobile devices. Every year, there are more and more developers getting involved in Android development. The Android Framework makes it possible to develop applications for mobile phones, tablets, televisions, and much more! So far, all development has been done in Java. Recently, Google announced Kotlin as the second language developers can use. Because of this, and with Kotlin's ever-growing popularity, we decided to introduce you to Android using Kotlin as its primary development programming language.
With Kotlin, you can do everything you can do with Java, but with more joy and fun! We will show you how to play with Android and Kotlin, and how to create amazing things! Thanks to Kotlin, it's certain that the Android platform will evolve even more. In the near future, it's not impossible that Kotlin will become the primary development language for the platform. Take your seat and get ready for a great journey!
Chapter 1, Starting with Android, teaches you how to start Android development with Kotlin and how to set up your working environment.
Chapter 2, Building and Running, shows you how to build and run your project. It will demonstrate how to log and debug the application.
Chapter 3, Screens, starts with the UI. In this chapter, we will create the first screens for our application.
Chapter 4, Connecting Screen Flow, explains how to connect the screen flow and define basic user interaction with the UI.
Chapter 5, Look and Feel, covers the theming of the UI. We will introduce you to the basic concepts of theming in Android.
Chapter 6, Permissions, explains that in order to take advantage of certain system functionalities, it's necessary to get proper system permissions, which are discussed in this chapter.
Chapter 7, Working with Databases, shows you how to use SQLite as storage for your application. You will create a database to store and share data.
Chapter 8, Android Preferences, states that not all data should be stored in the database; some information can be stored in shared preferences. We will explain why and how.
Chapter 9, Concurrency in Android, explains that if you are familiar with concurrency in programming, then you will know that, in software, many things happen simultaneously. Android is not an exception!
Chapter 10, Android Services, presents Android services and how to use them.
Chapter 11, Messaging, says that in Android, your application can listen for various events. How to do this will be answered in this chapter.
Chapter 12, Backend and API, connects to the remote backend instance to obtain the data.
Chapter 13, Tuning Up for High Performance, is the perfect chapter to give you answers when you are not sure if your application is fast enough.
Chapter 14, Testing, mentions that before we release anything, we must test it. Here, we will explain how to write tests for your application.
Chapter 15, Migration to Kotlin, guides you if you plan to migrate the existing Java code base into Kotlin.
Chapter 16, Deploying Your Application, guides you through the deployment process. We will release everything we develop during this book.
For this book, a modern computer running Microsoft Windows, Linux, or macOS is required. You will need Java JDK, the Git version-control system, and Android Studio installed.
To run all code examples and the code you write, you will need an Android phone running Android with OS version >= 5.
The book is aimed at developers who want to build amazing Android applications in an easy and effective way. Basic knowledge of Kotlin is assumed, having no familiarity with Android development.
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, and user input are shown as follows: "We will add proper log messages for each lifecycle event of the Application class and the screen (activity) we created."
A block of code is set as follows:
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) Log.v(tag, "[ ON CREATE 1 ]") }
Any command-line input or output is written as follows. The input command might be broken into several lines to aid readability, but needs to be entered as one continuous line in the prompt:
sudo apt-get install libc6:i386 libncurselibstdc++6:i386 lib32z1 libbz2-1.0:i386
New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: " SelectTools|Android|AVDManageror click on theAVDManagericon in the toolbar."
Feedback from our readers is always welcome. Let us know what you think about this book--what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
Log in or register to our website using your e-mail address and password.
Hover the mouse pointer on the
SUPPORT
tab at the top.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box.
Select the book for which you're looking to download the code files.
Choose from the drop-down menu where you purchased this book from.
Click on
Code Download
.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR / 7-Zip for Windows
Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/-Mastering-Android-Development-with-Kotlin/branches/all. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/MasteringAndroidDevelopmentwithKotlin_ColorImages.pdf.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books--maybe a mistake in the text or the code--we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata</span> section.
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at [email protected] with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.
Kotlin has been officially announced by Google as a first-class programming language for Android. Find out why Kotlin is the best tool available for you as a newcomer and why senior Android developers first adopted Kotlin.
In this chapter, you will learn how to set up a working environment. You will install and run Android Studio and set up Android SDK and Kotlin. Here, you will also be introduced to some important and useful tools such as Android Debug Bridge (adb).
Since you don't have your project yet, you will set it up. You will initialize a Git repository to track changes in your code and create an empty project. You will enable it to support Kotlin and add support for additional libraries that we will use.
After we have initialized the repository and project, we will go through the project structure and explain each file the IDE has generated. Finally, you will create your first screen and take a look at it.
This chapter will cover the following points:
Setting up an environment for the development of Git and Gradle basics
Working with Android Manifest
Android emulator
Android tools
Before we start our journey, we will answer the question from the chapter title--Why Kotlin? Kotlin is a new programming language developed by JetBrains, the company that developed IntelliJ IDEA. Kotlin is concise and understandable, and it compiles everything to bytecode just like Java. It can also compile to JavaScript or native!
Kotlin comes from professionals of the industry and solves problems programmers are facing every day. It is easy to start and adopt! IntelliJ comes with a Java to Kotlin converter tool. You can convert Java code file by file and everything will still work flawlessly.
It is interoperable and can use any existing Java Framework or library. The interoperability is impeccable and does not require wrappers or adapter layers. Kotlin supports build systems such as Gradle, Maven, Kobalt, Ant, and Griffon with external support.
The most important thing about Kotlin, for us, is that it works perfectly with Android.
Some of the most impressive Kotlin features are as follows:
Null safety
Exceptions are unchecked
Type inference works everywhere
One-liner functions take one line
Generated getters and setter out of the box
We can define functions outside of classes
Data classes
Functional programming support
Extension functions
Kotlin uses Markdown instead of HTML for API documents! The Dokka tool, a Javadoc alternative, can read Kotlin and Java source code and generate combined docs
Kotlin has a better generics support than Java
Reliable and performant concurrent programming
String patterns
Named method arguments
On May 17th 2017, Google announced that it's making Kotlin, a statically typed programming language for the Java Virtual Machine, a first-class language to write Android apps.
The next version of Android Studio (3.0, current one is 2.3.3) will support Kotlin out of the box. Google will put its effort in the future of Kotlin.
To develop our application, we will need some tools. First of all, we will need an IDE. For that purpose, we will use Android Studio. Android Studio provides the fastest tools to build apps on every type of Android device.
Android Studio offers professional code editing, debugging, and performance tooling. It's a flexible build system that allows you to focus on building a top quality application.
Setting up Android Studio takes just a few clicks. Before we go any further, you need to download the following version for your operating system:
https://developer.android.com/studio/index.html
Here are the instructions for macOS, Linux, and Windows:
macOS: To install it on macOS, follow these steps:
Launch the Android Studio
DMG
file.
Drag and drop Android Studio into the
Applications
folder.
Launch Android Studio.
Select whether you want to import previous Android Studio settings.
Click on
OK
.
Follow the instructions until Android Studio is ready for use.
Linux:To install it on Linux, follow these steps:
Unpack the archive you downloaded to an appropriate location for your applications.
Navigate to
bin/directory/
.
Execute
/studio.sh
.
Select whether you want to import previous Android Studio settings or not.
Click on
OK
.
Follow the instructions until Android Studio is ready for use.
Optionally, select
Tools
|
Create Desktop Entry
from the menu bar.
Windows:To install it on Windows, follow these steps:
Execute the
.exe
file you downloaded.
Follow the instructions until Android Studio is ready for use.
Android SDK comes with emulators capable of running applications we develop. We will need it for our project! The purpose of an emulator is to simulate a device and displays all its activity windowed on your computer. What can we do with it? We can prototype, develop, and test--all this without a hardware device. You can emulate phones, tablets, wearables, and TV devices. You can create your own device definitions, or you can use predefined emulators.
The good thing about emulators is that they are fast. In many situations, it will take less time to run an application on an emulator instance than on a real hardware device.
Working with the emulators is just as easy with a real hardware device. For gestures, you use your mouse, and for input, your keyboard.
Emulators can do anything a real phone does! You can easily send incoming phone calls and text messages! You can specify the location of the device, send fingerprint scans, adjust network speed and status, or even simulate battery properties. Emulators can have a virtual SD card and internal data storage, both of them you can use to send real files to that space.
Android Virtual Device (AVD) configuration is used to define an emulator. Each AVD instance works as a completely independent device! For the purpose of creating and management of AVDs, we use the AVD Manager. An AVD definition holds a hardware profile, system image, storage area, skin, and other important properties.
Let's play with it! To run the AVD Manager, do one of the following:
Select Tools | Android | AVDManager or click on the AVDManager icon in the toolbar:
It displays all AVDs you've already defined. As you can see, we don't have any yet!
What can we do here? We can do the following:
Create a new AVD
Edit an existing AVD
Delete the existing AVD
Create hardware profiles
Edit an existing hardware profile
Delete an existing hardware profile
Import/export definitions
Start or stop the AVD
Clear data and reset the AVD
Access the AVD
.ini
and
.img
files on the filesystem
View the AVD configuration details
To obtain the AVD instance, you can either create a new AVD from the beginning or duplicate an existing AVD and modify it by need.
From the Your Virtual Devices of the AVD Manager, click on Create Virtual Device (you can do the same as you run your app from within Android Studio by clicking on the Run icon, and then, in the Select Deployment Target dialog, choose Create New Emulator). Please refer to the following screenshot:
Select a hardware profile and then click on Next, as shown in the previous screenshot.
If you notice the Download link next to the system image, you have to click on it. The download process starts, as you can see in the following screenshot:
We must note that the API level of the target device is very important! Your application can't run on a system image whose API level is less than the one required by your application. That attribute is specified in your Gradle configuration. We will deal with Gradle in detail later.
Finally, Verify Configuration appears:
Change the AVD properties if needed and then click on Finish to complete the wizard. The newly created AVD appears in the Your Virtual Devices list or the Select Deployment Target dialog, depending on where you accessed the wizard from.
If you need to create a copy of the existing AVD, follow these instructions:
Open AVD Manager, right-click on the AVD instance, and select
Duplicate
.
Follow the wizard, and, after you modified what you needed, click on
Finish
.
A new modified version appears in our AVD list.
We will demonstrate dealing with hardware profiles by creating a new one from scratch. To create a new hardware profile, follow these instructions. In Select Hardware, click on New Hardware Profile. Please refer to the following screenshot:
Configure Hardware Profile appears. Adjust the hardware profile properties as needed. Click on Finish. Your newly created hardware profile appears.
If you need a hardware profile based on an existing one, follow these instructions:
Select an existing
hardware profile
and click on
Clone Device
.
Update the
hardware profile
properties by your needs. To complete the wizard, click on
Finish
.
Your profile appears in the
hardware profile
list.
Let's go back to the AVD list. Here, you can perform the following operations on any existing AVD:
Edit it by clicking on
Edit
Delete by right-clicking and choosing
Delete
Access the
.ini
and
.img
files on the disk by right-clicking on an AVD instance and choosing
Show on Disk
To view the AVD configuration details, right-click on an AVD instance and choose
View
Details
Since we covered this, let's go back to the hardware profile list. Here, we can do the following:
Edit a hardware profile by selecting it and choosing
Edit Device
Delete a hardware profile by right-clicking on it and choosing
Delete
Then, we can run or stop an emulator or clear its data as follows:
To run an emulator that uses an AVD, double-click on the AVD or just choose
Launch
To stop it, right-click on it and choose
Stop
To clear the data for an emulator, and return it to the same state as when it was first defined, right-click on an AVD and choose
Wipe Data
We will continue our emulators' journey with the explanation of command-line features that you can use with *-.
To start an emulator, use the emulator command. We will show you some basic command-line syntax to start a virtual device from a terminal:
emulator -avd avd_name [ {-option [value]} ... ]
Another command-line syntax is as follows:
emulator @avd_name [ {-option [value]} ... ]
Let's take a look at the following example:
$ /Users/vasic/Library/Android/sdk/tools/emulator -avd Nexus_5X_API_23 -netdelay none -netspeed full
You can specify startup options when you start the emulator; later, you can't set these options.
If you need a list of available AVDs, use this command:
emulator -list-avds
The result is a list of AVD names from the Android home directory. You can override the default home directory by setting the ANDROID_SDK_HOME environment variable.
Stopping an emulator is simple--just close its window.
To access devices, you will use the adb command executed from the terminal. We will take a look into the common cases.
Listing all devices:
adb devices
Console output:
List of devices attached
emulator-5554 attached
emulator-5555 attached
Obtaining shell access to device:
adb shell
Accessing a specific device instance:
adb -s emulator-5554 shell
Where -s represents device source.
Copying a file from and to a device:
adb pull /sdcard/images ~/images
adb push ~/images /sdcard/images
Uninstalling an application:
adb uninstall <package.name>
One of the greatest features of adb is that you can access it through telnet. Use telnet localhost 5554 to connect to your emulator device. Terminate your session using the quit or exit command.
Let's play with adb:
Connect to device:
telnet localhost 5554
Change the power level:
power status full
power status charging
Or simulate a call:
gsm call 223344556677
Send an SMS:
sms send 223344556677 Android rocks
Set geolocation:
geo fix 22 22
We will cover some other tools you will need in everyday Android development.
Let's start with the following:
adb dumpsys
: To get information about a system and running an application, use the
adb dumpsys
command. To get a memory status, execute the following command--
adb shell dumpsys meminfo <package.name>
.
Next important tool is as follows:
adb shell procrank
: The
adb shell procrank
lists all the applications for you in the order of their memory consumption. This command does not work on live devices; you connect only with emulators. For the same purpose, you can use--
adb shell dumpsys meminfo
.
For battery consumption, you can use--
adb shell dumpsys batterystats
--charged
<package-name>
.
Next important tool is
Systrace
. To analyze performance of your application by capturing and displaying execution times, you will use this command.
When you have problems with application glitches, Systrace tool comes as a powerful ally!
It does not work with Android SDK Tools less than 20! To use it, you must have Python installed and configured.
Let's try it!
To access it from UI, open Android Device Monitor in Android Studio and then choose Monitor:
Sometimes, it can be easier to access it from the terminal (command line):
Let's take a look at some examples:
General usage:
$ python systrace.py [options] [category1] [category2] ... [categoryN]
Android 4.3 and up:
$ python systrace.py --time=15 -o my_trace_001.html sched gfx view wm
Android 4.2 and lower options:
$ python systrace.py --set-tags gfx,view,wm
$ adb shell stop
$ adb shell start
$ python systrace.py --disk --time=15 -o my_trace_001.html
The last important tool we want to present is sdkmanager. It allows you to view, install, update, and uninstall packages for the Android SDK. It is located in android_sdk/tools/bin/.
Let's take a look at some common examples of use:
Listing installed and available packages:
sdkmanager --list [options]
Installing packages:
sdkmanager packages [options]
You can send packages you got from --list command.
Uninstalling:
sdkmanager --uninstall packages [options]
Updating:
sdkmanager --update [options]
There are also some other tools you can use in Android, but we only showed the most important ones.
We have installed Android Studio and introduced ourselves to some important SDK tools. We also learned how to deal with emulated devices that will run our code. It is time to start working on our project. We will develop a small application for notes and todos. This is a tool that everybody needs. We will give it a name--Journaler and it will be an application capable of creating notes and todos with reminders that will be synced to our backend.
First step in development is initializing a Git repository. Git will be our code versioning system. It is up to you to decide if you will use GitHub, BitBucket, or something else for a remote Git instance. Create your remote repository and keep its URL ready, along with your credentials. So, let's start!
Go into the directory containing the project:
Execute: git init .
The console output will be something like this:
Initialized empty Git repository in <directory_you_choose/.git>
We initialized the repo.
Let's add the first file--vi notes.txt.
Populate notes.txt with some content and save it.
Execute git add . to add all of the relevant files.
Then:
git commit -m "Journaler: First commit"
The console output will be something like this:
