- Objective-C for Android
- At Apportable, we believe:
- About Apportable
- What exactly is the Apportable SDK?
- The Apportable SDK compiles your Objective-C (iOS) source code into a native application that runs on Android
- What Apportable is NOT
- How does Apportable work exactly?
- What trickery is this?
- Lets port something!
- The Apportable SDK includes.
- Frameworks and libraries
- The same clang compiler used in Xcode
- Debugging and tools
- Support for many binary 3rd party libraries
- The Best Features
- Essentially, you ship a user land implementation of the iOS libraries in your app with Apportable.
- We have done the hard work of supporting the fragmentation in Android
- Customizing For Android
- Customizing your Android build
- Support More Screen Resolutions
- Add Hardware Button Support
- Use different device information
- BridgeKit
- Bridging Application Lifecycle
- Push Notifications and Local Notifications
- In App Purchasing (StoreKit)
- Framework Support
- iOS 7 Features
- OpenGL based UIKit preview
- Objective-C for Android
- At Apportable, we believe:
- About Apportable
- What exactly is the Apportable SDK?
- The Apportable SDK compiles your Objective-C (iOS) source code into a native application that runs on Android
- What Apportable is NOT
- How does Apportable work exactly?
- What trickery is this?
- Lets port something!
- The Apportable SDK includes.
- Frameworks and libraries
- The same clang compiler used in Xcode
- Debugging and tools
- Support for many binary 3rd party libraries
- The Best Features
- Essentially, you ship a user land implementation of the iOS libraries in your app with Apportable.
- We have done the hard work of supporting the fragmentation in Android
- Customizing For Android
- Customizing your Android build
- Support More Screen Resolutions
- Add Hardware Button Support
- Use different device information
- BridgeKit
- Bridging Application Lifecycle
- Push Notifications and Local Notifications
- In App Purchasing (StoreKit)
- Framework Support
- iOS 7 Features
- OpenGL based UIKit preview
- Запуск objective-c кода на Android устройствах
- Начало истории
- Собственно тема
- Apportable SDK — Objective-C/Cocoa Touch для Android
Objective-C for Android
At Apportable, we believe:
About Apportable
- Founded Winter 2011 with YCombinator
- First app, Osmos, shipped January, 2012
- Raised $2.4m led by Google Ventures
- Today power dozens of best sellers on Android
What exactly is the Apportable SDK?
The Apportable SDK compiles your Objective-C (iOS) source code into a native application that runs on Android
What Apportable is NOT
- It is NOT source code translation
- It does NOT generate Java
- It is NOT an iOS emulator on Android (i.e. WINE)
How does Apportable work exactly?
What trickery is this?
Lets port something!
- Visit www.apportable.com and sign up
- Install the SDK and toolchain
- Open a terminal and navigate to your source code
- Plugin an Android device
- Run apportable load and answer a few questions about your app
- Thats it. You should see your app running on Android!
The Apportable SDK includes.
Frameworks
and libraries
The same clang compiler used in Xcode
Debugging and tools
- Latest GDB
- Our own Apportable profiler suite
- memory, network, performance
- resembles a mini instruments
Support for many binary 3rd party libraries
The Best Features
- ARC
- C++11
- Assembly
- Objective-C literals
- Objective-C Runtime API (swizzling, etc)
Essentially, you ship a user land implementation of the iOS libraries in your app with Apportable.
We have done the hard work of supporting the fragmentation in Android
Customizing For Android
Customizing your Android build
- Edit the .approj directory generated next to xcode project
- In the
.approj/configuration.json file you can:
- Add and remove source files
- Tweak the APKs features and permissions on Android
- Change defines, icons, and other settings
Support More Screen Resolutions
- Handling the native resolution is best and will always look the better
- If you made assumptions about iOS screen sizes, you can emulate them on Android and scale your UI up with UIScreenModes
Add Hardware Button Support
Use different device information
BridgeKit
- BridgeKit is a fully Objective-C API for bridging to Java and calling Android APIs or custom Java code
- Used to back much of UIKit and system APIs
Bridging Application Lifecycle
- Apportable backs iOS lifecycle events with their Android counterparts
- application:didFinishLaunchingWithOptions: — -> Activity.onCreate
- applicationDidBecomeActive: —> Activity.onResume
- applicationDidEnterBackground: —> Activity.onStop
- When apps are in the background, Apportable emulates iOS behavior by suspending them
Push Notifications and Local Notifications
- Push notifications are handled by Google Cloud Messaging on Google Play Apps
- Other push notification services such as Parse and Urban Airship are supported as well
- Local notifications translate to a custom alarm service
In App Purchasing (StoreKit)
- Apportable store kit bridges to Google In App Billing (on Google Play) and Amazon Payments (on Amazon App Store)
- Near full StoreKit compatibility
Framework Support
Foundation — Near full coverage. Major revision in development
CoreFoundation — Common classes covered. Full support in development
CoreAnimation — Limited. New version in development backed by OpenGL
UIKit — Current shipping version is limited to simple UIKit apps. Full UIKit support backed by new CoreAnimation in development
CoreData — Working. Limited to automatic migration support only
AVFoundation — Audio but no video support
MediaPlayer — Video and audio supported (codecs depend on device, ogg is the most universal)
iOS 7 Features
- SpriteKit — In development; currently 20% faster than iOS (even on iOS)
- GameController API ready
OpenGL based UIKit preview
Источник
Objective-C for Android
At Apportable, we believe:
About Apportable
- Founded Winter 2011 with YCombinator
- First app, Osmos, shipped January, 2012
- Raised $2.4m led by Google Ventures
- Today power dozens of best sellers on Android
What exactly is the Apportable SDK?
The Apportable SDK compiles your Objective-C (iOS) source code into a native application that runs on Android
What Apportable is NOT
- It is NOT source code translation
- It does NOT generate Java
- It is NOT an iOS emulator on Android (i.e. WINE)
How does Apportable work exactly?
What trickery is this?
Lets port something!
- Visit www.apportable.com and sign up
- Install the SDK and toolchain
- Open a terminal and navigate to your source code
- Plugin an Android device
- Run apportable load and answer a few questions about your app
- Thats it. You should see your app running on Android!
The Apportable SDK includes.
Frameworks
and libraries
The same clang compiler used in Xcode
Debugging and tools
- Latest GDB
- Our own Apportable profiler suite
- memory, network, performance
- resembles a mini instruments
Support for many binary 3rd party libraries
The Best Features
- ARC
- C++11
- Assembly
- Objective-C literals
- Objective-C Runtime API (swizzling, etc)
Essentially, you ship a user land implementation of the iOS libraries in your app with Apportable.
We have done the hard work of supporting the fragmentation in Android
Customizing For Android
Customizing your Android build
- Edit the .approj directory generated next to xcode project
- In the
.approj/configuration.json file you can:
- Add and remove source files
- Tweak the APKs features and permissions on Android
- Change defines, icons, and other settings
Support More Screen Resolutions
- Handling the native resolution is best and will always look the better
- If you made assumptions about iOS screen sizes, you can emulate them on Android and scale your UI up with UIScreenModes
Add Hardware Button Support
Use different device information
BridgeKit
- BridgeKit is a fully Objective-C API for bridging to Java and calling Android APIs or custom Java code
- Used to back much of UIKit and system APIs
Bridging Application Lifecycle
- Apportable backs iOS lifecycle events with their Android counterparts
- application:didFinishLaunchingWithOptions: — -> Activity.onCreate
- applicationDidBecomeActive: —> Activity.onResume
- applicationDidEnterBackground: —> Activity.onStop
- When apps are in the background, Apportable emulates iOS behavior by suspending them
Push Notifications and Local Notifications
- Push notifications are handled by Google Cloud Messaging on Google Play Apps
- Other push notification services such as Parse and Urban Airship are supported as well
- Local notifications translate to a custom alarm service
In App Purchasing (StoreKit)
- Apportable store kit bridges to Google In App Billing (on Google Play) and Amazon Payments (on Amazon App Store)
- Near full StoreKit compatibility
Framework Support
Foundation — Near full coverage. Major revision in development
CoreFoundation — Common classes covered. Full support in development
CoreAnimation — Limited. New version in development backed by OpenGL
UIKit — Current shipping version is limited to simple UIKit apps. Full UIKit support backed by new CoreAnimation in development
CoreData — Working. Limited to automatic migration support only
AVFoundation — Audio but no video support
MediaPlayer — Video and audio supported (codecs depend on device, ogg is the most universal)
iOS 7 Features
- SpriteKit — In development; currently 20% faster than iOS (even on iOS)
- GameController API ready
OpenGL based UIKit preview
Источник
Запуск objective-c кода на Android устройствах
Начало истории
Пришел мне на доработку проект написанный на cocos2d. Игра для детей, в которой необходимо собирать пазлы и учить слова. Работа как работа, но главная проблема заключалась в том, что до меня над проектом работала некая девушка из Индии. И тут у меня начался очень веселый период. Пример того, на что мне пришлось смотреть, что делать и чем все это закончилось, будет под катом.
Однако пост не об ошибках, которые мне пришлось исправлять, а совсем о другой проблеме.
Через несколько месяцев работы над проектом, когда основные проблемы были решены, заказчик попросил собрать билд под его Android девайс. Далее шел удивительный разговор о том, что первый разработчик должен был писать под cocos2d-x и приложение должно легко запускаться на любом устройстве. Решать проблему пришлось уже мне и мой выбор пал на Apportable.
Собственно тема
Как утверждает официальный сайт, Apportable SDK — это система, которая позволяет запускать один и тот же xCode проект на iOS и Android устройствах. В первую очередь, это касается игр написаных на cocos2d. C портирование некоторых системных Core фреймворков есть проблемы.
Наша игра была написана практически на чистом кокосе и только в двух местах использовались UIKit элементы.
Ну что же. Приступим.
Первое, что необходимо сделать — установить SDK на Mac. Для этого, следуя инструкциям на сайте, необходимо просто ввести в терминале
SDK требует около 2гб свободного места на диске и установленного xCode 5.
Пока все это скачивается, можно дописать в наш проект необходимый код.
Сначала установим режим эммулирования экрана. Тут есть несколько варианта.
Например:
UIScreenIPhone3GEmulationMode — используется, если ваше приложение не будет поддерживать графику от retina устройств. Размер виртуального экрана 320px/480px, scale — 1.0
UIScreenScaledAspectFitEmulationMode — растягивает ваше приложение в соответсвии с размером экрана Android устройства. Использует не retina графику.
UIScreenBestEmulatedMode — растягивает ваше приложение в соответсвии с размером экрана Android устройства. Использует наиболее подходящую графику. Для корректной работы этого режима должна быть графика для всех вариантов iPhone и iPad экранов. Иначе может выглядеть совсем не best.
Следующее что пришлось переделывать — позиции элементов.
Тоже самое при отслеживании нажатий.
После этого надо перейти в терминале в папку с проектом и ввести:
Эта команда создаст apk файл, загрузит его на подключенное устройство, установит и запустит. В идеальном варианте. Он бывает не всегда. Я не буду рассматривать ошибки линковки файлов, они очень индивидуальны. Однако бывает ситуация когда apportable не видит какой-то определенный девайс. На офисе из 7 устройств, на которых я тестировал приложение, не смог установить на 3.
Что делать в таком случае? Все очень просто. Apportable сначала создает apk файл и только потом пытается загрузить его на устройство. Значит этот файл где-то есть. Если более точно, то вот здесь:
В этой папке лежит apk файл и его можно просто перекинуть на девайс и установить. Для этого я использовал приложение Android File Transfer(в маке из коробки нельзя обращаться к памяти Android устройств).
Все? Профит? К сожалению нет.
Возникла проблема с фотокамерой. Камера вызывалась, делала фотографию, но при нажатии кнопки подтверждения, приложение падало. Проблема не гуглилась и обещала принести большие проблемы, но… Помощь пришла от наших android разработчиков. Я узнал, что такое манифест и пермишены.
И так. После создания билда с помощью apportable, в директории с проектом появилась папка ProjectName.aproj. В этой папке лежат конфигурационные файлы и файлы, которые не компилируются(например ресурсы).
Нас интересует файл configuration.json. В нем можно изменить настройки компиляции проекта для android. Например, добавить пермишены. Для работы фотокамеры нужны права на запись.
И изменение строки
волшебным образом решило проблему.
Также есть нюанс с локализацией имени приложения на экране устройства. Для каждого языка необходимо добавить файл strings.xml и положить в папку ProjectName/java/res/values-[lang_description]
И добавить в configuration.json:
Несколько моментов на последок:
- Рамеров экранов у Android устройств очень много, и кое-где приходилось использовать следующие вставки:
Источник
Apportable SDK — Objective-C/Cocoa Touch для Android
Apportable SDK — это продукт, который позволяет без изменений скомпилировать игру (или приложение), разработанное на Objective-C/Cocoa Touch для iOS под Android. Это полный toolchain (компилятор, дебаггер, линковщик — все-все-все), работающие Foundation, CoreFoundation, UIKit, множество других фреймворков из состава iOS, перенесенные на Android (даже такая «мелочь» как GameKit и StoreKit, с бэкендами для GooglePlus и Amazon GameCircle/Appstore).
Цель Apportable — дать iOS разработчику перенести свое приложение на Android за час, без изменения кода, и поддерживать после этого одну кодовую базу. Как портировать простую игрушку на cocos2d — под катом
Заходим на сайт Apportable.
После регистрации нам дают выкачать SDK, ссылка специфичная для пользователя.
Выкачиваться оно будет очень долго — Apportable использует патченные android-sdk, ndk и прочую тяжелую артиллерию.
После установки оно скажет:
Toolchain downloaded into /Users/darvin/.apportable/toolchain.
Apportable CLI is successfully installed at /Users/darvin/.apportable/SDK/bin/apportable
If you’re using the default shell, add the Apportable CLI to your PATH using:
(echo; echo ‘PATH=»/Users/darvin/.apportable/SDK/bin:$PATH»‘) >>
Теперь выкачаем нашего подопытного кролика, какую-нибудь рандомную опенсорсную игру с гитхаба, запиленную на Objective-C/Cocos-2d (поддержка cocos2d у apportable особо хороша, они даже являются оффициальным спонсором cocos2d). Дисклеймер: автор не имеет никаго отношения к подопытной игре, она совершенно не адаптированна для Apportable SDK, просто игра на cocos2d
Проверяем, чтобы компилировалось из XCode:
Подключаем любимый Нексус (или галакси, или нонейм-китайца без google-apps — нет почти никакой разницы), запускаем утилиту, которая создаст climbers.approj (это набор настроек для Apportable, которые накладываются поверх .xcodeproj), скомпилирует проект и загрузит его на девайс:
Утилита вначале спросит:
If the app is using OpenGL ES, does it use ES1 or ES2? (Cocos2D 1.X uses ES1, 2.X uses ES2)
[1/2] 1
Should the app initially launch in landscape or portrait orientation? (default: landscape)
[L/p] p
Игрушка использует Cocos2D 1.X, так что отвечаем «1», второй вопрос — «p».
После первой попытки компиляция отваливается с сообщениями об ошибках:
/Users/darvin/GAMES/climbers/Support/CocosDenshion/CDAudioManager.m:322: error: undefined reference to ‘AudioSessionGetProperty’
/Users/darvin/GAMES/climbers/Support/CocosDenshion/CDAudioManager.m:382: error: undefined reference to ‘AVAudioSessionCategoryPlayAndRecord’
. вырезано.
/Users/darvin/GAMES/climbers/Support/CocosDenshion/CDOpenALSupport.m:227: error: undefined reference to ‘ExtAudioFileDispose’
Updating Jar.
scons: *** [Build/android-armeabi-debug/climbers/apk/lib/armeabi/libverde.so] Error 1
scons: building terminated because of errors.
Оно жалуется на отсутствующие AudioFile* функции… Гугль подсказывает, что они находятся в фреймворке AudioToolbox. Ну что ж…
В разделе «add_params» находим строки:
Игра загружена на подключенный Android мобильник, даже есть звук. Графика немного сьехала — разработчик не расчитывал на разные разрешения андроидофонов, впрочем, это легко (и нужно) исправить, если же адаптировать графику лень, Apportable представляет workaround, который будет масштабировать графику, как если бы игра была запущена на iOS девайсе. Давайте попробуем второй путь:
В начале -[AppDelegate applicationDidFinishLaunching:] добавим:
Здесь мы выставляем лучший режим эмуляции для девайса — если его разрешение/пропорции похожи на iPad — он будет эмулировать iPad, если на iPhone — iPhone.
Также стоит удалить ненужный код выбора ориентации:
Сохраняем, запускаем коммандой apportable load. Видим Objective-C/Cocos 2d игрушку на Нексусе:
Доступна документация и список рассылки. Также наши специально обученные инженеры мониторят тэг на StackOverflow. Видео сессии портирования tweejump.
Starter редакция SDK бесплатна, подерживается Android 4+. Лучше всего Apportable подходит для портирования игр — у приложений все равно разные гайдлайны UI, a игры уже обкатаны на множестве лидеров аппстора. Буду рад ответить на любые вопросы, в следующей статье собираюсь рассказать как быстро и безболезненно выдрать возникающие при портировании баги и прозрачно, без изменения кодовой базы интегрировать социальные фреймворки, StoreKit и GameKit.
Источник