“But when does the Android version come out?”
–The first blog comment after any iOS app gets announced.
–The first blog comment after any iOS app gets announced.
Clearly there’s a demand for Android app development, and it’s turning the platform with the lovable green mascot into more and more of a strong first choice rather than just a secondary option to iOS.
With over one billion devices activated, Android is an exciting space to make apps to help you communicate, organize, educate, entertain or anything else you’re passionate about.
If that’s not enough, here are a few more reasons to learn Android:
- You’ll be plugged into the open source platform with (at the time of press) thelargest market share of smart devices worldwide.
- Android’s policies on device provisioning and app submission are more open than Apple’s, meaning that once you complete your first app—as you’ll do in this tutorial—you and your friends can enjoy it on your devices right away!
- If you have experience developing for iOS, you can become well-versed in the ways that the two platforms coincide and differ (we’ll discuss a few in this tutorial) and what you like about each. Then you’ll have more tools at your disposal for your next mobile project.
- It’s not just the iPhone anymore. There are so many smartphones, tablets, glasses, and watches out there, coming from so many manufacturers, and they’re all trying to jump into the game. You don’t have to be any sort of market analyst to know that there are a few important platforms and Android is one of them.
So if you’ve been intent on, thinking about, or simply playing with the idea of learning Android… Make Your First Android Appis the tutorial series for you!
There aren’t any prerequisites to start. You’ll learn how to set up all the tools you need to become an Android developer-in-training. Then you’ll put together your own full-fledged Android app from scratch! This app will, when completed, help you get details about a book you’re interested in using online search sources.
By the end of Part Three of this series, your app will include useful features like:
- Saving app data locally on the phone.
- Loading and interacting with a dynamic list of data.
- Accessing an online data source.
- Sharing links through social networks.
Android, and several popular frameworks for it, make all of these features really simple to implement. Why not start learning this easy and powerful platform for yourself, today?
Getting Started
How does Android development go down? First, the zoomed-out basics:
- You’ll write your programming—what you want your app to do—in Java files and design your layouts—how you want your app to look—in XML files.
- Once your app is ready, you’ll use a build tool to compile all the project files and package them together into a
.apk
file that you can run on Android devices and/or submit to Google Play. - All of the files you used to put your app together are managed by an Integrated Development Environment (IDE). The IDE is the program you will open to edit your code files and to manage your projects.
- The standard IDE for Android used to be Eclipse, but this is now being replaced by Google’s own Android Studio.
If you zoom in (metaphorically), you’ll find more in-depth processes going on behind the scenes during all of the above steps. For example, advanced users will want to investigate the role of the Dalvik Virtual Machine and it’s new replacement, ART.
But for now, let’s move on. Here’s what you’re going to accomplish in this part of the tutorial:
- Download and install Android Studio.
- Set up testing on devices and emulators.
- Create a simple “Hello World!” Android app that prints to your device’s screen.
- Make small edits to the app so it can congratulate you by name.
In the second part of this tutorial, you’ll make an app that records a message you type, adds it to a list, saves it in memory and shares it with friends. Along the way, you’ll learn how to add and configure various UI elements such as
ImageView
s,Button
s, ListView
s, and EditText
controls.
Finally, the third part will cover how to make an app to search an online database of books, display and share the cover images of the search results, and navigate between the different screens of your new app!
Installing Android Studio
It’s really tempting to jump in, start writing code right away and figure out the various Android features as quickly as possible. And you will get there soon! But one of the most important parts of getting started with a new platform is setting up your environment.
Especially for beginners, it’s important to take your time here and follow each step methodically. Even if you follow the steps perfectly, you may have to troubleshoot some small issue, depending on your system configuration or product versions.
It’s important to not let any roadblocks prevent you from your ultimate goal of learning Android. Even seasoned professionals have been known to have some trouble with the new Android Studio.
Note: Just as much as you’re training in programming syntax and frameworks, it’s important to train yourself to have a successful programming mindset — one that won’t accept
file X not found
as a final answer. 90% of this mindset is simply training yourself to keep trying till you find a solution.
With all of this in mind, let’s quickly check that you have the Java Development Kit (JDK) installed. You might already, even if you don’t know for sure.
To check, you’ll use the Terminal. If you’re unfamiliar with the Terminal, you may want to read a good introductory tutorialabout working with the Terminal.
In a nutshell, your Terminal is like looking under your car’s hood. It’s how you really get to know the machine face-to-face, without any complex graphical interface in the middle. You can find the Terminal app quite easily on a Mac using Spotlight. Search for terminal and click the top hit to run Terminal.
Once you have the Terminal open, type in
java -version
. You should see some output that mentions a version number, like below.
If you don’t have the JDK installed, your Terminal will tell you
command not found
. If that’s the case, you should download the JDK from Oracle.
When ready, head over to the Android Studio page and click the big green button to download the correct version for your Operating System.
Google is constantly updating this page, so the version you see may be newer than the screenshot above. Once you have clicked the button you’ll be asked to agree to the Terms and Conditions:
After reading these carefully (as you always do) accept the Terms and Conditions and click the blue button underneath titledDownload Android Studio. Your download will finally begin. It may take a few minutes but once finished you can install Android Studio similar to any other program.
The download page will helpfully redirect to a webpage that contains installation instructions for OSX, Windows and Linux Operating Systems. If for some reason the instructions don’t appear then you can also view them here.
Now that you’ve installed Studio, let’s fire it up! Launch Android Studio.
Once Android Studio has finished loading, you’ll be greeted with the Setup Wizard the first time Studio loads.
Click Next to move to the next screen. This screen will ask what type of setup you would like. Make sure Standard is checked and click Next again to move to the next screen to accept some licenses for components that will be installed on your computer.
Accept these and click Next one last time to begin downloading the extra components you will need.
After a few minutes you will have everything you need to begin building fantastic Android Apps and will move to the welcome screen.
Even though you just downloaded Android Studio, you might not actually have the latest version. Right away, you need to check to see if any updates are available and if necessary, follow any instructions to get the latest version. You can check whether any updates are available by clicking check for updates at the bottom of the welcome screen.
If an update is available you will have a window like this appear:
When you see this screen. Always choose Update and Restart. In some cases, you may need to download the full installer – in that case you will see a Download button that will take you to instructions for installing.
Great! As all programmers in the movies say when they are successfully greeted with a new interface: We’re in!
Optional/Advanced: Moving from Eclipse
You can skip to the next section if you are new to Android development.
Android Studio is a new IDE that Google is constantly updating. If you are already involved in Android development, you are probably using Eclipse. For the transition, the Android team has put together a helpful guide on how to move from Eclipse to Studio.
The process can still be a little bumpy, even for advanced users, so the best advice I can offer on that front is to make sure that your version of Gradle is up-to-date, as well as your versions of the Android Platform Tools and Studio itself.
It’s also important to check the
PATH
of your Android software development kit (SDK) when switching to Studio. Otherwise, Studio may not be able to find the right Android SDK or Build Tools!The Android SDK Manager
Each version of Android has it’s own SDK you can use to build apps that can run on. As part of the Setup Wizard you will already have the latest SDK available to you, however it’s useful to know how to install additional SDK’s if you need to work with older devices that do not run the latest version of Android.
SDK’s allow you to create AVD’s (Android Virtual Devices) to test your Apps on, customized to your personal configuration. Want to see how your Android App looks on a TV sized screen? If you have a screen big enough you can find out. More on AVD’s later.
Lets get to it. From the Android Studio welcome screen, click Configure.
The menu will slide across and present a new menu with various options. The option you want is the SDK Manager. This is the go to place if you need to download a specific version of Android to develop or test your app on. It also contains other useful things such as API documentation, version specific code samples and even previews of software kits that interact with Android such as Android Wear and Google Glass.
For now lets focus on downloading a version of the Android SDK. Click the SDK Manager option, a new window will present itself to you with checkboxes, folders and statuses across the page.
Lets make some sense of this. Each folder is a directory of tools, software and documentation. The majority of directories are specific to an SDK version of Android but there are some that cater to multiple versions. The first folder for example, entitledTools, is a folder that contains components that are designed to assist in the development of Android and work across multiple SDK’s.
The Android 5.0 (API 21) directory on the other hand holds everything specific to that version of the Android SDK. Including sample code for new features within the SDK, API documentation and system images you can use to simulate a certain mobile architecture using an AVD.
If you don’t understand what all this means then don’t worry, just think of each folder as a place where each version of Android and their tools live happily. From the latest preview version right down to the original Android Beta (API 2).
You should already have the latest version of the Android SDK Tools, Android SDK Platform-tools and Android SDK Build-tools downloaded from the tools directory. If an update for any of these tools is available then the checkbox next to the tool will automatically be ticked, alongside a polite message in the Status column of the window telling you what the latest version is.
For now lets download the previous version of Android, that being Android 4.4.2 (API 19).
Click the tick box next to the folder icon for Android 4.4.2, this will select everything within that directory for download. You can always come back to the SDK Manager to delete anything you don’t use.
Important: It’s alway worth opening the SDK Manager every time you start Android Studio to see if there is any updates to any tools or SDKs you have installed. This ensures you get access to the latest features in your alongside any fixes for nasty bugs.
Your SDK Manager window should look something like this:
Click Install x packages (x being the amount of packages checked for download) on the bottom right of the SDK Manager. A new window will appear with a drop down list of the packages you wish to install, simply click the root of the drop down list and then click the Accept License radio button in the bottom right.
You may need to do this for multiple licenses depending on what packages you download.
Finally, click the install button at the very bottom right of the window to begin your download.
The window will disappear and the SDK Manager will begin to download and install your selected items. Go grab a drink and take in what you’ve just done whilst the SDK Manager is ticking away. This will become a regular task that you need to get accustomed to so you can quickly acquire and update the various SDK’s you want to work with.
Once the SDK Manager has finished downloading and installing your items you can move onto creating your first Android App!
Creating OMG Android
It’s time. Let’s make your first project.
You’ll start simple. Many first programs are called “Hello World.” Let’s follow that tradition and then make a few small edits so that the app uses your name to greet you. By the end, you’ll be able to load your new app onto a device and show it to your friends!
Android Studio has a nice little step-by-step tool to help you make your project. Click Start a new Android Studio Projectfrom the Welcome to Android Studio screen:
Note: If you currently have an Android Studio project open and the Welcome screen isn’t showing, select File\New Project from the menu to create a new project.
Studio will present you with your first project creation screen:
Enter OMG Android in Application name as shown above. Feel free to put your own name in the Company Domaintextfield. As you type, you’ll notice the Package Name will automatically change to create a reverse domain style name based on your Application name and Company Domain.
The Package Name is used to uniquely identify your app amongst other apps, that way any work an Android device has to be perform on behalf of the app always knows its source and can’t get confused between two apps. iOS developers will recognize this concept as being similar to the Bundle Identifier.
You can set the Project location to any location on your hard drive – you do not need to follow the screenshot for that one :]
Click Next at the bottom of the window to progress to the next part of the project setup.
The next screen is where you select device types and operating systems to target. Want an App to focus on just Phone and Tablet? Not a problem! How about an App for TV and Google Glass? Thats great too. For now though you just want an App that works on an Android Phone. This option is selected as the default, alongside the default Minimum SDK.
The Minimum SDK drop down menu sets the minimum version of Android needed to run your app. Selecting this value for your own projects is a matter of balancing the SDK capabilities you want and the devices you want to support.
For your first app, you’ll use the default – API 16, which is Android 4.1 (Jelly Bean). Every app will have different requirements and you may want to choose something else, depending on the situation.
If you really want to get into the details of what Minimum SDK version is best for your App then Android Studio can help you out. As you change the Minimum SDK in the drop down menu, the percentage in the text underneath reflects what percentage of devices currently run that version of Android.
If you are more about features than numbers, Android Studio has got your back too. Click the highlighted Help me chooseunderneath the drop down list to display a useful new window.
What you are looking at is a bar chart, split by the amounts of devices running a specific version of Android. Click on any part of the bar and the text to the right will change, telling you the most significant features of the Android Version that part of the bar represents. Useful if you need a quick overview of what each version of Android provides for your App.
Take note of the Cumulative Distribution values on the right of the bar. This represents the percentage of devices supporting that particular version of Android – which includes backwards compatibility. As you descend down the bar, the version of Android increases and you gain more features that your App can make use of. The downside to this is the amount of devices that can actually run your App is reduced.
Picking what Minimum SDK your App will require is a crucial choice. It will influence what features you have available to you in your project while also influencing how many Android users can run your App. Choose wisely!
For more information on API versions and their use, check out the Android Dashboards, which are updated every few days.
Getting back to the new project window, click Next in the bottom right to pick more options for your project.
This screen lets you choose a default
Activity
for your app. Think of an Activity as a window within your App that displays content the user can interact with – not unlike a View Controller in iOS. An activity can take up the entire screen or it could be a simple pop-up.
Available activities on this template range from a blank activity with an Action Bar right up to an Activity with a
MapView
embedded. You will be making a lot of activities, so it’s good to get accustomed with them.
Select the Blank Activity option and click Next.
If you have made it this far then well done, you are at the final screen before you dig into some actual coding. To speed this part up a little bit you will use the pre-populated default values, but what is actually done with these values?
- Activity Name. This will give your
Activity
a name to refer to in code. Once the project setup is complete Android Studio will create a .java class and use the contents of this textfield to give the class a name. This is the name you will use to refer to your Activity inside your code.Note: What it’s actually doing is making a subclass ofActivity
. Those familiar with object-oriented programming will know what this is, but for newcomers, this basically means that yourMainActivity
is going to be a customized version ofActivity
that acts just like the default one, handling things like its lifecycle and the user interface display. - Layout Name. You’re going to define your
Activity
in Java, but the layout of everything it will show to the user is defined in a special sort of Android XML. You will learn how to read and edit those files shortly.
Click Finish. Android Studio takes this as its cue to go do a bunch of behind-the-scenes operations and create your project. As it shoots out some descriptions of what it’s doing from time to time, you may notice it say something like the following:
You see your project name, which is familiar. But then there is this Gradle word, and then a mention of Maven in the URL. The benefit of having a modern IDE like Android Studio is that it handles a lot for you. But as you’re just beginning to learn how to use the software, it’s good to know, in general, what it’s doing for you.
- Gradle is a new build tool that is easy to use, but it also contains a lot of advanced options if you investigate it further. It takes your Java code and XML layouts, and then uses the latest Android build tools to create the app package file, known as an APK file. You can customize your configurations to have development or production versions of the app that behave differently, or add dependencies for third-party libraries.
- Maven is another project build tool, and it can also refer to the Maven Central repository of java libraries. It is absurdly easy to use Gradle and Maven Central in concert with Android Studio to incorporate all sorts of functionality from the Android development community. Those with an iOS background will know how cool this sort of thing can be from using the CocoaPods tool. You’ll learn more about Maven in Part Three of the tutorial.
After a brief moment, Android Studio will finish building your project. The project is pretty empty, of course, but it still has everything it needs already set up so that it can be launched on an Android device or emulator. You will be dropped off in this spot:
Android Studio will contain three windows. To the left you have your project folder structure, the middle contains a preview of your layout on a Nexus 5 device and finally the right shows your layout hierarchy as well as attributes if you have a part of your layout hierarchy selected. Before you get into any programming, let’s talk about how you’re going to get this app running. It’s time to say “Hello world!”
Running on an Emulator or Device
All right: You’ve got Android Studio and you’ve created an app. So how do you run it?
If you have a physical Android device available, you’ll learn how to use that soon. But for those without one, you also have the choice to run your App on an emulator.
Android Studio comes free with the ability to set up a software-based Android device on your computer and run apps on it, browse websites, debug and everything you would expect. This capability is known as the Android Emulator.
You can set up multiple emulators and set the screen size and platform version for each one to whatever you like. This is great, as with the diversity of the Android platform, you’d otherwise need a large amount of devices for testing.
If you ran through the setup wizard earlier using the standard installation then you will already have an emulator setup and ready for you to use. Making use of some useful software developed by Intel to ensure your emulator runs quickly for your testing needs.
Up until recently, your computer would have to emulate everything an Android device would try to do. Everything down to it’s hardware which runs using an ARM based processor. Most computers these days make use of x86 based processors, which means your computer would be doing computationally intense tasks that take a significant amount of time just to test your App.
You still have the option to do this if you want to create an emulator that is as close to an actual device as you can, but be aware that the initial load times have put off many an Android Developer using the emulator all together.
All of that being said…let’s set up an emulator anyway, because you’re going to need to know how!
Click AVD Manager. It’s the button in the toolbar that has an Android popping its head up next to a device with a purple display.
As you will see. Android Studio has already created an AVD for you to use. You’ll see a few details about it, notably what type of emulator it is, what API it is using and what CPU instruction set it uses.
Lets run through creating a new AVD. Click Create Virtual Device… in the bottom left to begin configuring a new virtual device.
The first decision you need to make is what type of device you want to emulate. The Category list to the left shows all the types of device you can emulate. Clicking each option shows you what type of devices are available to you in that category. For now you just want to emulate a phone sized device but if you wanted to emulate an Android Wear watch or an Android TV then you have options to do so here.
Select Nexus S in the list of devices available to you from the phone category and click Next.
Your next decision is to decide what version of Android you want your virtual device to run. You will already have one or two available to you thanks to the setup wizard, so lets use one of them.
Select Lollipop and make sure the one selected has the value x86 in the ABI column. We want the emulator to be running as fast as possible on our x86 computers. :)
Click Next once this is done to move to the final screen. The last screen is simply a confirmation of your previous choices with the option to configure some other properties of your device such as device name, startup orientation, and RAM size. For now leave these set as their defaults and click Finish
Congratulations! With relative ease you’ve just created a fresh virtual device ready for use to test out your new app.
Now, close the AVD Manager to go back to Android Studio’s main view. Now that you’ve configured everything, there’s but one step left…
Click the Run button. It looks like a “play” icon.
A new window will appear, asking you to choose the device you wish to test your App on. You currently have no devices running, so lets start the AVD you just created. Ensure the Launch Emulator radio button is checked and your AVD is selected in the drop down menu, then click OK.
Note: If you get an error that says “This AVD’s configuration is missing a kernel file!!”, check to make sure that you don’t have the ANDROID_SDK_ROOT environment variable set from a previous installation of the Android SDK. See this thread for more troubleshooting tips.
You may have to wait a while as the emulator loads, and you may even need to try it more than once for the emulator to get it right, but once it’s ready, you should see something like this:
Congratulations! You made your first Android app!
Android Apps used to be something you only interacted with on the consumer side, but now… you’re a creator. There’s power and possibility in that. It’s worth taking a moment to think about where you might want to go with this newfound ability.
When you’re ready, you need to revisit something I quickly glossed over earlier — testing on devices.
Navigating the Android Candy Store
One of Android’s advantages, the diversity of devices that can run the platform, is also a major complication for developers. You have to consider just about everything, such as the items on the following non-exhaustive list, to be variable:
- Screen sizes, both physically and in terms of pixels
- Processor speed
- Screen density, or the number of pixels per mm
- The ratio of the screen width to the screen height
- The number of simultaneous touches the touchscreen can register
- The quantity and positioning (front vs. back) of cameras
- Bluetooth capabilities
- Platform and software versions
If you want to make an App that will run on a hundred different devices, how can you tell if it’s going to work? Well, there are six main strategies I can recommend:
- Nail down your target
- Filter your manifest
- Check Android’s best practices
- Emulate
- Pick at least one representative device
- Fake other screens on your device
Let’s go through them one by one.
1. Nail down your target
Does your App have some specific, indispensable hardware or software requirement? What about nice-to-haves? Take stock of device needs early, so that if your App is camera-based, or communicates with a specific product through Bluetooth, you’re ready to target your App to devices with those capabilities.
Check the often-updated Android Dashboards to see the prevalence of platform versions as well as screen sizes and densities. You can see, for example, that your choice in this tutorial to only support Ice Cream Sandwich and higher will lose you just over a quarter of Android users. It’s a reasonable sacrifice in your case.
2. Filter your manifest
Once you’ve determined your App’s requirements, you need to let Android know about them. That way, the Google Play Store can keep non-compatible devices from purchasing your App.
This will save you a lot of frustration and poor reviews from users who might have downloaded your app, only to find a strange error awaiting them. It won’t, however, absolve you from communicating in any marketing materials the list of devices your users should expect to be able to run your App on.
The device features you need should be listed in a file. This file, available in every project, is called the Android Manifest. This is an XML file that contains all the high-level info about your App. Remember when you chose API 15: Ice Cream Sandwich as the minimum SDK when you created the OMG Android project? That choice needs to be reflected in your Android Manifest.
Find your
AndroidManifest.xml
file on the left side of the Android Studio window, likely under app/manifests
, and double-click it to open it up. You will see a few elements contain values, but nothing that looks like it determines what SDK is used in your App. Thats fine, lets just add it in. Add the following to your Android Manifest above the application XML tag.<uses-sdk android:targetSdkVersion="21" android:minSdkVersion="16" /> |
Looking good. You’ve just told your Android App what version of Android it is targeting and what the minimum version a device needs to run it. Or have you? Mouse your cursor over your newly added XML and you should receive the following message.
As the message politely tells you, your newly input values are being overridden by a Gradle Build Script. Lets go see where this happens, double-click on the build.gradle (Module: App) file in the Gradle Scripts folder and you will be presented with something like this.
apply plugin: 'com.android.application' android { compileSdkVersion 21 buildToolsVersion "21.1.2" defaultConfig { applicationId "com.darrylbayliss.omgandroid" minSdkVersion 16 targetSdkVersion 21 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:21.0.3' } |
There are quite a few things going on here, but for now you will focus on just one part – the defaultConfig element. Inside its curly brackets you will see some familiar looking values that are affecting your App when it is being compiled. This was what the message in your Manifest was warning you about. Fortunately, it isn’t a concern, but it is something worth understanding.
Whenever you click Run in your main project window, any values within the defaultConfig element of build.gradle are used to populate some additional information into your AndroidManifest.xml file. The reason for this is to make use of the flexibility of the Gradle Build Toolkit.
Before Android Studio, things such as trying to build multiple versions of an App from the same project was something of a pipe dream. An App project only has one manifest file to declare it’s features and rules so if you wanted to test different configurations of your App, it would be a long and labored process because you would have to make your changes, compile the App and then repeat this process until you were happy with the results.
The arrival of Gradle changes all that, allowing for multiple bespoke versions of your App to be created using specific rules you can set yourself. Project dependencies can be linked to from remote code repositories, ensuring every time you build your App you are using the latest version of 3rd party libraries. You can even set rules up to test your APK using a variety of source files during the build process.
Gradle makes use of Groovy syntax, a Java like language, so if you are intent on learning Java then you will easily pick Groovy up as well.
You can learn more about Gradle and its treasure chest of features right here on the Android Developers website.
3. Check Android’s best practices
There’s a great list of best practices to address compatibility issues that’s available on the Android Developer site. Some of the most useful tips include:
- Use density-independent measurements in your layouts, so your specifications will scale along with the screen.
- When putting together layouts, use relative widths and heights instead of absolute values.
- Putting in several versions of the same image file, tailored to different screen densities, can also be a good idea.
The tutorial will discuss these in more detail in Part Two, when you lay out views in XML.
4. Emulate
When you set up your Emulator earlier, you saw how many options you have to work with different screen sizes. If you used the stock emulator then you also saw how slow it can be. As mentioned earlier, there are ways to improve it and alternative emulators all together you can make use of to try your App on a huge variety of configurations.
If the stock emulator isn’t for you, try them out and see what works best.
5. Pick at least one representative device
The most expensive option, unless you already own an Android device, is to go out and buy one. I recommend trying to find a used, unlocked device from the Google Nexus series. If your budget is tight, go two generations back, which at the moment would mean a Galaxy Nexus. Of course, if you’ve got the money, you can go for the new snazzy Nexus 5!
With all the time you will save avoiding the emulator, if you continue on with Android (which I hope you will!), it will definitely be a worthwhile investment.
If you have a device, you don’t need any silly Provisioning Profiles. You just need to turn on USB debugging for your device. Sometimes the checkbox option is available just by going to Settings > Developer Options on your device. Check these instructions for more details.
Other times, you have to do some weird shenanigans. I can’t make this up! A direct quote from Android: “On Android 4.2 and newer, Developer options is hidden by default. To make it available, go to Settings > About phone and tap Build numberseven times. Return to the previous screen to find Developer options.”
No matter if you had to do a little dance or whistle a perfect C to reveal the option, once USB debugging is on, you can go back to the Run/Debug Configurations screen and set your Target Device to USB Device. This will serve you well for the rest of the tutorial.
6. Fake other screens on your device
If you are lucky enough to have a device and have enabled USB Debugging on it, then you have another testing advantage: you can use it to “fake” other screen sizes. Here’s how.
Open your Terminal as you did earlier, when you checked for the JDK. Then locate a tool called the Android Debug Bridge (adb). With early versions of Android Studio, it will be in the /Applications/Android\ Studio.app/sdk/platform-toolsdirectory, or wherever you installed your copy of Android Studio, if elsewhere. Later versions of Android Studio do not come with the Android SDK bundled in and so you might have your Android SDK installed in a totally different location.
You can use the following command at the Terminal prompt to see if adb is available in your system PATH:
adb version |
The result should be something like this:
Note: If the
adb version
command results in an error message, your Android SDK folder is probably not in your PATH. Then you’d need to find the exact location of the Android SDK and change to the correct folder (as in the first steps in the screenshot above) and prefix any adb commands with ./
. Alternatively, you can add the adb path to your PATH.
The
adb version
command is just an example to show you how to call adb from the command line. It can run all sorts of commands and you can get a list of available commands by typing adb help
.
If not already set up, you can optionally add the Android SDK platform tools folder to your $PATH so that you can run adb from anywhere on your system. You should only do this if you are familiar with UNIX and feel comfortable doing so.
With your device plugged in and with its screen turned off, type the following:
adb shell wm size 640x480 |
And then type:
adb shell wm density 160 |
This represents a screen size of 640×480 pixels with 160 pixels per inch pixel density.
Note: In Android versions earlier than 4.3 Jelly Bean, these commands are slightly different, as documented here.
When you turn the device screen back on, you should see that the resolution has changed to match the new values you entered!
Feel free to turn the screen off, try another set of dimensions and turn it back on again.
To return your device to its normal settings, type:
adb shell wm size reset |
And then type:
adb shell wm density reset |
So you could get a full-size tablet (like a Nexus 10, perhaps) and then easily simulate all sorts of smaller devices, without having to use the emulator! If you are trying this with a device that has a relatively small screen then it’s not really worth going beyond the dimensions of your screen as it will begin to display elements offscreen.
I hope that information helps you navigate the Gingerbreads, KitKats, Jelly Beans, and all the other varieties of Android candy. Now, back to the app at hand…
So… WHY did that work?
You’ve got your first app behind you. To start making changes and adding cool features, it’s necessary to get a working knowledge of what’s going on behind the scenes.
Take a look at the Project section of Android Studio, with the files and folders on the left side of the screen. You may need to press the little tab on the edge (see below) if the project explorer isn’t visible at the moment.
Browse around for a few minutes without any explicit instructions, expanding and collapsing folders and double-clicking on files to see their contents in the main window. If you notice any trends, great. If it all still looks cryptic, not to worry!
Android Project Structure: The Team
Every great team is composed of people who play different roles. Do you want to do the job right? You need the right team. Android Projects have a few key elements and each has a role to play:
- Java: The Professional
- Resources: The Artist
- AndroidManifest.xml: The Boss
- Intent: The Job itself
Java: The Professional
It’s the job of your Java code to get things done. Your code is all going to be in the src/main/java directory under your main project folder. You will be given all the code you need to complete this tutorial, but if you want to learn or refresh your Java knowledge, here is a nice online interactive tutorial.
It will be worth your time to learn more and more Java as you explore Android development. Your team is relying on the professional.
Resources: The Artist
It’s not enough to just get the job done. It needs to be done in style. Your App is never going to stand out unless it has great icons and images, well-designed layouts, engaging copy text, and maybe even some smooth animations.
Initially, the app/res (Resources) folder contains:
- Drawable folders that hold images — just the default launch icon for now.
- The layout folder with XML that represents the screen designs.
- The menu folder with XML of the items that will appear on the Action Bar. More on that later.
- The values folder with XML containing dimensions, strings, and styles.
AndroidManifest.xml: The Boss
Someone’s got to call the shots. That “someone” would be the Android Manifest. This XML file informs your system of the app’s hardware and software requirements and contains your app’s name, icon, and version.
The manifest also filters the
Intents
coming in. You need a job done by your app? Talk to the boss first. Now, more about the jobs themselves…Intent: The Job itself
Want to show the user a screen? Want to navigate to a website? Whatever the job is, in Android it is going to take the form of an
Intent
. If you come from an iOS background, pay close attention because this is a very “Android” concept.
The Android system knows that you will potentially have a lot of Apps on your device, and wants to make it easy for them to talk to each other. So, it allows you to send and receive what are essentially requests for jobs to be done.
A job could get picked up by your App’s own boss (the manifest) or another App. When creating an
Intent
, it’s up to you to either write it very generally to have the option of picking from several Apps to perform the job (implicit), or very specifically to follow a certain path (explicit). You’ll see an example of each type if Intent
later in this tutorial.
For an immediate example, your App already has an
Activity
called MainActivity
. Your manifest has it labeled with an intent filter that causes the MainActivity
to launch when the user selects the App icon from their home screen. You could potentially move that filter to another Activity
and then that activity would launch instead of MainActivity
. Basically, the App does whatever the boss says.
If you don’t fully grasp everything about
Intents
right away, don’t worry. Just keep the concept in mind as you see Intents
throughout the code, and eventually you will start to get an idea of their potential.Putting a Personal Stamp on Your App
You’ve made your first App, but what’s the first thing you always want to put on any of your work? Thats right, your name!
Navigate to
res/values/strings.xml
and double-click the file. When you open the file, you’ll see three string resources in XML.
These resources are accessed in different places, but it is very convenient to have all of the text used in your App in one file. If you need to translate it, or if your marketing coworker tells you to remove all the nerdy references from your App, it will be easy to make all the changes here.
Change the hello_world string. That string is the one that the app displays on the screen. So, change it to something more personal that incorporates your own name – something like:
<string name="hello_world">Darryl is learning Android!</string> |
So remember: When you launch the App, you’re essentially doing the same thing as sending a launch
Intent
to the manifest. As the boss, the manifest takes a look at the Intent
and decides it has the perfect fit for the job: MyActivity
. The Java does the heavy lifting of opening the screen, but for what to display it goes and asks the artist, eventually leading tostrings.xml.
Click Run. When the App launches again, you’ll see your personalized message!
Congratulations! If you have a device, you can go around showing off your new app to your friends or take a screenshot from the emulator and send it to them.
You’ve entered the world of Android. You’ve set up your development environment (no easy task!), created your first app, run it on an Emulator or device, and changed the App so that it specifically addresses you. Great job!
Updating With the SDK Manager
This tutorial will work with whatever SDK version you downloaded with Android Studio, but as mentioned earlier it’s a good idea to always keep your SDK versions and Android Platform Tools up-to-date.
To access the SDK Manager quickly from your project, click the button, which allows you to easily download or update your Android SDK components.
Where to Go From Here?
There’s a lot still to come, but here are some extra tips to think about before jumping into the next part of the tutorial:
- Follow Android. The development community around any language or framework can be its strongest asset. It’s never too soon or too late to start checking out Google I/O videos, following the Android Developers blog or watching DevBytes videos.
- Get the full source for this section of the tutorial on GitHub or as a .zip.
- Post any comments/suggestions/questions below.
- Stick around for the second and third sections of the tutorial! Thank you!
The Android robot is reproduced or modified from work created and shared by Google and used according to terms described in the Creative Commons 3.0 Attribution License.
Android Studio
Next Tutorial