This draft deletes the entire topic.
Examples
-
After setting up Android Studio, let's make our first Android application. (This example is written to target Android Studio 2.0)
Creating a Project
Start Android Studio and create a new project.
This can be done:
- from the welcome screen clicking
Start a New Android Studio project
- by navigating to
File → New Project
if you already have a project open.
Configure the project
Next, we are going to need to fill out some fields to describe our application.
- Application Name - This is what your application will be called, and what will be shown to the user. Choose "Hello World", or a custom name.
- Company Domain - Qualifier for your project's package name. ex:
docs.stackexchange.com
- Package Name - Fully qualified project package name. Should follow Reverse domain name notation (Also called Reserve DNS) of the Company Domain + the Application Name. ex:
com.stackechange.docs.HelloWorld
- Project Location - Directory to store your project in.
Select form factors and API level
After filling out the above fields, click next.
Here we will choose what platforms and what version of Android SDK our application will support.For now, select only Phone and Tablet.
The Minimum SDK is the lower bound for your app. It is one of the signals the Google Play Store uses to determine which of a user’s devices an app can be installed on.
For the Minimum SDK, Android Studio will tell you (approximately) what percentage of devices will support this version.As it says,
Lower API levels target more devices but have fewer features available.
In any case, when deciding on the Minimum SDK, you should consider the stats on the Dashboards, which give you a global look on all devices that visited the Google Play Store in the prior 7 days.
For now, choose
API 16: Android 4.1 (Jelly Bean)
and click next.Version Codename API % 2.2 Froyo 8 0.1 2.3.3 - 2.3.7 Gingerbread 10 1.3 4.0.3 - 4.0.4 Ice Cream Sandwich 15 1.3 4.1.x Jelly Bean 16 4.9 4.2.x Jelly Bean 17 6.8 4.3 Jelly Bean 18 2.0 4.4 KitKat 19 25.2 5.0 Lollipop 21 11.3 5.1 Lollipop 22 22.8 6.0 Marshmallow 23 24.0 7.0 Nougat 24 0.3 7.1 Nougat 25 <1.0 Data collected during a 7-day period ending on November 7, 2016.
Any versions with less than 0.1% distribution are not shown. From: https://developer.android.com/about/dashboards/index.htmlAdd an activity
Now we are going to select a default activity for our application. In Android, an activity is a single screen that will be presented to the user. An application can house multiple activities, and navigate between them. For this example, choose
Empty Activity
and click next.Here, if you wish, you can change the name of the activity and layout. A good practice is to keep
Activity
as a suffix for the activity name, andactivity_
as a prefix for the layout name. If we leave these as the default, Android Studio will generate an activity for us calledMainActivity
, and a layout file calledactivity_main
. Now click finish.Android Studio will create and configure our project, which can take some time depending on the system.
Inspecting the Project
To understand how Android works, let's take a look at some of the files that were created for us.
On the left pane of Android Studio, we can see the structure of our Android application.
First, let's open
AndroidManifest.xml
by double clicking it. The Android manifest file describes some of the basic information about an Android application. It contains the declaration of our activities, as well as some more advanced components.<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.stackexchange.docs.helloworld"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
Next, let's open
activity_main.xml
which is located inapp/src/main/res/layout/
. This file contains declarations for the visual components of our MainActivity.<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.stackexchange.docs.helloworld.MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" /> </RelativeLayout>
You will see a widget called a
TextView
inside of this layout, with the text property set to "Hello World!" this is a block of text that will be shown to the user when they run the application.
You can also switch to the visual layout designer by clicking "Design" at the bottom of Android Studio, seen here:This will allow you do drag and drop elements onto the selected layout.
Next, let's take a look at
MainActivity
. This is the Java code that has been generated for MainActivity.public class MainActivity extends AppCompatActivity { // The onCreate method is called when an Activity starts // This is where we will set up our layout @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // setContentView sets the Activity's layout to a specified XML layout // In our case we are using the activity_main layout setContentView(R.layout.activity_main); } }
As defined in our Android manifest,
MainActivity
will launch by default when a user starts theHelloWorld
app.Lastly, open up the file named
build.gradle
located inapp/
.
Android Studio uses the build system Gradle to compile and build Android applications and libraries.apply plugin: 'com.android.application' android { signingConfigs { applicationName { keyAlias 'applicationName' keyPassword 'password' storeFile file('../key/applicationName.jks') storePassword 'anotherPassword' } } compileSdkVersion 25 buildToolsVersion "25.0.0" defaultConfig { applicationId "com.stackexchange.docs.helloworld" minSdkVersion 16 targetSdkVersion 25 versionCode 1 versionName "1.0" signingConfig signingConfigs.applicationName } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:25.0.0' }
This file contains information about the build, and you can also use it to add dependencies to external libraries. For now, let's not make any changes.
You can find more info about the Gradle plugin:
- A basic example
- Introduction to the Gradle plugin for android and the wrapper
- Introduction to the configuration of the build.gradle and the DSL methods
Running the Application
Now, let's run our HelloWorld application. You can either run an Android Virtual Device (which you can set up by using the AVD Manager in Android Studio) or connect your own Android device through a USB cable.
Setting up an Android device
To run an application from Android Studio on your Android device, you must enable
USB Debugging
in theDeveloper Options
in the settings of your device.If
Developer Options
is not visible in the settings, navigate toAbout Phone
and tap on theBuild Number
seven times. This will enableDeveloper Options
to show up in your settings.You also might need to change
build.gradle
configuration to build on a version that your device has.Running from Android Studio
Click the green
Run
button from the toolbar at the top of Android Studio. In the window that appears, select whichever device you would like to run the app on (start an Android Virtual Device if necessary) and click OK.The application will now install and run on your device or emulator.
- from the welcome screen clicking
-
Android Studio is the Android development IDE that is officially supported and recommended by Google. Android Studio comes bundled with the Android SDK Manager, which is a tool to download the
Android SDK
components required to start developing apps.Installing Android Studio and
Android SDK
tools:- Download and install JDK (Java Development Kit) version 8.
- Download and install Android Studio.
- Download the latest SDK Tools and SDK Platform-tools by opening the Android Studio, and then following the Android SDK Tool Updates instructions. You should install the latest available stable packages.
If you need to work on old projects that were built using older SDK versions, you may need to download these versions as well
The JDK (Java Development Kit) package also contains the consumer-facing Java Runtime Environment (JRE), but having only JRE installed will not be sufficient for using Android Studio.
Android Studio
for Windows and Linux officially requiresJDK 8
. However, it will work withJDK 7
, but will not be able to compile Android Nougat code. On Mac OSX it requiresJDK 8
andJRE 6
, due to some rendering issues. Android Studio 2.0 is set to fix it.Compiling Apps
Create a new project or open an existing project in Android Studio and press the green Play button
on the top toolbar to run it. If it is gray you need to wait a second to allow Android Studio to properly index some files, the progress of which can be seen in the bottom status bar.
If you want to create a project from the shell make sure that you have a
local.properties
file, which is created by Android Studio automatically. If you need to create the project without Android Studio you need a line starting withsdk.dir=
followed by the path to your SDK installation.Open a shell and go into the project's directory. Enter
./gradlew aR
and press enter.aR
is a shortcut forassembleRelease
, which will download all dependencies for you and build the app. The final APK file will be inProjectName/ModuleName/build/outputs/apk
and will been calledModuleName-release.apk
. -
-
Requirements and assumptions
- Oracle JDK 1.7 or later
- Android SDK Tools (just the command line tools)
This example assumes Linux. You may have to adjust the syntax for your own platform.
Setting up the Android SDK
After unpacking the SDK release:
-
Install additional packages using the SDK manager. Don't use
android update sdk --no-ui
as instructed in the bundled Readme.txt; it downloads some 30 GB of unnecessary files. Instead use the interactive SDK managerandroid sdk
to get the recommended minimum of packages. -
Append the following JDK and SDK directories to your execution PATH. This is optional, but the instructions below assume it.
- JDK/bin
- SDK/platform-tools
- SDK/tools
- SDK/build-tools/LATEST (as installed in step 1)
-
Create an Android virtual device. Use the interactive AVD Manager (
android avd
). You might have to fiddle a bit and search for advice; the on-site instructions aren't always helpful.(You can also use your own device)
-
Run the device:
emulator -avd DEVICE
-
If the device screen appears to be locked, then swipe to unlock it.
Leave it running while you code the app.
Coding the app
-
Change to an empty working directory.
-
Make the source file:
mkdir --parents src/dom/domain touch src/dom/domain/SayingHello.java
Content:
package dom.domain; import android.widget.TextView; public final class SayingHello extends android.app.Activity { public void onCreate( final android.os.Bundle activityState ) { super.onCreate( activityState ); final TextView textV = new TextView( SayingHello.this ); textV.setText( "Hello world" ); setContentView( textV ); } }
-
Add a manifest:
touch AndroidManifest.xml
Content:
<?xml version='1.0'?> <manifest xmlns:a='http://schemas.android.com/apk/res/android' package='dom.domain' a:versionCode='0' a:versionName='0'> <application a:label='Saying hello'> <activity a:name='dom.domain.SayingHello'> <intent-filter> <category a:name='android.intent.category.LAUNCHER'/> <action a:name='android.intent.action.MAIN'/> </intent-filter> </activity> </application> </manifest>
-
Make a sub-directory for the declared resources:
mkdir res
Leave it empty for now.
Building the code
- Create a sub-directoris for all the binary files that will be generated during the build process:
mkdir gen out bin
If you will learn more about the commands used below, you will understand that the
gen
folder is used as aclasspath
.-
Generate the source for the resource declarations. Substitute here the correct path to your SDK, and the installed API to build against (e.g. "android-23"):
aapt package -f \ -I SDK/platforms/android-API/android.jar \ -J gen -m \ -M AndroidManifest.xml -S res -v
Resource declarations (described further below) are actually optional. Meantime the above call does nothing if res/ is still empty.
-
Compile the source code to Java bytecode (.java → .class):
javac \ -bootclasspath SDK/platforms/android-API/android.jar \ -classpath gen -source 1.7 -target 1.7 \ src/dom/domain/*.java
-
Translate the bytecode from Java to Android (.class → .dex):
First using Jill (.class → .jayce):
java -jar SDK/build-tools/LATEST/jill.jar \ --output gen/classes.jayce gen
Then Jack (.jayce → .dex):
java -jar SDK/build-tools/LATEST/jack.jar \ --import gen/classes.jayce --output-dex gen
Android bytecode used to be called "Dalvik executable code", and so "dex".
You could replace steps 11 and 12 with a single call to Jack if you like; it can compile directly from Java source (.java → .dex). But there are advantages to compiling with
javac
. It's a better known, better documented and more widely applicable tool. -
Package up the resource files, including the manifest:
aapt package -f \ -F bin/app.apkPart \ -I SDK/platforms/android-API/android.jar \ -M AndroidManifest.xml -S res -v
That results in a partial APK file (Android application package).
-
Make the full APK using the
ApkBuilder
tool:java -classpath SDK/tools/lib/sdklib.jar \ com.android.sdklib.build.ApkBuilderMain \ app.apkUnalign \ -d -f gen/classes.dex -v -z bin/app.apkPart
It warns, "THIS TOOL IS DEPRECATED. See --help for more information." If
--help
fails with anArrayIndexOutOfBoundsException
, then instead pass no arguments:java -classpath SDK/tools/lib/sdklib.jar \ com.android.sdklib.build.ApkBuilderMain
It explains that the CLI (
ApkBuilderMain
) is deprecated in favour of directly calling the Java API (ApkBuilder
). (If you know how to do that from the command line, please update this example.) -
Optimize the data alignment of the APK (recommended practice):
zipalign -f -v 4 bin/app.apkUnalign out/app.apk
In case you need it, here's a working example of a build script that uses the above commands.
Installing and running
-
Install the app to the Android device:
adb install -r out/app.apk
-
Start the app:
adb shell am start -n dom.domain/.SayingHello
It should run and say hello.
That's all. That's what takes to say hello using the basic Android tools.
Declaring a resource
This section is optional. Resource declarations aren't required for a simple "hello world" app. If they aren't required for your app either, then you could streamline the build somewhat by omitting step 10, and removing the reference to the res/ directory from step 13.
Otherwise, here's a brief example of how to declare a resource, and how to reference it.
-
Add a resource file:
mkdir res/values touch res/values/values.xml
Content:
<?xml version='1.0'?> <resources> <string name='appLabel'>Saying hello</string> </resources>
-
Reference the resource from the XML manifest. This is a declarative style of reference:
<!-- <application a:label='Saying hello'> --> <application a:label='@string/appLabel'>
-
Reference the same resource from the Java source. This is an imperative reference:
// v.setText( "Hello world" ); v.setText( "This app is called " + getResources().getString( R.string.appLabel ));
-
Test the above modifications by rebuilding, reinstalling and re-running the app (steps 10-17).
It should restart and say, "This app is called Saying hello".
Uninstalling the app
adb uninstall dom.domain
-
Live templates help you to write more code with less effort. Live templates contain predefined code structure. What if you will get whole for loop with just one word? Seems interesting, let’s see how live template can help to increase your productivity.
Live templates are code snippet which can be inserted in your code with their abbreviation and pressing tab. You can find all pre-defined live templates in Editor section of your Android Studio.
(Quick shortcut: Alt+s, and type "live")For example, if you want
Toast
in your code, you just need to writeToast
and press enter or tab, that's it, whole Toast will be written like below :Toast.makeText(MainActivity.this,"Your message",Toast.LENGTH_SHORT).show();
Here is the Live Template syntax of
Toast
Adding User Live Templates
By pressing the '+' button on the right, you can add your own templates.
For example:
- Abbreviation: todo
- Template Text: // TODO: $date$ $END$
- The $date$ is a new variable that we're introducing.
- Click on Edit Variable button and set the "Expression" of date to
date()
and check ☑ "skip if defined".
- Context: set to "Java".
Notice the "Context" definition that needs to be defined using the "Define" link under the "Template text" box.
Some Useful User Templates
- now →
long now = System.currentTimeMillis(); - todo →
// TODO: $date$ $END$ - tag (editing the default one provided under AndroidLog) →
private static final String TAG = $className$.class.getSimpleName();- Click on Edit Variable button and check ☑ "skip if defined".
Remarks
If you want to learn more about the Android Gradle Plugin setting check out the android-gradle
Documentation.
Versions
Version | API Level | Version Code | Release Date |
---|---|---|---|
1.0 | 1 | BASE | 2008-09-23 |
1.1 | 2 | BASE_1_1 | 2009-02-09 |
1.5 | 3 | CUPCAKE | 2009-04-27 |
1.6 | 4 | DONUT | 2009-09-15 |
2.0 | 5 | ECLAIR | 2009-10-26 |
2.0.1 | 6 | ECLAIR_0_1 | 2009-12-03 |
2.1.x | 7 | ECLAIR_MR1 | 2010-01-12 |
2.2.x | 8 | FROYO | 2010-05-20 |
2.3 | 9 | GINGERBREAD | 2010-12-06 |
2.3.3 | 10 | GINGERBREAD_MR1 | 2011-02-09 |
3.0.x | 11 | HONEYCOMB | 2011-02-22 |
3.1.x | 12 | HONEYCOMB_MR1 | 2011-05-10 |
3.2.x | 13 | HONEYCOMB_MR2 | 2011-07-15 |
4.0 | 14 | ICE_CREAM_SANDWICH | 2011-10-18 |
4.0.3 | 15 | ICE_CREAM_SANDWICH_MR1 | 2011-12-16 |
4.1 | 16 | JELLY_BEAN | 2012-07-09 |
4.2 | 17 | JELLY_BEAN_MR1 | 2012-11-13 |
4.3 | 18 | JELLY_BEAN_MR2 | 2013-07-24 |
4.4 | 19 | KITKAT | 2013-10-31 |
4.4W | 20 | KITKAT_WATCH | 2014-06-25 |
5.0 | 21 | LOLLIPOP | 2014-11-12 |
5.1 | 22 | LOLLIPOP_MR1 | 2015-03-09 |
6.0 | 23 | M (Marshmallow) | 2015-10-05 |
7.0 | 24 | N (Nougat) | 2016-08-01 |
7.1 | 25 | N_MR1 (Nougat MR1) | 2016-10-04 |
Topic Outline
- Creating a new project
- Setting up Android Studio
- Android programming without an IDE
- Live Templates in Android Studio
Versions
Sign up or log in
Save edit as a guest
Join Stack Overflow
Using Google
Using Facebook
Using Email and Password
We recognize you from another Stack Exchange Network site!
Join and Save Draft