Changes between Initial Version and Version 1 of Android/AppDevelopment


Ignore:
Timestamp:
10/22/2017 05:28:45 AM (6 years ago)
Author:
trac
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • Android/AppDevelopment

    v1 v1  
     1[[PageOutline]]
     2
     3= App Development =
     4
     5[=#overview]
     6== Overview ==
     7
     8This 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.
     9
     10For further training on Android Studio and Android app development in general, see [http://developer.android.com/training/index.html Android's Developer Training page].
     11
     12
     13[=#setup]
     14== Setting Up a Development Environment ==
     15While 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.
     16
     17
     18=== Android Studio IDE ===
     19Here 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.
     20
     211. Update your machine with the Software Updater or via commandline:
     22{{{#!bash
     23sudo apt-get upgrade
     24}}}
     25
     262. Verify you have JDK version 6 or higher (7 is required for development of Android 5.0 and above) from the command line:
     27{{{#!bash
     28javac --version
     29}}}
     30   * Note that the OpenJDK can generally be used in place of the Oracle JDK.
     31
     32  2a. If you do not, browse to Oracle's [http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html JDK Downloads] page and download the linux 32/64 bit tar.gz after accepting the license agreement (above the download link).
     33 
     34  2b. Navigate to a directory of your choice and install the jdk:
     35{{{#!bash
     36tar -zxvf <jdk file>
     37}}}
     38
     39  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):
     40{{{#!bash
     41export JAVA_HOME=/<jdk directory>/
     42export JDK_HOME=/<jdk directory>/
     43}}}
     44
     453. Visit the Android [http://developer.android.com/sdk/index.html 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 [http://developer.android.com/sdk/index.html#Other here].
     46
     474. Navigate to an appropriate directory and extract Android Studio with your !File/Archive Manager or with the command line:
     48{{{#!bash
     49unzip <studio zip file>
     50}}}
     51
     525. Launch Android Studio. From the command line:
     53{{{#!bash
     54android-studio/bin/studio.sh
     55}}}
     56
     57 Note: You may want to add android-studio/bin/ to your PATH environmental variable so that you can start Android Studio from any directory.
     58
     596. Select the SDK Manager button in the Android Studio toolbar [[Image(http://developer.android.com/images/tools/sdk-manager-studio.png)]] and install the preselected packages which should at least include:
     60 * Android SDK tools
     61 * Android SDK Platform-tools
     62 * Android SDK Build-tools
     63 * The latest Android version's SDK platform
     64 * A target system image such as ARM EABI v7a System Image.
     65
     66You can always come back and install new packages here as your project requires.
     67
     68[=#cmdline]
     69=== Command Line ===
     70Execute 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}}}.
     71
     72 1. Download the oracle jdk (replace with latest version of JDK as required by desired Android API):
     73{{{#!bash
     74wget --no-check-certificate --no-cookies \
     75 --header "Cookie: oraclelicense=accept-securebackup-cookie" \
     76 http://download.oracle.com/otn-pub/java/jdk/7u79-b15/jdk-7u79-linux-x64.tar.gz
     77}}}
     78  * Note that the OpenJDK can generally be used in place of the Oracle JDK.
     79
     80 2. Extract contents
     81{{{#!bash
     82tar -zxvf jdk-7u79-linux-x64.tar.gz
     83}}}
     84
     85 3. Set JAVA_HOME and JDK_HOME to the directory of the extracted jdk in your preferred .bash file. Example:
     86{{{#!bash
     87#!/bin/sh
     88echo "export JAVA_HOME=/home/user/jdk1.7.0_79" >> ~/.bashrc
     89echo "export JDK_HOME=/home/user/jdk1.7.0_79" >> ~/.bashrc
     90. ~/.bashrc
     91}}}
     92
     93 4. Download the Android SDK Tools (replace with current version found [http://developer.android.com/sdk/index.html#Other here]):
     94{{{#!bash
     95wget http://dl.google.com/android/android-sdk_r24.4.1-linux.tgz
     96}}}
     97
     98 5. Extract contents:
     99{{{#!bash
     100tar -zxvf android-sdk_r24.4.1-linux.tgz
     101}}}
     102
     103 6. Add SDK packages:
     104{{{#!bash
     105android-sdk-linux/tools/android sdk
     106}}}
     107
     108
     109[=#avd]
     110=== (Optional) Create an Android Virtual Device ===
     111For 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.
     112
     113You can access the manager by either
     114 * The AVD Manager button in the Android Studio toolbar [[Image(http://developer.android.com/images/tools/avd-manager-studio.png)]]
     115 * From your Android SDK installation directory:
     116{{{#!bash
     117android-sdk-linux/tools/android avd
     118}}}
     119
     120An example Virtual device configuration that mimics the hardware and software profile of our Ventana products would be the following:
     121 * Device: 7" WSVGA (Tablet)(1024x600: mdpi)
     122 * Target: Android 4.4.2 - API Level 19 (You may need to download this via the package manager first)
     123 * CPU/ABI: x86
     124  - 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
     125 * No hardware keyboard present
     126 * Skin: Skin with dynamic hardware controls
     127 * Front Camera: Emulated
     128 * Back Camera: None
     129 * RAM: 512, VM Heap: 16
     130 * Internal Storage: 2GiB
     131 * SD Card: 100 MiB
     132 * Emulation Options: Use Host GPU
     133
     134You can always create new or edit your existing virtual devices using the manager at any time.
     135
     136
     137[=#helloworld]
     138== Creating a Simple “Hello World!” App ==
     139To 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.
     140
     141The 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.
     142
     143The 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.
     144
     145The 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}}}.
     146
     147The 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.
     148
     149Running 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 [#avd 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.
     150
     151If 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.
     152
     153=== Modifying your app ===
     154To 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.
     155
     156Android 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.
     157
     158You 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.
     159
     1601. 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:
     161 {{{#!xml
     162<TextView
     163    android:id="@+id/hellotextview"
     164    android:layout_width="wrap_content"
     165    android:layout_height="wrap_content"
     166    android:text="@string/hello_text" />
     167<Button
     168    android:id="@+id/randomizerbutton"
     169    android:layout_width="wrap_content"
     170    android:layout_height="wrap_content"
     171    android:layout_alignParentEnd="true"
     172    android:text="@string/button_text"/>
     173 }}}
     174  - note we have added an 'id' to the !TextView so that we can identify it in code
     175 * The '''id''' attribute gives the widget a unique identifier that will allow us to reference the button from within our !MainActivity.java
     176 * 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.
     177 * The '''alignParentEnd''' attribute when set to true anchors the widget to the right side of the layout (so not to overlap the "!HelloWorld!" text).
     178 * 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}}}.
     179   * 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.
     180
     1812. 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:
     182 {{{#!xml
     183<resources>
     184    <string name="app_name">HelloWorld</string>
     185    <string name="hello_text">Hello World!</string>
     186    <string name="button_text">Randomize!</string>
     187</resources>
     188 }}}
     189
     1903. 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:
     191{{{#!java
     192@Override
     193protected void onCreate(Bundle savedInstanceState) {
     194    super.onCreate(savedInstanceState);
     195    setContentView(R.layout.activity_main);
     196
     197    // NEW TEXT HERE
     198    // Create a reference to the button declared in our activity_main.xml
     199    Button button = (Button) findViewById(R.id.randomizerbutton);
     200
     201    // Add an action listener for when the button is pressed
     202    button.setOnClickListener(new View.OnClickListener() {
     203        @Override
     204        public void onClick(View v) {
     205            // Create a random number generator
     206            Random rnd = new Random();
     207 
     208            // Create a reference to the "Hello World!" text view
     209            TextView tv = (TextView) findViewById(R.id.hellotextview);
     210
     211            // Randomize the color of the text
     212            tv.setTextColor(Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256)));
     213        }
     214    });
     215}
     216}}}
     217 * 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.
     218
     219The final project should look like this:
     220 * !MainActivity.java:
     221{{{#!java
     222package com.gateworks.helloworld;
     223
     224import android.graphics.Color;
     225import android.support.v7.app.AppCompatActivity;
     226import android.os.Bundle;
     227import android.view.View;
     228import android.widget.Button;
     229import android.widget.TextView;
     230
     231import java.util.Random;
     232
     233
     234public class MainActivity extends AppCompatActivity {
     235
     236    @Override
     237    protected void onCreate(Bundle savedInstanceState) {
     238        super.onCreate(savedInstanceState);
     239        setContentView(R.layout.activity_main);
     240
     241        // Create a reference to the button in our activity_main.xml
     242        Button button = (Button) findViewById(R.id.randomizerbutton);
     243
     244        // Add an action listener for when the button is pressed
     245        button.setOnClickListener(new View.OnClickListener() {
     246            @Override
     247            public void onClick(View v) {
     248                // Create a random number generator
     249                Random rnd = new Random();
     250
     251                // Create a reference to the "Hello World!" text view
     252                TextView tv = (TextView) findViewById(R.id.hellotextview);
     253
     254                // Randomize the color of the text
     255                tv.setTextColor(Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256)));
     256            }
     257        });
     258    }
     259}
     260}}}
     261 * activity_main.xml:
     262{{{#!xml
     263<?xml version="1.0" encoding="utf-8"?>
     264<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     265    xmlns:tools="http://schemas.android.com/tools"
     266    android:layout_width="match_parent"
     267    android:layout_height="match_parent"
     268    android:paddingBottom="@dimen/activity_vertical_margin"
     269    android:paddingLeft="@dimen/activity_horizontal_margin"
     270    android:paddingRight="@dimen/activity_horizontal_margin"
     271    android:paddingTop="@dimen/activity_vertical_margin"
     272    tools:context="com.gateworks.helloworld.MainActivity">
     273
     274    <TextView
     275        android:id="@+id/hellotextview"
     276        android:layout_width="wrap_content"
     277        android:layout_height="wrap_content"
     278        android:text="Hello World!" />
     279    <Button
     280        android:id="@+id/randomizerbutton"
     281        android:layout_width="wrap_content"
     282        android:layout_height="wrap_content"
     283        android:layout_alignParentEnd="true"
     284        android:text="@string/button_text"/>
     285</RelativeLayout>
     286}}}
     287
     288
     289[=#gateworksutil]
     290== Using External Libraries such as GateworksUtil ==
     291An 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.
     292
     293To 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:
     294 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.
     295 2. expand {{{libs}}} and right click the new .jar file and select '''Add As Library'''.
     296
     297=== Using GateworksUtil ===
     298The [wiki:Android/GateworksUtil GateworksUtil] library includes classes and methods to easily access and manipulate some of the low level functionality on Gateworks Ventana boards such as [wiki:gpio#gpiolib_sysfs GPIOs], [wiki:linux/pwm PWMs], and [wiki:gpio#led LEDs].
     299
     300Here 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.
     301
     3021. Download the [http://trac.gateworks.com/attachment/wiki/Android/GateworksUtil/GateworksUtil.jar GateworksUtil.jar], or via command line:
     303{{{#!bash
     304wget http://trac.gateworks.com/attachment/wiki/Android/GateworksUtil/GateworksUtil.jar
     305}}}
     306
     3072. Add it to the project as shown above (Copy the .jar into your project folder under {{{app/libs}}} and select '''Add As Library'''.
     308
     3093. 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:
     310{{{#!xml
     311    <TextView
     312        android:id="@+id/voltageview"
     313        android:layout_width="wrap_content"
     314        android:layout_height="wrap_content"
     315        android:text="voltage"
     316        android:layout_alignBaseline="@+id/randomizerbutton"
     317        android:layout_alignBottom="@+id/randomizerbutton"
     318        android:layout_alignStart="@+id/hellotextview" />
     319}}}
     320
     3214. Add the following code to the {{{onClick}}} function in {{{MainActivity.java}}} .
     322{{{#!java
     323try {
     324    TextView voltage = (TextView) findViewById(R.id.voltageview);
     325    voltage.setText(Integer.toString(HardwareMonitor.getHwmonValue("gsc_vin")));
     326} catch (Exception e) {
     327    e.printStackTrace();
     328}
     329}}}
     330
     3315. Add an import to the top of {{{MainActivity.java}}} to import GateworksUtil:
     332{{{
     333import com.gateworks.gateworksutil.*;
     334}}}
     335
     336The final project should look like this:
     337 * !MainActivity.java:
     338{{{#!java
     339package com.gateworks.helloworld;
     340
     341import android.graphics.Color;
     342import android.support.v7.app.AppCompatActivity;
     343import android.os.Bundle;
     344import android.view.View;
     345import android.widget.Button;
     346import android.widget.TextView;
     347
     348import com.gateworks.gateworksutil.HardwareMonitor;
     349
     350import java.util.Random;
     351
     352
     353public class MainActivity extends AppCompatActivity {
     354
     355    @Override
     356    protected void onCreate(Bundle savedInstanceState) {
     357        super.onCreate(savedInstanceState);
     358        setContentView(R.layout.activity_main);
     359
     360        // Create a reference to the button in our activity_main.xml
     361        Button button = (Button) findViewById(R.id.randomizerbutton);
     362
     363        // Add an action listener for when the button is pressed
     364        button.setOnClickListener(new View.OnClickListener() {
     365            @Override
     366            public void onClick(View v) {
     367                // Create a random number generator
     368                Random rnd = new Random();
     369
     370                // Create a reference to the "Hello World!" text view
     371                TextView tv = (TextView) findViewById(R.id.hellotextview);
     372
     373                // Randomize the color of the text
     374                tv.setTextColor(Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256)));
     375
     376                try {
     377                    // Get GSC register for 'vin' and display it
     378                    TextView voltage = (TextView) findViewById(R.id.voltageview);
     379                    voltage.setText(Integer.toString(HardwareMonitor.getHwmonValue("gsc_vin")));
     380                } catch (Exception e) {
     381                    e.printStackTrace();
     382                }
     383            }
     384        });
     385    }
     386}
     387}}}
     388 * activity_main.xml:
     389{{{#!xml
     390<?xml version="1.0" encoding="utf-8"?>
     391<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     392    xmlns:tools="http://schemas.android.com/tools"
     393    android:layout_width="match_parent"
     394    android:layout_height="match_parent"
     395    android:paddingBottom="@dimen/activity_vertical_margin"
     396    android:paddingLeft="@dimen/activity_horizontal_margin"
     397    android:paddingRight="@dimen/activity_horizontal_margin"
     398    android:paddingTop="@dimen/activity_vertical_margin"
     399    tools:context="com.gateworks.helloworld.MainActivity">
     400
     401    <TextView
     402        android:id="@+id/hellotextview"
     403        android:layout_width="wrap_content"
     404        android:layout_height="wrap_content"
     405        android:text="Hello World!" />
     406    <Button
     407        android:id="@+id/randomizerbutton"
     408        android:layout_width="wrap_content"
     409        android:layout_height="wrap_content"
     410        android:layout_alignParentEnd="true"
     411        android:text="@string/button_text"/>
     412    <TextView
     413        android:id="@+id/voltageview"
     414        android:layout_width="wrap_content"
     415        android:layout_height="wrap_content"
     416        android:text="voltage"
     417        android:layout_alignBaseline="@+id/randomizerbutton"
     418        android:layout_alignBottom="@+id/randomizerbutton"
     419        android:layout_alignStart="@+id/hellotextview" />
     420</RelativeLayout>
     421}}}
     422
     423For a more advanced example using the GateworksUtil library see our [https://github.com/Gateworks/android_packages_apps_gateworksdemo GateworksDemo project] on Github.
     424
     425
     426[=#disable-navbar]
     427== Hide System Navigation Bar ==
     428The Android System Navigation Bar is the bar at the bottom of the screen which presents the back, home, and app-switch soft-keys.
     429
     430To 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 [#SetImmersiveMode below]).
     431
     432Note that if you want to hide the navigation bar for the entire Android OS, see [wiki:Android/Kiosk#disable-navbar here].
     433
     434For more information see:
     435- [http://developer.android.com/training/system-ui/navigation.html Hiding the Navigation Bar]
     436
     437
     438[=#immersive-mode]
     439== Set Immersive Mode ==
     440The 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'.
     441
     442To enable immersive mode you set the {{{SYSTEM_UI_FLAG_IMMERSIVE}}}, {{{SYSTEM_UI_FLAG_HIDE_NAVIGATION}}} and {{{SYSTEM_UI_FLAG_FULLSCREEN}}} flags for {{{setSystemUiVisibility()}}}.
     443
     444You can do this in your base activity's oncreate method:
     445{{{#!java
     446getWindow().getDecorView().setSystemUiVisibility(
     447  View.SYSTEM_UI_FLAG_LAYOUT_STABLE
     448  | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
     449  | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
     450  | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
     451  | View.SYSTEM_UI_FLAG_FULLSCREEN
     452  | View.SYSTEM_UI_FLAG_IMMERSIVE
     453  | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
     454}}}
     455
     456See Also:
     457 - [http://developer.android.com/training/system-ui/immersive.html Immersive Full-Screen Mode]
     458 - [wiki:Android/Kiosk#lock-task-mode Lock Task Mode]