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