Free pascal android development

Android Programming/ru

Contents

Общие знания о программировании под Android могут очень помочь в разработке интерфейса Lazarus для Android.

Построить NDK (Android Native Development Kit) OpenGL

Просто выполните следующие действия:

Шаг 1 — Скачайте и установите Android NDK, Android SDK и Ant. Больше информации тут: Android_Interface/Using_the_Android_SDK,_Emulator_and_Phones/ru

Шаг 2 — Установите pre-compiled FPC cross-compiler. Инструкции здесь: Android_Interface#Using_the_pre-compiled_compiler

Шаг 3 — Загрузите последнюю версию lazarus-ccr sourceforge code:

или если вы думаете что это слишком много, вы можете скачать только каталог lazarus-ccr/bindings/android-ndk

Шаг 4 — Постройте Pascal Library

Откройте проект lazarus-ccr/bindings/android-ndk/examples/opengltest/opengltest.lpi

Откройте пункт меню Project->Project Options->Paths и где написано «Libraries -Fl» вы должны увидеть следующее значение:

Измените его на правильный путь, который указывает на библиотеку NDK с минимальной необходимой версией Android API Level

Теперь постройте проект используя Lazarus.

Шаг 5 — Настройка среды сборки

Откройте файл opengltest/local.properties и в строке:

Измените этот путь на местоположение SDK

Шаг 6 — Постройка APK

Откройте консоль и введите следущие команды:

Файл APK будет помещен в opengltest/android/bin/

Шаг 7 — Установка APK

Команда, чтобы установить APK на телефоне:

Если вы получили сообщение об ошибке, что APK уже установлен, вы можете установить его с помощью команды:

После можно запустить adb logcat чтобы увидеть журнал, в то время как вы запустите его в телефон через недавно добавленную иконку:

Получить параметры экрана

Вначале нужно заполнить TDisplayMetrics:

После вы можете получить информацию о дисплее из TDisplayMetrics:

Обратите внимание, что многие устройства врут о xdpi и ydpi, поэтому не стоит доверять lScreenSize, рассчитанному выше. Смартфоны могут сообщить о размере экрана 10 дюймов, хотя их настоящий размер может быть около 4.

Подробная информация об устройствах с Android

Поскольку существует так много Android устройств, эта информация может быть полезно для отслеживания информации о них. Смотрите также в википедии Сравнение устройств с Android и подробную информацию о процессорах в Android#System_Requirements.

Смартфоны

Производитель Модель Android API Name (Build.Model) Процессор Версия Android Мультитач Комментарий
HTC Wildfire HTC Wildfire armv6 2.1=>2.2 Да
Sony Erricson Xperia X10 X10i armv7 1.6=>2.1 Нет

Планшеты

Производитель Модель Android API Name (Build.Model) Процессор Версия Android Мультитач Комментарий
Toshiba Folio 100 Tablet TOSHIBA_FOLIO_AND_A armv7 2.2 Yes

Списки устройств сгруппированные по процессорам (ARMv6 vs ARMv7)

Список устройств на ARMv7:

  • Advent Vega (P10AN01)
  • Dell Streak, Streak 7
  • HTC Desire
  • HTC Desire Z (T-Mobile G2)
  • HTC Desire HD
  • HTC Droid Incredible
  • HTC EVO 4G, EVO Shift 4G
  • HTC Glacier (T-Mobile myTouch 4G)
  • HTC Inspire 4G
  • HTC Nexus One
  • HTC Thunderbolt 4G
  • Huawei Ideos S7
  • LG Optimus Z
  • Motorola Atrix 4G
  • Motorola Bravo
  • Motorola Cliq 2 — untested
  • Motorola Defy
  • Motorola Droid 2, Droid 2 Global
  • Motorola Droid Pro (Motorola PRO)
  • Motorola Droid X
  • Motorola Xoom
  • POV Mobii Tegra Tablet
  • Samsung Continuum (i400)
  • Samsung Galaxy S (i9000, Captivate, Fascinate, Vibrant, Epic 4G)
  • Samsung Galaxy Tab
  • Sharp IS03
  • Sony Ericsson Xperia X10
  • Toshiba AS100
  • Viewsonic gTablet
  • Acer Liquid E
  • Acer Liquid (Liquid A1)
  • Archos 101 Internet Tablet
  • Motorola Charm
  • Motorola Droid (Milestone)
  • Samsung Galaxy S 4G
  • Samsung Nexus S

Список устройств на ARMv6:

  • Android SDK emulator
  • Asus Garmin nuvifone A50 (T-Mobile Garminfone)
  • Augen GENTouch 78 Tablet
  • Coby Kyros Internet Tablet (MID7015)
  • Geeksphone One, Geeksphone Zero
  • HTC Aria
  • HTC ChaCha
  • HTC Dream (T-Mobile G1, Android Dev Phone 1)
  • HTC Droid Eris
  • HTC Espresso (T-Mobile myTouch 3G Slide)
  • HTC Hero (T-Mobile G2 Touch)
  • HTC Legend
  • HTC Magic (T-Mobile myTouch 3G, T-Mobile G1 Touch)
  • HTC Salsa
  • HTC Tattoo
  • HTC Wildfire
  • Huawei Ascend
  • Huawei Ideos U8150-B (T-Mobile Comet)
  • Huawei U8110 (T-Mobile Pulse Mini)
  • Huawei U8230
  • LG Ally (Apex) (LG VS740)
  • LG GW620 (Eve, InTouch Max, LinkMe)
  • LG Optimus, Optimus M, Optimus T, Optimus S, Optimus V
  • LG Vortex
  • LG P500
  • MAG iMiTO iM7
  • vMAG iMiTO iM7S
  • Motorola Backflip
  • Motorola Citrus
  • Motorola Cliq (MB200)
  • Motorola Dext
  • Motorola Devour
  • Motorola i1
  • Motorola Spice XT300
  • Motorola Quench XT5 XT502
  • Pandigital Novel
  • Samsung GT-S5570 Galaxy Mini
  • Samsung i5500 Galaxy 5 (Corby)
  • Samsung i5700 Galaxy Portal (Spica)
  • Samsung i5800 Galaxy 3
  • Samsung i7500 Galaxy
  • Samsung Intercept
  • Samsung M900 Moment
  • Samsung S5830 Galaxy Ace
  • Samsung Transform
  • Sanyo ZIO M6000
  • Sony Ericsson Xperia X8
  • Sony Ericsson Xperia X10 Mini
  • Sony Ericsson Xperia X10 Mini Pro
  • Superpad 10.2″ Tablet PC
  • Viewsonic ViewPad 7 Tablet
  • Velocity Micro T103 Cruz tablet
  • Vodafone 845
  • ZTE Blade
Читайте также:  Онкио плеер для андроид

Воспроизведение Аудио и Видео на телефонах

Каждый телефон поставляется со своим набором кодеков, поэтому на разных телефонах родной Media Player может воспроизводить разные форматы. Ниже приведена таблица, показывающая, какие форматы воспроизводит Media Player на каждом телефоне:

Телефон Android webm — VP8 m4v — H.264 ogv — Theora mp4 — H.264 mov — H.264 avi — RLE mpg — MPEG-1 wmv — WM9 3gp — MPEG-4
Emulator 1.6 x x x x x x x x OK
Emulator 2.1 x x x x x x x x OK
Nexus One 2.2 x OK x OK x x x x OK
HTC Desire 1.6 x OK x OK x x x OK OK
Toshiba Folio 100 2.2 x OK x OK x x x OK OK
Xperia X10 2.1 x OK x x x x x OK OK
Xperia X8 2.2 x OK x x x x x x OK
HTC Wildfire 2.1 x OK x x x x x x OK
HTC Desire HD 2.2 x OK x OK x x x x OK
Galaxy Tab 2.2 x OK x x x x x x OK
myPhone A210 1.6 x OK x x x x x x OK
Motorola Milestone 2.1 x OK x x x x x OK ?
Milestone 2 2.2 x OK x x x x x только звук OK

Файловая система Android

Рекомендуется использовать getApplicationContext().getFilesDir() чтобы получить путь к каталогу для хранения данных приложения. В HTC Wildfire эта функция возвращает /data/data/

Библиотеки приложения находятся в /data/data/

В папке /data/data/

есть разрешение на чтение и запись, можно создавать новые файлы и даже запускать их.

Создание нового Java Приложения для Android

Эта информация может быть полезна для реализации LCL-CustomDrawn-Android

Источник

FPC JVM Android Development

This article applies to Android only.

This page gives you an introduction for developing Android applications using the JVM Port of the FPC compiler. For native development for ARM/Android, please see here.

Contents

Prerequisites

You need to have the Android SDK installed (at least version 10 should be sufficient). For more information about installing the SDK please refer to the Android sites.

You also need the JDK (either the Oracle one or OpenJDK) and the JRE. To be more precise: the applications jarsigner and java must be available and depending on the method you choose below javac needs to be available as well.

At last you also need the FPC JVM compiler and the Jasmin assembler for which you should follow the guidelines written here.

Using Eclipse

Using Lazarus

Preparations

You should use a trunk version of Lazarus as this already contains a few extensions for language features used and implemented in the JVM port.

Also to simplyfy things a bit you might want to patch Lazarus and the compiler driver «fpc»:

Patching Lazarus

Apply the following patch to add support for the jvm platform and the android and arm operating systems (this patch is not yet reported, because first the JVM port should be merged back into FPC’s trunk):

Patching FPC

While every platform in Free Pascal has it’s own compiler binary (e.g. ppc386, ppcarm, etc.) there is the binary fpc which selects the correct compiler by interpreting the -Pxxx argument. To enable support for the jvm platform the source code of the fpc binary needs to be adjusted. For this you can use any source for this binary that’s younger than February 2010 (as this is where the last change was made). You can also simply download the source code file from FPC’s trunk (here) for this and compile that as there are no dependencies besides unit SysUtils.

Here is the patch:

After you compiled the fpc binary you can replace your old one with it and copy the ppcjvm to the directory where all other compilers are located. These are for the different platforms:

  • Windows: %fpcdir%\bin\i386-win32\ (or x86_64-win64 if you have a native 64-Bit installation)
  • Linux: $fpcdir/lib/fpc/$fpcversion/ (depending on your installation $fpcdir could be /, /usr or some directory in your home directory)
  • macOS: WRITE ME

Also you should copy the compiled units from your FPC JVM snapshot to the corresponding units directory of your installation:

  • Windows: from %fpcjvm%\units\jvm-android to %fpcdir%\units\jvm-android
  • Linux: from $fpcjvm/units/jvm-android to $fpcdir/lib/fpc/$fpcversion/units/jvm-android
  • macOS: WRITE ME

Also if you don’t want to copy the jasmin.jar to the same directory as the ppcjvm, you should adjust your fpc.cfg compiler by adding the following lines:

Generate a Key Store

Only signed Android packages can be deployed on any Android device (including the emulator) without exception. The only difference to Windows Phone and iOS is that it is sufficient if you sign them yourself (even if you deploy them to the Android market). This is done by creating a keystore which is later utilized by the jarsigner tool to sign the package.

Читайте также:  Android как пользоваться яндекс картами

Using the following command you can create such a key store if you haven’t one yet:

You can freely chose the location and name of the keystore file as well as the alias name. But you need both of the to sign an Android package. The tool will then ask you some questions and for the passwords for keystore and alias (you can use the same password for both or different ones).

Note: You should also follow the guidelines written on the Android developer sites so that your application might be approved for the Android market.

Structure of an Android application

An Android applications consists of the source code of the applications, some resources like images and XML files which describe the layout of the GUI (similar to LFMs) and a manifest file which describes options like the minimum SDK version or which activity is the main one.

This leads to another difference to e.g. Lazarus applications: an Android applications consists of at least one so called Activity, which can be thought of as a combination of Lazarus’ TForm and TApplication. Every activity that can be started must be defined in the manifest file (otherwise an exception occurs if one tries to start that activity). Activities are started using so called intents which tell the activity why they are started and are also used to send parameters to the activity. Thus the main project file of an Android is not a program file, but an unit which will contain at least one class that derives from android.app.Activity or one of its subclasses (like android.app.ListActivity). An activity then consists of a view which contain — depending on their class — one or more additional views which all together make up the GUI of an Android application. These views can either be instantiated at runtime by creating the view classes or by inflating a layout that is part of the resources. Handling events (e.g. reacting on the click of a button) is always done by specifying a class instance that implements the corresponding listener interface (Java does not support procedure/method variables).

Building an Android application

Summary

For building an Android applications multiple tools are necessary. First the resources need to be converted to binaries and added to a «resource package». Also the IDs they have in this resource package need to be added to a resource class (usally called R). Then the source code needs to be compiled (in our case using the FPC JVM compiler). After that the generated *.class files need to be converted to the Dalvik’s DEX format and combined with the resource package and the manifest these build a unsigned package (extension APK). This package then needs to be signed (using jarsigner) and can then be installed on the emulator or a device or (hopefully) be deployed to the Android market.

Used Directories

To simplyfy the given commandlines the following conventions are used:

  • $platform gives the platforms/android-VERSION/ directory of the Android SDK
  • $platformtools gives the platform-tools directory of the Android SDK
  • $tools gives the tools directory of the Android SDK

Directory layout

To avoid clutter in the project’s directory the following directory layout is suggested:

The manifest file

A basic manifest file looks like the following:

The attribute package gives the class path of your application. This will be used by the generation of the R.java and you should also use this at least for the $namespace option in units containing activities. The attributes containing «@» are references to resources in the res directory. Hereby the drawable is replaced by drawable-mdpi, drawable-hdpi or drawable-ldpi depending of the screen size at runtime. The value @string/app_name refers to the string app_name in the res/values/strings.xml file. TMyAppActivity is the main activity which will be invoked when started by the launcher. TSomeOtherActivity is for example some second application window. Both need to derive from android.app.Activity or one of its subclasses. Having targetSdkVersion and minSdkVersion set will avoid that compatibilty modules are used if you have a newer SDK version installed as well.

The resource files

The exact contents of your resource directory will depend on your application, but some generic advices can be given:

The drawable directories can contain a icon.png in different sizes (ldpi: 36×36, mdpi: 48×48, hdpi: 72×72).

For the contents of the layouts in the menu and layout directories I advice you to read the Android documentation.

Читайте также:  Ария тема для андроид

The values directory contains a strings.xml which looks like the following:

Generate the resource package

To generate the resource package and the R.java you can use the following command:

This will take all resources from the directory given by -S, the manifest file given by -M and the android.jar given by -I to generate the resource package given by -F and the R.java of which the base directory is given by -J (the remaining class path is extracted from the manifest).

The resource identifiers

The generated R.java file (located in gen/org/myname/myapp according to above shown manifest file) will look like the following (supposing that there is a layout for a dialog in res/layouts, two layouts for menus in res/menu and two more strings in res/values/strings.xml):

This class then needs to be converted to Pascal code in a unit I decided to call src/resources.pas (this needs to be done everytime you recreate the resources, because ID values might change then). The unit then looks like this:

You could also use global constants, but this way it looks more like the usual Android development.

Compiling the source

If you’ve followed the advice above regarding adjusting FPC and Lazarus you should be able to simply compile the code using Lazarus and setting the target to jvm-android. The unit output directory should also be set to bin/classes.

If you did not follow the advice you can create a script or a makefile containg the following command (note: you can not simply change the compiler, because Lazarus then does not know the target «android»):

You can then add this script, makefile or also the command itself to Lazarus’ pre or post build commands (Project => Project Settings => Compilation) and uncheck all checkboxes for the compilation command. For error locations you can also check the «FPC» checkbox next to «look for messages» for your command.

After the source is compiled you need to convert it to the format understood by Dalvik. For this you also need to copy all *.class files provided in the units/jvm-android directory and subdirectories to the bin/classes directory (it should be possible to put the RTL files into a JAR file as well, but this was not tested by me). Then you simply execute the following command:

Generating the package

Now you need to generate first a unsigned package out of the resources and the dex file. This is done using the following command:

The file given with -z is the resource package generated earlier.

Note: This tools will print a message that it is deprecated (which is true), but for now it still works. Until it is removed a solution for this needs to be found (maybe by developing a custom application around the Java class which does the hard work and which is not deprecated).

After the unsigned package is created it needs to be signed so it can be loaded to the emulator or device. For this the following command suffices:

The values /path/to/YourKeyStore.keystore and YourAlias are the same which you created earlier. You are then prompted for the passwords of the two.

Deploying the package

Using the adb tool the package can be directly installed to a running emulator or connected device (for more infos on the latter see here).

For the emulator use the following command:

For the device the following:

In both cases the -r tells adb to reinstall the application (thus application data like databases is kept).

You can uninstall an application (together with its user data) using the following command:

Use -d instead of -e if you want to do this on a connected device.

Hint: The uninstall command gives a good reason why you should use different namespaces for your application.

Finding errors

During the development of an Android application you might often see a dialog that informs you that your application has crashed. You can then use the $tools/adb tool with the «logcat» command which will cat the log of the device or emulator to your console (you need to use Ctrl+C to close it again). There you’ll see the name of the Exception class, its message and a stacktrace. You can also use the tool $tools/ddms which is a GUI application and represents the log to you in a colored way (depending on the severity of the log message). It also allows taking screenshots.

Источник

Оцените статью