Update note: This tutorial was updated for the latest version of Android Studio by Darryl Bayliss. Original tutorial by Matt Luedke.
“But when does the Android version come out?”
–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) the largest 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 App is 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 tutorial about 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 blue 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 titled Download 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. It may ask you if you want to import any settings:
Since you’re starting from scratch, if given the choice just select I do not have a previous version… and move on. You’re presented with the loading screen, complete with all the various phone and tablet screen sizes in the background. More on screen size diversity later. ;]
Once Android Studio has finished loading, you’ll be greeted with 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 the check for updates at the bottom of the welcome screen.
If any 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
The next thing you need to do is download a version of the Android SDK. With the huge amount of devices that use the Android Operating System, you need to have access to every SDK that has been released and is in use all over the world.
Once you have an SDK you can begin 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 Android to develop with. 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, entitled Tools, 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 a 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.
Next you need to grab a version of the SDK. Lets dive into the latest version, that being Android 5.0 (API 21). Lucky for you Android Studio comes bundled with the Android 5.0 SDK when you install Android Studio, although its most likely the SDK Manager will have marked this for an update if one is available.
To get an idea of how the SDK Manager works, you’ll download everything the Android 5.0 Directory offers. Click the tick box next to the folder icon for Android 5.0, 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 tools or SDK’s you have installed. This ensures you get access to the latest features in your SDK’s 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 New Project from 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 Domain textfield. 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 15, which is Android 4.0.3 (Ice Cream Sandwich). 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 choose underneath 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 of Activity
. Those familiar with object-oriented programming will know what this is, but for newcomers, this basically means that your MainActivity
is going to be a customized version of Activity
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 shows a layout file in XML and the right contains a preview of your layout on a Nexus 4 device. 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.
The downside to the emulator is a big one. Unfortunately, the emulator is painfully slow. For those coming from iOS development, you will really start to appreciate the iOS Simulator after using the Android Emulator.
Note: The reasons why the emulator is frustratingly slow boil down to one thing.
Instruction sets. The majority of Android devices run on ARM based processors whilst the majority of computers use x86 based processors.
What the Android Emulator does is completely emulate an Android device running on an ARM based processor, forcing your computer to translate from x86 to ARM based instructions. This is computationally taxing on your computer, hence why the initial loading of the emulator takes so long.
The lightning quick Genymotion Emulator is a fantastic alternative to the stock emulator, although setting it up has a quite a few steps. Intel has also made impressive efforts to offer x86 compatible System Images via the SDK Manager that can be Hardware Accelerated. Feel free to use ether of these alternatives if you just can’t wait for the stock emulator to load.
All of that being said…let’s set up an emulator anyway, because you’re going to need it!
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.
Since your list is probably empty (if you are just starting Android development), you will need to create one. Click the Create button.
Now you see a bunch of options to create your emulator:
Configure your settings as follows:
- Enter EmulateMasterGeneral for the AVD Name.
- The Device dropdown contains a number of useful presets to help you base your virtual device off a real one. Choose the Nexus 4 option.
- For the Target dropdown, choose the Android 5.0 option. Remember the SDK Manager? Well as you use it to download more SDK’s to develop and test for, they will appear here for you to use on your AVD’s, allowing you to test your App across multiple versions of Android.
- For CPU/API, choose ARM.
- For Skin, choose Skin with dynamic hardware controls.
You can leave the rest as default. Once you’re ready, click OK.
Note: If your Device selection doesn’t automatically pick a CPU, make sure to select an
ARM processor for your emulator. You can use the CPU options such as the Intel Atom (x86) but these can take some additional effort to setup and use effectively.
If you downloaded any of the alternative emulators mentioned earlier in this tutorial then follow the instructions provided on each website.
You’ll see a brief summary pop-up of the options you just chose. Click Ok, your newly-created emulator will now be on the list and waiting to be brought to life!
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/src/res
, 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="15" /> |
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 file in the app folder and you will be presented with something like this.
apply plugin: 'com.android.application'
android {
compileSdkVersion 21
buildToolsVersion "20.0.0"
defaultConfig {
applicationId "com.darrylbayliss.omgandroid"
minSdkVersion 15
targetSdkVersion 21
versionCode 1
versionName "1.0"
}
buildTypes {
release {
runProguard false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
} |
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:
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 number seven 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-tools directory, 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:
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:
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:
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 src/main/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 MyActivity
. Your manifest has it labeled with an intent filter that causes the MyActivity
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 MyActivity
. 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 to strings.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 Tutorial for Beginners: Part 1 is a post from: Ray Wenderlich
The post Android Tutorial for Beginners: Part 1 appeared first on Ray Wenderlich.