wiki:Android/AppDevelopment

App Development

Overview

This page explains the basic steps to begin development on Android applications, as well as the set up required to install and use the Android Studio IDE. The examples on this page assume that you have little to no Android development experience.

For further training on Android Studio and Android app development in general, see Android's Developer Training page.

Setting Up a Development Environment

While there are numerous development environment set ups available to android developers, the recommended option for users new to android would be the Android Studio IDE, which is now the official IDE supported by Google. Support for Eclipse has been planned to discontinue and it is suggested to migrate your eclipse projects to Android Studio in order to ensure continued updates and support. For linux users wishing to avoid IDEs, steps will also be provided for command line installation of the tools required to begin development.

Android Studio IDE

Here are the steps for installing and initially configuring android studio on a Linux system or VM. In all cases below be sure to replace the items within <> to those appropriate to what you downloaded.

  1. Update your machine with the Software Updater or via commandline:
    sudo apt-get upgrade
    
  1. Verify you have JDK version 6 or higher (7 is required for development of Android 5.0 and above) from the command line:
    javac --version
    
    • Note that the OpenJDK can generally be used in place of the Oracle JDK.

2a. If you do not, browse to Oracle's JDK Downloads page and download the linux 32/64 bit tar.gz after accepting the license agreement (above the download link).

2b. Navigate to a directory of your choice and install the jdk:

tar -zxvf <jdk file>

2c. Set JAVA_HOME (you can add these to the bottom of your ~/.bashrc file to do this every time you open a shell - if you do this make sure you open a new shell for them to take effect):

export JAVA_HOME=/<jdk directory>/
export JDK_HOME=/<jdk directory>/
  1. Visit the Android Developer Downloads page and download the appropriate Android Studio bundle for your system. If you are just interested in the SDK tools, they are also available here.
  1. Navigate to an appropriate directory and extract Android Studio with your File/Archive Manager or with the command line:
    unzip <studio zip file>
    
  1. Launch Android Studio. From the command line:
    android-studio/bin/studio.sh
    

Note: You may want to add android-studio/bin/ to your PATH environmental variable so that you can start Android Studio from any directory.

  1. Select the SDK Manager button in the Android Studio toolbar http://developer.android.com/images/tools/sdk-manager-studio.png and install the preselected packages which should at least include:
    • Android SDK tools
    • Android SDK Platform-tools
    • Android SDK Build-tools
    • The latest Android version's SDK platform
    • A target system image such as ARM EABI v7a System Image.

You can always come back and install new packages here as your project requires.

Command Line

Execute the following commands below. If you already have version 1.6 or greater of the oracle jdk skip to step 4. You can verify your jdk version with javac --version.

  1. Download the oracle jdk (replace with latest version of JDK as required by desired Android API):
    wget --no-check-certificate --no-cookies \
     --header "Cookie: oraclelicense=accept-securebackup-cookie" \
     http://download.oracle.com/otn-pub/java/jdk/7u79-b15/jdk-7u79-linux-x64.tar.gz
    
    • Note that the OpenJDK can generally be used in place of the Oracle JDK.
  1. Extract contents
    tar -zxvf jdk-7u79-linux-x64.tar.gz
    
  1. Set JAVA_HOME and JDK_HOME to the directory of the extracted jdk in your preferred .bash file. Example:
    #!/bin/sh
    echo "export JAVA_HOME=/home/user/jdk1.7.0_79" >> ~/.bashrc
    echo "export JDK_HOME=/home/user/jdk1.7.0_79" >> ~/.bashrc
    . ~/.bashrc
    
  1. Download the Android SDK Tools (replace with current version found here):
    wget http://dl.google.com/android/android-sdk_r24.4.1-linux.tgz
    
  1. Extract contents:
    tar -zxvf android-sdk_r24.4.1-linux.tgz
    
  1. Add SDK packages:
    android-sdk-linux/tools/android sdk
    

(Optional) Create an Android Virtual Device

For developmental or compatibility testing purposes a virtual device can be added to android studio to run your apps on. You can create a new virtual device from the precomposed profiles or edit a new profile to your specifications using the Android Virtual Device Manager.

You can access the manager by either

  • The AVD Manager button in the Android Studio toolbar http://developer.android.com/images/tools/avd-manager-studio.png
  • From your Android SDK installation directory:
    android-sdk-linux/tools/android avd
    

An example Virtual device configuration that mimics the hardware and software profile of our Ventana products would be the following:

  • Device: 7" WSVGA (Tablet)(1024x600: mdpi)
  • Target: Android 4.4.2 - API Level 19 (You may need to download this via the package manager first)
  • CPU/ABI: x86
    • if you will be using any pre-compiled objects for an ARMv7 target like the Gateworks Ventana use ARM(armeabi-v7a), otherwise use x86 to avoid the large performance hit of emulation
  • No hardware keyboard present
  • Skin: Skin with dynamic hardware controls
  • Front Camera: Emulated
  • Back Camera: None
  • RAM: 512, VM Heap: 16
  • Internal Storage: 2GiB
  • SD Card: 100 MiB
  • Emulation Options: Use Host GPU

You can always create new or edit your existing virtual devices using the manager at any time.

Creating a Simple “Hello World!” App

To show the basic fundamentals of creating a new project with Android Studio we will make an app that simply displays the static text Hello World! The following paragraphs will explain each dialogue screen in the Android Studio Create New Project wizard. Begin by selecting File > New > New Project in the studio toolbar.

The first new project screen goes over naming and placing your Android application. The conventional naming scheme for Android apps involves constructing the package name as the reverse company domain followed by the application name. For this example, use "HelloWorld" as the application name and "gateworks.com" as the company domain. Keep the default project location as is and select Next to continue.

The next screen covers what type of devices will be able to run your application. Leave "Phone and Tablet" selected and assign the Minimum SDK to API 19: Android 4.4 (KitKat). As Android Studio states, lowering the API level will make your app compatible with a larger percentage of the devices being publicly used but as a trade off you will not have access to the latest Android features. Using API level 19 will ensure that your app will be compatible with most Gateworks Ventana boards which use Android KitKat. Select Next to continue.

The following screen displays a number of template activities that the user can select from to get a head start on development. Any activity selected here will be considered the launcher activity of the application, or in other words, will be the first activity displayed when a user runs your application. For the purposes of this tutorial, select the Empty Activity then select Next.

The final screen covers naming the source files that will be used for your application (Note that this final page can differ depending on which activity you selected from the previous menu). Firstly, make sure that the Generate Layout File option is selected. The Activity Name will dictate the name of the .java source file that handles the procedural logic executed when your app is first launched. The Layout Name specifies the name of the .xml file that is responsible for the formatting of visible elements in the app window. Leaving these names as their defaults is acceptable. Select Finish to finally create the project.

Running your app can be done by selecting the run button in the studio toolbar, or via Run > Run 'app'. If you have no connected Android devices, and wish to start your app on an emulated device, select the Launch emulator radio button and your virtual device from the dropdown menu then select ok (if you have not created a virtual device, see the section on creating a virtual device). If your virtual device is not already running, it may take a few minutes for it to start up depending on your selected hardware configuration, this is normal.

If you have multiple devices connected such as multiple emulators, or a physical device as well as an emulator you will be prompted to choose a device to run on. To use a physical device simply connect it to the host computer over USB OTG and enable USB debugging on the device.

Modifying your app

To showcase the process of making a simple modification to our example app, we'll step through the process of adding a button to the main activity that randomizes the color of the existing "Hello World!" text.

Android Applications separate layout (presentation) from logical code. The layout is in XML files and the code is in java files. Within the IDE the Component Tree will provide a hierarchical representation of the various graphical components. Selecting a component will let you see and alter its physical properties in the Properties box.

You can choose to view the layout in Design form or Text form by selecting the appropriate tab at the bottom of the Design box. When in Design view, you can drag-and-drop various graphical components from the Palette onto the design and arrange them as desired. The Text view lets you edit the XML representation of the layout, which is how it is stored.

  1. In the Text view mode (view modes can be selected from the tabs at the bottom of the view window when editing an xml file), modify the TextView in addition to adding a Button widget to the activity_main.xml inside of the RelativeLayout tag. In the Design view mode you can also find the TextView in the Component Tree within the IDE nested under Device Screen -> RelativeLayout. Make the TextView and Button tags appear like so:
    <TextView
        android:id="@+id/hellotextview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_text" />
    <Button
        android:id="@+id/randomizerbutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:text="@string/button_text"/>
    
    • note we have added an 'id' to the TextView so that we can identify it in code
  • The id attribute gives the widget a unique identifier that will allow us to reference the button from within our MainActivity.java
  • The width and height attributes specify the dimensions of the button, with the wrap_content value meaning that the button will only be large enough to contain the text assigned as the button label.
  • The alignParentEnd attribute when set to true anchors the widget to the right side of the layout (so not to overlap the "HelloWorld!" text).
  • The text attribute assignes a text label to the button, with the value @string/button_text meaning that we will use a string value specified in /app/src/main/res/values/strings.xml.
    • Note that good Android development practice suggests that strings visible to a user be declared in this strings.xml file rather than hardcoded for portability reasons, such as translation. Some Android build systems will even throw errors on hardcoded strings in your xml files that are not declared in strings.xml.
  1. Add the "button_text" and "hello_text" entries we specified earlier to strings.xml. You will find the 'strings.xml' file in the file browser window. Your strings.xml should now resemble:
    <resources>
        <string name="app_name">HelloWorld</string>
        <string name="hello_text">Hello World!</string>
        <string name="button_text">Randomize!</string>
    </resources>
    
  1. Add the randomization logic to the MainActivity.java. We will add a listener to the click event and when the button is clicked we will choose a random color and assign it to the TextView showing the 'Hello World!' string. The onCreate function with added code looks like this:
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        // NEW TEXT HERE
        // Create a reference to the button declared in our activity_main.xml
        Button button = (Button) findViewById(R.id.randomizerbutton);
    
        // Add an action listener for when the button is pressed
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Create a random number generator
                Random rnd = new Random();
     
                // Create a reference to the "Hello World!" text view
                TextView tv = (TextView) findViewById(R.id.hellotextview);
    
                // Randomize the color of the text
                tv.setTextColor(Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256)));
            }
        });
    }
    
    • You will also need to add an 'import android.widget.Button' at the top of MainActivity.java where the other imports are. You will note that Android Studio helps you with this step - if you paste the code in first, then click below one of the existing imports the IDE will popup suggestions for things you need to import and you can hit 'Alt+Enter' to add those suggestions.

The final project should look like this:

  • MainActivity.java:
    package com.gateworks.helloworld;
    
    import android.graphics.Color;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.TextView;
    
    import java.util.Random;
    
    
    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            // Create a reference to the button in our activity_main.xml
            Button button = (Button) findViewById(R.id.randomizerbutton);
    
            // Add an action listener for when the button is pressed
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // Create a random number generator
                    Random rnd = new Random();
    
                    // Create a reference to the "Hello World!" text view
                    TextView tv = (TextView) findViewById(R.id.hellotextview);
    
                    // Randomize the color of the text
                    tv.setTextColor(Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256)));
                }
            });
        }
    }
    
  • activity_main.xml:
    <?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.gateworks.helloworld.MainActivity">
    
        <TextView
            android:id="@+id/hellotextview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World!" />
        <Button
            android:id="@+id/randomizerbutton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:text="@string/button_text"/>
    </RelativeLayout>
    

Using External Libraries such as GateworksUtil

An important tool to development for any Android project is the ability to add external libraries to an existing project. External libraries will be provided as jar files.

To use an external library copy the jar file to the app/libs directory of your project, then in the Android Studio IDE add the library:

  1. select the app folder in the file structure below the toolbox then click libs and then click the library you need to add. This will add it to the file view in the Project.
  2. expand libs and right click the new .jar file and select Add As Library.

Using GateworksUtil

The GateworksUtil library includes classes and methods to easily access and manipulate some of the low level functionality on Gateworks Ventana boards such as GPIOs, PWMs, and LEDs.

Here we will demonstrate a simple example of showing the input voltage by adding a TextView to our example app and updating it on the button press.

  1. Download the GateworksUtil.jar, or via command line:
    wget http://trac.gateworks.com/attachment/wiki/Android/GateworksUtil/GateworksUtil.jar
    
  1. Add it to the project as shown above (Copy the .jar into your project folder under app/libs and select Add As Library.
  1. Add a new TextView to the main activity. In the Text view of activity_main.xml add the following to create the component and position it with respect to the hellotextview component and the randomizerbutton compoenent:
        <TextView
            android:id="@+id/voltageview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="voltage"
            android:layout_alignBaseline="@+id/randomizerbutton"
            android:layout_alignBottom="@+id/randomizerbutton"
            android:layout_alignStart="@+id/hellotextview" />
    
  1. Add the following code to the onClick function in MainActivity.java .
    try {
        TextView voltage = (TextView) findViewById(R.id.voltageview);
        voltage.setText(Integer.toString(HardwareMonitor.getHwmonValue("gsc_vin")));
    } catch (Exception e) {
        e.printStackTrace();
    }
    
  1. Add an import to the top of MainActivity.java to import GateworksUtil:
    import com.gateworks.gateworksutil.*;
    

The final project should look like this:

  • MainActivity.java:
    package com.gateworks.helloworld;
    
    import android.graphics.Color;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.TextView;
    
    import com.gateworks.gateworksutil.HardwareMonitor;
    
    import java.util.Random;
    
    
    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            // Create a reference to the button in our activity_main.xml
            Button button = (Button) findViewById(R.id.randomizerbutton);
    
            // Add an action listener for when the button is pressed
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // Create a random number generator
                    Random rnd = new Random();
    
                    // Create a reference to the "Hello World!" text view
                    TextView tv = (TextView) findViewById(R.id.hellotextview);
    
                    // Randomize the color of the text
                    tv.setTextColor(Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256)));
    
                    try {
                        // Get GSC register for 'vin' and display it
                        TextView voltage = (TextView) findViewById(R.id.voltageview);
                        voltage.setText(Integer.toString(HardwareMonitor.getHwmonValue("gsc_vin")));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
    
  • activity_main.xml:
    <?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.gateworks.helloworld.MainActivity">
    
        <TextView
            android:id="@+id/hellotextview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World!" />
        <Button
            android:id="@+id/randomizerbutton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:text="@string/button_text"/>
        <TextView
            android:id="@+id/voltageview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="voltage"
            android:layout_alignBaseline="@+id/randomizerbutton"
            android:layout_alignBottom="@+id/randomizerbutton"
            android:layout_alignStart="@+id/hellotextview" />
    </RelativeLayout>
    

For a more advanced example using the GateworksUtil library see our GateworksDemo project on Github.

Hide System Navigation Bar

The Android System Navigation Bar is the bar at the bottom of the screen which presents the back, home, and app-switch soft-keys.

To hide the navigation bar (and status bar) within an application (although it will pop back if the user touches anywhere on the screen) you would set the SYSTEM_UI_FLAG_HIDE_NAVIGATION flag (see below).

Note that if you want to hide the navigation bar for the entire Android OS, see here.

For more information see:

Set Immersive Mode

The aptly named "Immersive Mode" of the Android framework hides both the status and navigation bars while your app is in the foreground. However users can still swipe from the top/bottom of the screen to retrieve the system UI. The idea is that unless the user wants to see the status and navigation bars, they are hidden to provide your application with more screen real-estate or to make it more 'immersive'.

To enable immersive mode you set the SYSTEM_UI_FLAG_IMMERSIVE, SYSTEM_UI_FLAG_HIDE_NAVIGATION and SYSTEM_UI_FLAG_FULLSCREEN flags for setSystemUiVisibility().

You can do this in your base activity's oncreate method:

getWindow().getDecorView().setSystemUiVisibility(
  View.SYSTEM_UI_FLAG_LAYOUT_STABLE
  | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
  | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
  | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
  | View.SYSTEM_UI_FLAG_FULLSCREEN
  | View.SYSTEM_UI_FLAG_IMMERSIVE
  | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);

See Also:

Last modified 10 months ago Last modified on 04/29/16 07:58:32