Android


This draft deletes the entire topic.

expand all collapse all

Examples

  • 117

    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.

    1. 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.
    2. Company Domain - Qualifier for your project's package name. ex: docs.stackexchange.com
    3. 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
    4. Project Location - Directory to store your project in.

    Create new project

    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.

    enter image description here

    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.

    VersionCodenameAPI%
    2.2Froyo80.1
    2.3.3 - 2.3.7Gingerbread101.3
    4.0.3 - 4.0.4Ice Cream Sandwich151.3
    4.1.xJelly Bean164.9
    4.2.xJelly Bean176.8
    4.3Jelly Bean182.0
    4.4KitKat1925.2
    5.0Lollipop2111.3
    5.1Lollipop2222.8
    6.0Marshmallow2324.0
    7.0Nougat240.3
    7.1Nougat25<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.html

    Add 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, and activity_ as a prefix for the layout name. If we leave these as the default, Android Studio will generate an activity for us called MainActivity, and a layout file called activity_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.

    Basic Application Structure

    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 in app/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:

    Layout Design / Text Tabs

    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 the HelloWorld app.

    Lastly, open up the file named build.gradle located in app/.
    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:

    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 the Developer Options in the settings of your device.

    If Developer Options is not visible in the settings, navigate to About Phone and tap on the Build Number seven times. This will enable Developer 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.

  • 33

    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:

    1. Download and install JDK (Java Development Kit) version 8.
    2. Download and install Android Studio.
    3. 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 requires JDK 8. However, it will work with JDK 7, but will not be able to compile Android Nougat code. On Mac OSX it requires JDK 8 and JRE 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 enter image description here 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 with sdk.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 for assembleRelease, which will download all dependencies for you and build the app. The final APK file will be in ProjectName/ModuleName/build/outputs/apk and will been called ModuleName-release.apk.

  • 23

    Requirements and assumptions

    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:

    1. 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 manager android sdk to get the recommended minimum of packages.

    2. 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)
    3. 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)

    4. Run the device:

      emulator -avd DEVICE
      
    5. If the device screen appears to be locked, then swipe to unlock it.

      Leave it running while you code the app.

    Coding the app

    1. Change to an empty working directory.

    2. 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 );
          }
      }
      
    3. 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>
      
    4. Make a sub-directory for the declared resources:

      mkdir res
      

      Leave it empty for now.

    Building the code

    1. 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 a classpath.

    1. 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.

    2. 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
      
    3. 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.

    4. 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).

    5. 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 an ArrayIndexOutOfBoundsException, 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.)

    6. 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

    1. Install the app to the Android device:

      adb install -r out/app.apk
      
    2. 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.

    1. 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>
      
    2. Reference the resource from the XML manifest. This is a declarative style of reference:

      <!-- <application a:label='Saying hello'> -->
           <application a:label='@string/appLabel'>
      
    3. 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 ));
      
    4. 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
    
Please consider making a request to improve this example.

Remarks

If you want to learn more about the Android Gradle Plugin setting check out the android-gradle Documentation.

Versions

VersionAPI LevelVersion CodeRelease Date
1.01BASE2008-09-23
1.12BASE_1_12009-02-09
1.53CUPCAKE2009-04-27
1.64DONUT2009-09-15
2.05ECLAIR2009-10-26
2.0.16ECLAIR_0_12009-12-03
2.1.x7ECLAIR_MR12010-01-12
2.2.x8FROYO2010-05-20
2.39GINGERBREAD2010-12-06
2.3.310GINGERBREAD_MR12011-02-09
3.0.x11HONEYCOMB2011-02-22
3.1.x12HONEYCOMB_MR12011-05-10
3.2.x13HONEYCOMB_MR22011-07-15
4.014ICE_CREAM_SANDWICH2011-10-18
4.0.315ICE_CREAM_SANDWICH_MR12011-12-16
4.116JELLY_BEAN2012-07-09
4.217JELLY_BEAN_MR12012-11-13
4.318JELLY_BEAN_MR22013-07-24
4.419KITKAT2013-10-31
4.4W20KITKAT_WATCH2014-06-25
5.021LOLLIPOP2014-11-12
5.122LOLLIPOP_MR12015-03-09
6.023M (Marshmallow)2015-10-05
7.024N (Nougat)2016-08-01
7.125N_MR1 (Nougat MR1)2016-10-04
Still have a question about Getting started with Android? Ask Question

Topic Outline