9b6ba5a929dceea26f8aaa87a7592c6be643a83e
[platform/upstream/opencv.git] / doc / tutorials / introduction / android_binary_package / android_dev_intro.markdown
1 Introduction into Android Development {#tutorial_android_dev_intro}
2 =====================================
3
4 @prev_tutorial{tutorial_clojure_dev_intro}
5 @next_tutorial{tutorial_O4A_SDK}
6
7
8 This guide was designed to help you in learning Android development basics and setting up your
9 working environment quickly. It was written with Windows 7 in mind, though it would work with Linux
10 (Ubuntu), Mac OS X and any other OS supported by Android SDK.
11
12 If you encounter any error after thoroughly following these steps, feel free to contact us via
13 [OpenCV4Android](https://groups.google.com/group/android-opencv/) discussion group or OpenCV [Q&A
14 forum](http://answers.opencv.org). We'll do our best to help you out.
15
16 Preface
17 -------
18
19 Android is a Linux-based, open source mobile operating system developed by Open Handset Alliance led
20 by Google. See the [Android home site](http://www.android.com/about/) for general details.
21
22 Development for Android significantly differs from development for other platforms. So before
23 starting programming for Android we recommend you make sure that you are familiar with the following
24 key topis:
25
26 -#  [Java](http://en.wikipedia.org/wiki/Java_(programming_language)) programming language that is
27     the primary development technology for Android OS. Also, you can find [Oracle docs on
28     Java](http://docs.oracle.com/javase/) useful.
29 -#  [Java Native Interface (JNI)](http://en.wikipedia.org/wiki/Java_Native_Interface) that is a
30     technology of running native code in Java virtual machine. Also, you can find [Oracle docs on
31     JNI](http://docs.oracle.com/javase/7/docs/technotes/guides/jni/) useful.
32 -#  [Android
33     Activity](http://developer.android.com/training/basics/activity-lifecycle/starting.html) and its
34     lifecycle, that is an essential Android API class.
35 -#  OpenCV development will certainly require some knowledge of the [Android
36     Camera](http://developer.android.com/guide/topics/media/camera.html) specifics.
37
38 Manual environment setup for Android development
39 ------------------------------------------------
40
41 ### Development in Java
42
43 You need the following software to be installed in order to develop for Android in Java:
44
45 -#  **Sun JDK 6** (Sun JDK 7 is also possible)
46
47     Visit [Java SE Downloads page](http://www.oracle.com/technetwork/java/javase/downloads/) and
48     download an installer for your OS.
49
50     Here is a detailed JDK (Java Development Kit) [installation
51     guide](http://source.android.com/source/initializing.html#installing-the-jdk) for Ubuntu and Mac
52     OS (only JDK sections are applicable for OpenCV)
53
54     @note OpenJDK is not suitable for Android development, since Android SDK supports only Sun JDK. If you use Ubuntu, after installation of Sun JDK you should run the following command to set Sun java environment:
55         @code{.bash}
56         sudo update-java-alternatives --set java-6-sun
57         @endcode
58
59 -#  **Android SDK**
60
61     Get the latest Android SDK from <http://developer.android.com/sdk/index.html>
62
63     Here is Google's [install guide](http://developer.android.com/sdk/installing.html) for the SDK.
64
65     @note You can choose downloading **ADT Bundle package** that in addition to Android SDK Tools
66     includes Eclipse + ADT + NDK/CDT plugins, Android Platform-tools, the latest Android platform and
67     the latest Android system image for the emulator - this is the best choice for those who is setting
68     up Android development environment the first time!
69
70     @note If you are running x64 version of Ubuntu Linux, then you need ia32 shared libraries for use on amd64 and ia64 systems to be installed. You can install them with the following command:
71        @code{.bash}
72         sudo apt-get install ia32-libs
73         @endcode
74         For Red Hat based systems the following command might be helpful:
75         @code{.bash}
76         sudo yum install libXtst.i386
77         @endcode
78
79 -#  **Android SDK components**
80
81     You need the following SDK components to be installed:
82
83     -   *Android SDK Tools, revision 20* or newer.
84
85         Older revisions should also work, but they are not recommended.
86
87     -   *SDK Platform Android 3.0* (API 11).
88
89         The minimal platform supported by OpenCV Java API is **Android 2.2** (API 8). This is also
90         the minimum API Level required for the provided samples to run. See the
91         \<uses-sdk android:minSdkVersion="8"/\> tag in their **AndroidManifest.xml** files. But for
92         successful compilation the **target** platform should be set to Android 3.0 (API 11) or
93         higher. It will not prevent them from running on Android 2.2.
94
95         ![](images/android_sdk_and_avd_manager.png)
96
97         See [Adding Platforms and
98         Packages](http://developer.android.com/sdk/installing/adding-packages.html) for help with
99         installing/updating SDK components.
100
101 -#  **Eclipse IDE**
102
103     Check the [Android SDK System Requirements](http://developer.android.com/sdk/requirements.html)
104     document for a list of Eclipse versions that are compatible with the Android SDK. For OpenCV
105     2.4.x we recommend **Eclipse 3.7 (Indigo)** or **Eclipse 4.2 (Juno)**. They work well for OpenCV
106     under both Windows and Linux.
107
108     If you have no Eclipse installed, you can get it from the [official
109     site](http://www.eclipse.org/downloads/).
110
111 -#  **ADT plugin for Eclipse**
112
113     These instructions are copied from [Android Developers
114     site](http://developer.android.com/sdk/installing/installing-adt.html), check it out in case of
115     any ADT-related problem.
116
117     Assuming that you have Eclipse IDE installed, as described above, follow these steps to download
118     and install the ADT plugin:
119
120     -#  Start Eclipse, then select Help --\> Install New Software...
121     -#  Click Add (in the top-right corner).
122     -#  In the Add Repository dialog that appears, enter "ADT Plugin" for the Name and the following
123         URL for the Location: <https://dl-ssl.google.com/android/eclipse/>
124
125     -#  Click OK
126
127         @note If you have trouble acquiring the plugin, try using "http" in the Location URL, instead of "https" (https is preferred for security reasons).
128
129     -#  In the Available Software dialog, select the checkbox next to Developer Tools and click Next.
130
131     -#  In the next window, you'll see a list of the tools to be downloaded. Click Next.
132
133         @note If you also plan to develop native C++ code with Android NDK don't forget to enable NDK Plugins installations as well.
134
135         ![](images/eclipse_inst_adt.png)
136
137     -#  Read and accept the license agreements, then click Finish.
138
139         @note If you get a security warning saying that the authenticity or validity of the software can't be established, click OK.
140
141     -#  When the installation completes, restart Eclipse.
142
143 ### Native development in C++
144
145 You need the following software to be installed in order to develop for Android in C++:
146
147 -#  **Android NDK**
148
149     To compile C++ code for Android platform you need Android Native Development Kit (*NDK*).
150
151     You can get the latest version of NDK from the [download
152     page](http://developer.android.com/tools/sdk/ndk/index.html). To install Android NDK just
153     extract the archive to some folder on your computer. Here are [installation
154     instructions](http://developer.android.com/tools/sdk/ndk/index.html#Installing).
155
156     @note Before start you can read official Android NDK documentation which is in the Android NDK
157     archive, in the folder `docs/`. The main article about using Android NDK build system is in the
158     `ANDROID-MK.html` file. Some additional information you can find in the `APPLICATION-MK.html`,
159     `NDK-BUILD.html` files, and `CPU-ARM-NEON.html`, `CPLUSPLUS-SUPPORT.html`, `PREBUILTS.html`.
160
161 -#  **CDT plugin for Eclipse**
162
163     If you selected for installation the NDK plugins component of Eclipse ADT plugin (see the picture
164     above) your Eclipse IDE should already have CDT plugin (that means C/C++ Development Tooling).
165     There are several possible ways to integrate compilation of C++ code by Android NDK into Eclipse
166     compilation process. We recommend the approach based on Eclipse CDT(C/C++ Development Tooling)
167     Builder.
168
169 Android application structure
170 -----------------------------
171
172 Usually source code of an Android application has the following structure:
173
174 -   `root folder of the project/`
175     -   `jni/`
176     -   `libs/`
177     -   `res/`
178     -   `src/`
179     -   `AndroidManifest.xml`
180     -   `project.properties`
181     -   `... other files ...`
182
183 Where:
184
185 -   the `src` folder contains Java code of the application,
186 -   the `res` folder contains resources of the application (images, xml files describing UI layout,
187     etc),
188 -   the `libs` folder will contain native libraries after a successful build,
189 -   and the `jni` folder contains C/C++ application source code and NDK's build scripts `Android.mk`
190     and `Application.mk` producing the native libraries,
191 -   `AndroidManifest.xml` file presents essential information about application to the Android
192     system (name of the Application, name of main application's package, components of the
193     application, required permissions, etc).
194
195     It can be created using Eclipse wizard or android tool from Android SDK.
196
197 -   `project.properties` is a text file containing information about target Android platform and
198     other build details. This file is generated by Eclipse or can be created with android tool
199     included in Android SDK.
200
201 @note Both `AndroidManifest.xml` and `project.properties` files are required to compile the C++ part
202 of the application, since Android NDK build system relies on them. If any of these files does not
203 exist, compile the Java part of the project before the C++ part.
204
205 `Android.mk` and `Application.mk` scripts
206 -----------------------------------------
207
208 The script `Android.mk` usually has the following structure:
209 @code{.make}
210 LOCAL_PATH := \f$(call my-dir)
211
212 include \f$(CLEAR_VARS)
213 LOCAL_MODULE    := <module_name>
214 LOCAL_SRC_FILES := <list of .c and .cpp project files>
215 <some variable name> := <some variable value>
216 ...
217 <some variable name> := <some variable value>
218
219 include \f$(BUILD_SHARED_LIBRARY)
220 @endcode
221 This is the minimal file `Android.mk`, which builds C++ source code of an Android application. Note
222 that the first two lines and the last line are mandatory for any `Android.mk`.
223
224 Usually the file `Application.mk` is optional, but in case of project using OpenCV, when STL and
225 exceptions are used in C++, it also should be created. Example of the file `Application.mk`:
226 @code{.make}
227 APP_STL := gnustl_static
228 APP_CPPFLAGS := -frtti -fexceptions
229 APP_ABI := all
230 @endcode
231
232 @note We recommend setting APP_ABI := all for all targets. If you want to specify the target
233 explicitly, use armeabi for ARMv5/ARMv6, armeabi-v7a for ARMv7, x86 for Intel Atom or mips for MIPS.
234
235 @anchor tutorial_android_dev_intro_ndk
236 Building application native part from command line
237 --------------------------------------------------
238
239 Here is the standard way to compile C++ part of an Android application:
240
241 **warning**
242
243 We strongly recommend using cmd.exe (standard Windows console) instead of Cygwin on
244    **Windows**. Use the latter if only you're absolutely sure about, what you're doing. Cygwin is
245     not really supported and we are unlikely to help you in case you encounter some problems with
246     it. So, use it only if you're capable of handling the consequences yourself.
247
248 -#  Open console and go to the root folder of an Android application
249     @code{.bash}
250     cd <root folder of the project>/
251     @endcode
252 -#  Run the following command
253     @code{.bash}
254     <path_where_NDK_is_placed>/ndk-build
255     @endcode
256     @note On Windows we recommend to use ndk-build.cmd in standard Windows console (cmd.exe) rather than the similar bash script in Cygwin shell.
257        ![](images/ndk_build.png)
258
259 -#  After executing this command the C++ part of the source code is compiled.
260
261 After that the Java part of the application can be (re)compiled (using either *Eclipse* or *Ant*
262 build tool).
263
264 @note Some parameters can be set for the ndk-build:
265    **Example 1**: Verbose compilation
266     @code{.bash}
267     <path_where_NDK_is_placed>/ndk-build V=1
268     @endcode
269     **Example 2**: Rebuild all
270     @code{.bash}
271     <path_where_NDK_is_placed>/ndk-build -B
272     @endcode
273
274 @anchor tutorial_android_dev_intro_eclipse
275 Building application native part from *Eclipse* (CDT Builder)
276 -------------------------------------------------------------
277
278 There are several possible ways to integrate compilation of native C++ code by Android NDK into
279 Eclipse build process. We recommend the approach based on Eclipse CDT(C/C++ Development Tooling)
280 Builder.
281
282 **important**
283
284 OpenCV for Android package since version 2.4.2 contains sample projects
285    pre-configured CDT Builders. For your own projects follow the steps below.
286
287 -#  Define the NDKROOT environment variable containing the path to Android NDK in your system (e.g.
288     "X:\\Apps\\android-ndk-r8" or "/opt/android-ndk-r8").
289
290     **On Windows** an environment variable can be set via
291     My Computer -\> Properties -\> Advanced -\> Environment variables. On Windows 7 it's also
292     possible to use [setx](http://ss64.com/nt/setx.html) command in a console session.
293
294     **On Linux** and **MacOS** an environment variable can be set via appending a
295     "export VAR_NAME=VAR_VALUE" line to the `"~/.bashrc"` file and logging off and then on.
296
297     @note It's also possible to define the NDKROOT environment variable within Eclipse IDE, but it
298     should be done for every new workspace you create. If you prefer this option better than setting
299     system environment variable, open Eclipse menu
300     Window -\> Preferences -\> C/C++ -\> Build -\> Environment, press the Add... button and set variable
301     name to NDKROOT and value to local Android NDK path. \#. After that you need to **restart Eclipse**
302     to apply the changes.
303
304 -#  Open Eclipse and load the Android app project to configure.
305
306 -#  Add C/C++ Nature to the project via Eclipse menu
307     New -\> Other -\> C/C++ -\> Convert to a C/C++ Project.
308     ![](images/eclipse_cdt_cfg1.png)
309     And:
310     ![](images/eclipse_cdt_cfg2.png)
311
312 -#  Select the project(s) to convert. Specify "Project type" = Makefile project, "Toolchains" =
313     Other Toolchain.
314     ![](images/eclipse_cdt_cfg3.png)
315
316 -#  Open Project Properties -\> C/C++ Build, uncheck Use default build command, replace "Build
317     command" text from "make" to
318
319     "${NDKROOT}/ndk-build.cmd" on Windows,
320
321     "${NDKROOT}/ndk-build" on Linux and MacOS.
322
323     ![](images/eclipse_cdt_cfg4.png)
324
325 -#  Go to Behaviour tab and change "Workbench build type" section like shown below:
326
327     ![](images/eclipse_cdt_cfg5.png)
328
329 -#  Press OK and make sure the ndk-build is successfully invoked when building the project.
330
331     ![](images/eclipse_cdt_cfg6.png)
332
333 -#  If you open your C++ source file in Eclipse editor, you'll see syntax error notifications. They
334     are not real errors, but additional CDT configuring is required.
335
336     ![](images/eclipse_cdt_cfg7.png)
337
338 -#  Open Project Properties -\> C/C++ General -\> Paths and Symbols and add the following
339     **Include** paths for **C++**:
340     @code
341         # for NDK r8 and prior:
342         ${NDKROOT}/platforms/android-9/arch-arm/usr/include
343         ${NDKROOT}/sources/cxx-stl/gnu-libstdc++/include
344         ${NDKROOT}/sources/cxx-stl/gnu-libstdc++/libs/armeabi-v7a/include
345         ${ProjDirPath}/../../sdk/native/jni/include
346
347         # for NDK r8b and later:
348         ${NDKROOT}/platforms/android-9/arch-arm/usr/include
349         ${NDKROOT}/sources/cxx-stl/gnu-libstdc++/4.6/include
350         ${NDKROOT}/sources/cxx-stl/gnu-libstdc++/4.6/libs/armeabi-v7a/include
351         ${ProjDirPath}/../../sdk/native/jni/include
352     @endcode
353     The last path should be changed to the correct absolute or relative path to OpenCV4Android SDK
354     location.
355
356     This should clear the syntax error notifications in Eclipse C++ editor.
357
358     ![](images/eclipse_cdt_cfg8.png)
359
360 Debugging and Testing
361 ---------------------
362
363 In this section we will give you some easy-to-follow instructions on how to set up an emulator or
364 hardware device for testing and debugging an Android project.
365
366 ### AVD
367
368 AVD (*Android Virtual Device*) is not probably the most convenient way to test an OpenCV-dependent
369 application, but sure the most uncomplicated one to configure.
370
371 -#  Assuming you already have *Android SDK* and *Eclipse IDE* installed, in Eclipse go
372     Window -\> AVD Manager.
373 -#  Press the New button in AVD Manager window.
374 -#  Create new Android Virtual Device window will let you select some properties for your new
375     device, like target API level, size of SD-card and other.
376
377     ![](images/AVD_create.png)
378
379 -#  When you click the Create AVD button, your new AVD will be available in AVD Manager.
380 -#  Press Start to launch the device. Be aware that any AVD (a.k.a. Emulator) is usually much slower
381     than a hardware Android device, so it may take up to several minutes to start.
382 -#  Go Run -\> Run/Debug in Eclipse IDE to run your application in regular or debugging mode.
383     Device Chooser will let you choose among the running devices or to start a new one.
384
385 ### Hardware Device
386
387 If you have an Android device, you can use it to test and debug your applications. This way is more
388 authentic, though a little bit harder to set up. You need to make some actions for Windows and Linux
389 operating systems to be able to work with Android devices. No extra actions are required for Mac OS.
390 See detailed information on configuring hardware devices in subsections below.
391
392 You may also consult the official [Android Developers site
393 instructions](http://developer.android.com/tools/device.html) for more information.
394
395 #### Windows host computer
396
397 -#  Enable USB debugging on the Android device (via Settings menu).
398 -#  Attach the Android device to your PC with a USB cable.
399 -#  Go to Start Menu and **right-click** on Computer. Select Manage in the context menu. You may be
400     asked for Administrative permissions.
401 -#  Select Device Manager in the left pane and find an unknown device in the list. You may try
402     unplugging it and then plugging back in order to check whether it's your exact equipment appears
403     in the list.
404
405     ![](images/usb_device_connect_01.png)
406
407 -#  Try your luck installing Google USB drivers without any modifications: **right-click** on the
408     unknown device, select Properties menu item --\> Details tab --\> Update Driver button.
409
410     ![](images/usb_device_connect_05.png)
411
412 -#  Select Browse computer for driver software.
413
414     ![](images/usb_device_connect_06.png)
415
416 -#  Specify the path to `<Android SDK folder>/extras/google/usb_driver/` folder.
417
418     ![](images/usb_device_connect_07.png)
419
420 -#  If you get the prompt to install unverified drivers and report about success - you've finished
421     with USB driver installation.
422
423     ![](images/usb_device_connect_08.png)
424
425     ![](images/usb_device_connect_09.png)
426
427 -#  Otherwise (getting the failure like shown below) follow the next steps.
428
429     ![](images/usb_device_connect_12.png)
430
431 -#  Again **right-click** on the unknown device, select Properties --\> Details --\> Hardware Ids
432     and copy the line like `USB\VID_XXXX&PID_XXXX&MI_XX`.
433
434     ![](images/usb_device_connect_02.png)
435
436 -#  Now open file `<Android SDK folder>/extras/google/usb_driver/android_winusb.inf`. Select either
437     Google.NTx86 or Google.NTamd64 section depending on your host system architecture.
438
439     ![](images/usb_device_connect_03.png)
440
441 -#  There should be a record like existing ones for your device and you need to add one manually.
442
443     ![](images/usb_device_connect_04.png)
444
445 -#  Save the `android_winusb.inf` file and try to install the USB driver again.
446
447     ![](images/usb_device_connect_05.png)
448
449     ![](images/usb_device_connect_06.png)
450
451     ![](images/usb_device_connect_07.png)
452
453 -#  This time installation should go successfully.
454
455     ![](images/usb_device_connect_08.png)
456
457     ![](images/usb_device_connect_09.png)
458
459 -#  And an unknown device is now recognized as an Android phone.
460
461     ![](images/usb_device_connect_10.png)
462
463 -#  Successful device USB connection can be verified in console via adb devices command.
464
465     ![](images/usb_device_connect_11.png)
466
467 -#  Now, in Eclipse go Run -\> Run/Debug to run your application in regular or debugging mode.
468     Device Chooser will let you choose among the devices.
469
470 #### Linux host computer
471
472 By default Linux doesn't recognize Android devices, but it's easy to fix this issue. On Ubuntu Linux
473 you have to create a new **/etc/udev/rules.d/51-android.rules** configuration file that contains
474 information about your Android device. You may find some Vendor ID's
475 [here](http://developer.android.com/tools/device.html#VendorIds) or execute lsusb command to view
476 VendorID of plugged Android device. Here is an example of such file for LG device:
477 @code{.guess}
478 SUBSYSTEM=="usb", ATTR{idVendor}=="1004",  MODE="0666", GROUP="plugdev"
479 @endcode
480 Then restart your adb server (even better to restart the system), plug in your Android device and
481 execute adb devices command. You will see the list of attached devices:
482
483 ![](images/usb_device_connect_ubuntu.png)
484
485 #### Mac OS host computer
486
487 No actions are required, just connect your device via USB and run adb devices to check connection.
488
489 What's next
490 -----------
491
492 Now, when you have your development environment set up and configured, you may want to proceed to
493 installing OpenCV4Android SDK. You can learn how to do that in a separate @ref tutorial_O4A_SDK tutorial.