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