- Запуск NodeJS-приложения на Android
- Termux
- Клавиатура
- NodeJS
- Express
- Nodemon
- MongoDB
- Getting Started: Android native apps¶
- Download the library¶
- Creating your First Project¶
- Android SDK Requirements¶
- Create an Android Studio Project¶
- Copy libnode’s header files¶
- Add native JNI function to start node.js¶
- Call startNodeWithArguments from Java¶
- Load libnode.so:¶
- Remove references to stringFromJNI ¶
- Start a background thread to run startNodeWithArguments ¶
- Specify required permissions in the manifest¶
- Add libnode.so to the project¶
- Copy the library files¶
- Configure CMake¶
- Configure the app’s gradle settings¶
- Add simple UI for testing¶
- Node.js for Mobile Apps core library v0.3.3
- Assets
- Node.js for Mobile Apps core library v0.3.2
- Assets
- Node.js for Mobile Apps core library v0.3.1
- Assets
- Node.js for Mobile Apps core library v0.3.0
- Assets
- Node.js for Mobile Apps core library v0.2.2
- How To Build Android Apps With Node JS Using Android JS
- Discussion
- What is Android JS?
- Assumptions & Requirements
- So let’s start with Installation Part
- Now let’s start building app
- So let’s start packaging process
- let’s start packaging app
Запуск NodeJS-приложения на Android
Без сомнения, вам понравится запускать NodeJS на своем Android-устройстве. Благодаря эмулятору терминала и Linux-окружения для Android, разработка веб-приложений на смартфоне перестанет быть для вас проблемой.
Termux
Termux — это бесплатное приложение, которое можно установить прямо из магазина Google Play. Требуется версия Android 5.0 или более поздняя. Не требует root-прав.
При открытии Termux вас приветствует интерфейс командной строки. Рекомендуется проверить наличие обновлений сразу после установки Termux. Введите следующую команду и нажмите Enter:
Termux поставляется в минимальной базовой комплектации, так что вы должны установить coreutils для полноценного использования команд командной строки, таких как mv, ls и др.
Termux хранит данные в собственном хранилище данных, т.е. папка $HOME находится внутри частной области Termux, как у обычного Android приложения. Удаление Termux вызовет потерю этих данных. Если вы собираетесь хранить там важные файлы, то используйте termux-setup-storage, чтобы обеспечить сохранение данных во внешнем хранилище (например на SD-карте).
Итак, давайте создадим папку для нашего приложения и перейдем в этот каталог:
Клавиатура
В этот момент вы, скорее всего, почувствуете некоторые проблемы при работе в консоли со стандартной клавиатурой. Чтобы обойти их, я установил хакерскую клавиатуру из Google play. Это сенсорная клавиатура, которая имеет все необходимое для написания кода — Esc, Tab и клавиши со стрелками.
Для написания кода нам понадобится любой текстовый редактор, доступный в консоли. Вы можете установить Emacs или Vim, но для простоты можно использовать nano. Установим его:
Создадим файл app.js и откроем его в редакторе:
Напишем какой-нибудь простой NodeJS-код для проверки:
Чтобы выйти из nano, нужно нажать Ctrl+X, написать ‘yes’ и нажать Enter.
NodeJS
Теперь самое время установить NodeJS. Сделать это очень просто:
Теперь мы можем наконец запустить наш скрипт:
Express
Вместе с NodeJS нам доступен пакетный менеджер npm. Давайте воспользуемся им:
Откроем app.js и напишем/скопи-пастим туда следующий код:
Это должно вывести в консоль номер порта по которому отвечает сервер. Если вы откроете http://localhost:8080/ в браузере, то увидите на странице следующий текст:
Nodemon
Чтобы избежать перезагрузки сервера вручную каждый раз при изменении файла app.js мы можем установить nodemon. Nodemon — это утилита, которая будет отслеживать изменения в вашем коде и автоматически перезапустить сервер.
Теперь вы можете запустить сервер с помощью команды nodemon вместо node:
Даже с хакерской клавиатурой писать код на сенсорном экране не очень удобно. Скорее всего, вы пишите свой код в гораздо более удобных местах и храните его в репозитории. Установим git:
Теперь вы можете запускать git команды вроде git push, git pull и т.д. без каких-либо ошибок.
MongoDB
К сожалению, у меня не получилось запустить MongoDB-сервер на Android. В качестве альтернативы можно использовать облачные сервисы, типа MongoLab или довольствоваться чем-то вроде NeDB.
Источник
Getting Started: Android native apps¶
Download the library¶
The Android shared libraries are distributed in a zip file, which you can download from the core library release page.
The zip file contains Android binaries for the armabi-v7a , x86 , arm64-v8a and x86_64 architectures.
Creating your First Project¶
The following steps will guide you through creating an Android Studio project that uses the library and is built with Gradle. The complete project can also be downloaded from the samples repo.
This sample runs the Node.js engine in a background thread to start an HTTP server on port 3000 and return the process.versions value. The app’s Main Activity UI has a button to query the server and show the server’s response. Alternatively, it’s also possible to access the server from a browser running on a different device connected to the same local network.
Android SDK Requirements¶
When you build your project, Gradle will automatically try to detect any missing dependencies and prompt you to install them from within the Android Studio event log. Here’s the list of pre-requisites in case you want to download them from the SDK Manager:
- API Level greater or equal to Marshmallow (API Level 23)
- CMake
- Android SDK Platform-Tools greater or equal to Marshmallow (API Level 23)
- Android SDK Build-Tools greater or equal to Marshmallow (API Level 23)
- NDK version 15 or greater
Create an Android Studio Project¶
Using the Android Studio’s New Project wizard, create a new Project with the following settings, by the order the options appear in screens:
- Include C++ support checked
- Phone and Tablet with Minimum SDK to API 21: Android 5.0 (Lollipop)
- Empty activity selected
- Left the defaults, which were:
- Activity Name: MainActivity
- Generate Layout File checked
- Layout Name: activity_main
- Backwards Compatibility (AppCompat) checked
- Left the defaults, which were:
- C++ Standard: Toolchain Default
- Exceptions Support (-fexceptions) checked off
- Runtime TYpe Information Support (-frtti) checked off
- Finish
Copy libnode’s header files¶
To access libnode’s Start() entrypoint, the libnode’s header files are required.
Create the libnode/ folder inside the project’s app/ folder.
In the downloaded zip file, you can find the header files inside the include/ path. Copy this folder to app/libnode/include . If it’s been done correctly you’ll end with the following path for the node.h header file: app/libnode/include/node/node.h
In app/CMakeLists.txt add the following line to add libnode’s header files to the CMake include paths:
Add native JNI function to start node.js¶
Edit app/src/main/cpp/native-lib.cpp to add the required include files:
Convert the existing stringFromJNI function into the startNodeWithArguments function, which takes a Java String array, converts it into a libuv friendly format and calls node::Start . The function’s signature has to be adapted to the chosen organization/application name. Use the already existing stringFromJNI function as a guide. In this sample’s case, it meant changing from:
The final native-lib.cpp looks like this:
Call startNodeWithArguments from Java¶
A few changes are required in the application’s main file MainActivity.java .
Load libnode.so:¶
Instruct Java to load the libnode.so library by adding System.loadLibrary(«node»); to MainActivity.java after System.loadLibrary(«native-lib»); .
The prefix lib and the suffix .so in libnode.so are omitted.
Remove references to stringFromJNI ¶
Remove the references to the stringFromJNI function (which we have replaced in native-lib.cpp ), by deleting the following snippets:
Start a background thread to run startNodeWithArguments ¶
The app uses a background thread to run the Node.js engine.
Currently, only a single instance of the Node.js runtime can be started within an application. Restarting the engine after it has finished running is also not supported.
The node code is a simple HTTP server on port 3000 that returns process.versions . For semplicity, the node code is embedded in the MainActivity.java file:
Add a reference to the startNodeWithArguments function, the Java signature is public native Integer startNodeWithArguments(String[] arguments); .
The MainActivity class looks like this at this point:
Specify required permissions in the manifest¶
Since the app runs an HTTP server, it requires the right permissions in app/src/main/AndroidManifest.xml . Add the following line under the tag:
Add libnode.so to the project¶
Copy the library files¶
In the Android Studio Project, there should be a libnode/ folder inside the project’s app/ folder, created in a previous instruction. Copy the bin/ folder from inside the downloaded zip file to app/libnode/bin . If it’s been done correctly you’ll end with the following paths for the binaries:
- app/libnode/bin/arm64-v8a/libnode.so
- app/libnode/bin/armeabi-v7a/libnode.so
- app/libnode/bin/x86/libnode.so
- app/libnode/bin/x86_64/libnode.so
Configure CMake¶
In app/CMakeLists.txt specify the native shared library to import and its location:
Add libnode to the already existing target_link_libraries :
Configure the app’s gradle settings¶
In app/build.gradle , some changes have to be made to correctly build and package the application.
We have to instruct gradle to only package native code for the supported architectures, by adding an ndk clause inside defaultConfig :
The shared library was built using the libC++ STL, therefore the ANDROID_STL=c++_shared definition has to be passed inside the cmake clause in defaultConfig with arguments «-DANDROID_STL=c++_shared» :
Configure gradle to override its default sourceSets to include the libnode.so folder path, in the android section:
Add simple UI for testing¶
At this point, it’s already possible to run the app on an Android device and access the HTTP server from any device connected to the same local network. If the Android device’s IP is 192.168.1.100 point the browser at http://192.168.1.100:3000/ .
However, the sample also comes with the UI to query the local HTTP server and show the response.
Источник
Node.js for Mobile Apps core library v0.3.3
This release contains the build of the armeabi-v7a , x86 , arm64-v8a and x86_64 shared libraries for Android, the 64 bits universal and device-only NodeMobile.framework binaries and the NodeMobile.xcframework binary for iOS.
The packages also include the node header files from this repo.
View the changelog file in the repo for more detailed notes.
Assets
Node.js for Mobile Apps core library v0.3.2
This release contains the build of the armeabi-v7a , x86 , arm64-v8a and x86_64 shared libraries for Android, the 64 bits universal and device-only libnode.framework binaries for iOS.
The packages also include the node header files from this repo.
View the changelog file in the repo for more detailed notes.
Assets
Node.js for Mobile Apps core library v0.3.1
This release contains the build of the armeabi-v7a , x86 , arm64-v8a and x86_64 shared libraries for Android, the 64 bits universal and device-only libnode.framework binaries for iOS.
The packages also include the node header files from this repo.
View the changelog file in the repo for more detailed notes.
Assets
Node.js for Mobile Apps core library v0.3.0
This release contains the build of the armeabi-v7a , x86 , arm64-v8a and x86_64 shared libraries for Android, the 64 bits universal and device-only libnode.framework binaries for iOS.
The packages also include the node header files from this repo.
View the changelog file in the repo for more detailed notes.
Assets
Node.js for Mobile Apps core library v0.2.2
This release contains the build of the armeabi-v7a , x86 , arm64-v8a and x86_64 shared libraries for Android, the 64 bits universal and device-only libnode.framework binaries for iOS.
The android package also includes the node-v8 header files and the iOS package includes the node-chakracore header files from this repo.
View the changelog file in the repo for more detailed notes.
Источник
How To Build Android Apps With Node JS Using Android JS
Apr 18, 2019 · 4 min read
Built android apps with JavaScript, HTML and CSS based on Node JS
In this tutorial we’ll learn about how to build a simple story Android App with Node JS using Android JS
Discussion
What is Android JS?
Android JS is an open-source framework developed and maintained on GitHub. Android JS allows for the development of Android applications using front and back-end components originally developed for web applications: Node.js runtime for the backend and Android Webview for the frontend. Android JS framework can be used to android apps with frontend technologies like JavaScript, HTML, and CSS.
Assumptions & Requirements
I am assuming th a t you already have Node JS, npm and JDK ≥ 1.8 installed on your computer
So let’s start with Installation Part
Install Android JS project generator and builder
Now let’s start building app
create a folder whatever name you want with, and where you want. In my case I am creating it on my desktop with name myapp
you’ll get directory structure something like this
let’s create some useful directories and files in our app
- we need a file named main.js in our app’s parent directory
- and need one more file index.html inside views directory, it is the first view of our app which is gonna render by webview
- and one more for storing assets of our app
Now you’ll get directory structure something like this
let’s install androidjs to our app
get back to app’s directory
it’ll install androidjs and add it to the package.json as dependency of our app
download androidjs.js file and put it to assets folder and add it to the index.html
I am using simple HTML code to make the UI of our app like this :
I already have HTML code for doing this
copy this code to your index.html file and define some functions to change the author, title and text written over it
add these functions to the index.html file for retrieving the saved data when app opens and save the new data if user save it.
so we make a function called save which triggers when user click on save and get the author, title and text and send it to back process to save the data and path where to save that data into the storage of android device .
and when app opens, it request for data over signal get-data and when it get’s the data over signal get-data-result from back process, it fill’s the data into the HTML view.
So let’s define functions to handle the data in main.js (back process):
copy these functions to your main.js file to handle the data coming from front process (index.html)
Since Android JS provides Node JS runtime environment, that’s why we are writing our back end codes in Node JS .
So we require androidjs to get the facilities provided by androidjs , fs module to save data into the storage and path module to create the path.
we defined a signal save-data which get’s the data and path from the front process and save it to the storage of android device with name data.txt
and get-data signal read the same file from the storage and send the data to the front process.
So let’s start packaging process
before starting packaging just configure your app
- app name
- package name
- icon
- android permissions
- output directory
your package json look like this after all the configurations
here we defined 3 permissions
- android.permission.INTERNET for internet access
- android.permission.WRITE_EXTERNAL_STORAGE for write permission
- android.permission.READ_EXTERNAL_STORAGE for read permission
So we done with configuration part
let’s start packaging app
In order to package your app you just need to open console into our app’s directory
NOTE: Make sure you already installed androidjs-builder and JDK ≥ 1.8
then after a while you’ll find a signed apk inside the dist folder
Link of source code which we use in this tutorial
Источник