- PermissionsAndroid
- Project with Native Code Required
- Example
- Permissions that require prompting the user
- Result strings for requesting permissions
- Reference
- Methods
- constructor()
- check()
- request()
- requestMultiple()
- Integrating React Native with existing Android app
- Configuring Maven
- Adding permissions
- Code Integration
- Opening React App
- Run and Test
- Руководство по React Native для начинающих Android-разработчиков (с примером приложения)
- Что такое React Native
- Плюсы: в чем вы выиграете
- 1. Кроссплатформенная разработка
- 2. Освоение React
- 3. Время сборки быстрее, чем в Android Studio
- 4. JavaScript удобен для передачи данных по сети
- 5. Разработка UI
- Минусы: в чем вы, быть может, проиграете
- 1. Возможно, вы ненавидите JavaScript
- 2. Не так уж много сторонних библиотек
- Пример приложения
PermissionsAndroid
Project with Native Code Required
The following section only applies to projects with native code exposed. If you are using the managed expo-cli workflow, see the guide on Permissions in the Expo documentation for the appropriate alternative.
PermissionsAndroid provides access to Android M’s new permissions model. The so-called «normal» permissions are granted by default when the application is installed as long as they appear in AndroidManifest.xml . However, «dangerous» permissions require a dialog prompt. You should use this module for those permissions.
On devices before SDK version 23, the permissions are automatically granted if they appear in the manifest, so check should always result to true and request should always resolve to PermissionsAndroid.RESULTS.GRANTED .
If a user has previously turned off a permission that you prompt for, the OS will advise your app to show a rationale for needing the permission. The optional rationale argument will show a dialog prompt only if necessary — otherwise the normal permission prompt will appear.
Example
- Function Component
- Class Component
Permissions that require prompting the user
Available as constants under PermissionsAndroid.PERMISSIONS :
- READ_CALENDAR : ‘android.permission.READ_CALENDAR’
- WRITE_CALENDAR : ‘android.permission.WRITE_CALENDAR’
- CAMERA : ‘android.permission.CAMERA’
- READ_CONTACTS : ‘android.permission.READ_CONTACTS’
- WRITE_CONTACTS : ‘android.permission.WRITE_CONTACTS’
- GET_ACCOUNTS : ‘android.permission.GET_ACCOUNTS’
- ACCESS_FINE_LOCATION : ‘android.permission.ACCESS_FINE_LOCATION’
- ACCESS_COARSE_LOCATION : ‘android.permission.ACCESS_COARSE_LOCATION’
- ACCESS_BACKGROUND_LOCATION : ‘android.permission.ACCESS_BACKGROUND_LOCATION’
- RECORD_AUDIO : ‘android.permission.RECORD_AUDIO’
- READ_PHONE_STATE : ‘android.permission.READ_PHONE_STATE’
- CALL_PHONE : ‘android.permission.CALL_PHONE’
- READ_CALL_LOG : ‘android.permission.READ_CALL_LOG’
- WRITE_CALL_LOG : ‘android.permission.WRITE_CALL_LOG’
- ADD_VOICEMAIL : ‘com.android.voicemail.permission.ADD_VOICEMAIL’
- USE_SIP : ‘android.permission.USE_SIP’
- PROCESS_OUTGOING_CALLS : ‘android.permission.PROCESS_OUTGOING_CALLS’
- BODY_SENSORS : ‘android.permission.BODY_SENSORS’
- SEND_SMS : ‘android.permission.SEND_SMS’
- RECEIVE_SMS : ‘android.permission.RECEIVE_SMS’
- READ_SMS : ‘android.permission.READ_SMS’
- RECEIVE_WAP_PUSH : ‘android.permission.RECEIVE_WAP_PUSH’
- RECEIVE_MMS : ‘android.permission.RECEIVE_MMS’
- READ_EXTERNAL_STORAGE : ‘android.permission.READ_EXTERNAL_STORAGE’
- WRITE_EXTERNAL_STORAGE : ‘android.permission.WRITE_EXTERNAL_STORAGE’
- BLUETOOTH_CONNECT : ‘android.permission.BLUETOOTH_CONNECT’
- BLUETOOTH_SCAN : ‘android.permission.BLUETOOTH_SCAN’
- BLUETOOTH_ADVERTISE : ‘android.permission.BLUETOOTH_ADVERTISE’
Result strings for requesting permissions
Available as constants under PermissionsAndroid.RESULTS :
- GRANTED : ‘granted’
- DENIED : ‘denied’
- NEVER_ASK_AGAIN : ‘never_ask_again’
Reference
Methods
constructor()
check()
Returns a promise resolving to a boolean value as to whether the specified permissions has been granted.
Parameters:
Name | Type | Required | Description |
---|---|---|---|
permission | string | Yes | The permission to check for. |
request()
Prompts the user to enable a permission and returns a promise resolving to a string value (see result strings above) indicating whether the user allowed or denied the request or does not want to be asked again.
If rationale is provided, this function checks with the OS whether it is necessary to show a dialog explaining why the permission is needed (https://developer.android.com/training/permissions/requesting.html#explain) and then shows the system permission dialog.
Parameters:
Name | Type | Required | Description |
---|---|---|---|
permission | string | Yes | The permission to request. |
rationale | object | No | See rationale below. |
Rationale:
Name | Type | Required | Description |
---|---|---|---|
title | string | Yes | The title of the dialog. |
message | string | Yes | The message of the dialog. |
buttonPositive | string | Yes | The text of the positive button. |
buttonNegative | string | No | The text of the negative button. |
buttonNeutral | string | No | The text of the neutral button. |
requestMultiple()
Prompts the user to enable multiple permissions in the same dialog and returns an object with the permissions as keys and strings as values (see result strings above) indicating whether the user allowed or denied the request or does not want to be asked again.
Источник
Integrating React Native with existing Android app
Note : This article has been written after testing under the following environment.
1) React version : 16.0.0-alpha.12
2) React Native version : ^0.46.1
The guide might change with the version change. So if this guide doesn’t work for your environment please mention the errors in the comments below or send me a mail on rajsuvariya@gmail.com
- React Native setup in your system. If you don’t have then please follow this guide.
Note : Please do not proceed if you are not able to create and run a project without any errors with the above guide. - Android Studio setup with the latest version of JDK.
- An existing Android project ( for this article we will be using AwesomeApp ).
Step 1 : Re-structuring the existing project
This step is not the mandatory step for integrating react native into the existing project. But this step is important as it separates the Android Native and React Native code from each other.
Create a folder /android inside the root directory of the existing project ( in AwesomeApp folder).
After this step, your structure looks like this.
Now move everything to the android folder using cut and paste. So the existing project files will live at the path /AwesomeApp/android/
Now, you can open /AwesomeApp/android in Android Studio to write the Android Native code.
Step 2 : Install JavaScript dependencies
Now, move back to root directory /AwesomeApp and create a file named package.json and paste the following code inside it.
It’s time to install the react and react-native packages in our project. So, open a terminal inside the root directory /AwesomeApp and run the following command.
This will create a new /node_modules folder inside the root directory. This folder contains all the javascript packages required to run the app.
Step 3 : Integrating React Native in the project
Open the AwesomeApp/android folder in Android Studio.
Configuring Maven
Add the following dependency to the /app/build.gradle of the existing project.
If you want to work with the specific version of the react native then replace the + with the exact version.
Add an entry for the local React Native maven directory to build.gradle . Be sure to add it to the «allprojects» block and add it to android/build.gradle, not to android/app/build.gradle
So, the android/build.gradle looks like this now.
Now, sync the project in Android Studio. If you get any error please resolve it before proceeding to next step.
Adding permissions
Open AndroidManifest.xml in Android Studio which can be located at path android/app/src/main/AndroidManifest.xml. Add the following permission to it.
After adding the permission, AndroidManifest.xml looks like this
If you want to access DevSettingsActivity (used to access developer settings from mobile app) then add it to AndroidManifest.xml
This is only really used in dev mode when reloading JavaScript from the development server, so you can strip this in release builds if you need to.
Code Integration
Now, we will add the React Native code and create an activity in native Android which will render the React Native code.
Create index.android.js file inside the root directory /AwesomeApp. This is the entry point of the React Native app. You can read about it more on React Native official documentation. We will be adding a very simple code in React Native which will just say “Hey! How are you?” to the user.
Add the following code inside index.android.js
Make sure you write the same project name in AppRegistry.registerComponent() as written in package.json.
If you are targeting Android API level ≥ 23 then you need to take a permission from user for opening the React Native app from your native Android app, as after API level 23 new dynamic permission for opening other apps has been introduced.
For requesting the permission add the following code either inside the onCreate() of the first activity of the app or inside the onCreate() of the activity which will open the React Native activity.
After adding this permission request, the onCreate() looks like this.
Finally, the onActivityResult() method (as shown in the code below) has to be overridden to handle the permission Acceptance or Denial from the user.
Now, we will write the MyReactActivity which will render the React Native App. So, create a new Activity MyReactActivity using Android Studio and add the following code inside it.
You will get a lot of errors after pasting this code inside MyReactActivity, as the packages used inside the activity are not imported. To import all the packages hover over them one by one and press Alt + Enter . Make sure you import BuidConfig from your package and not from . facebook. package.
Also, change the theme of this activity as some of the components use this special theme. So, inside the AndroidManifest.xml update/add the following code.
Opening React App
We need to open the MyReactNative activity to launch the React Native app. To do so write the following code wherever you want (according to the business logic of your app)
Run and Test
We are ready to run the app and test it out. To start the React Native server run the following command inside the root directory /AwesomeApp.
Now, run the app from Android Studio as usual and test it out. You must see this screen.
Источник
Руководство по React Native для начинающих Android-разработчиков (с примером приложения)
Представляем вам перевод статьи Nikhil Sachdeva, опубликованной на hackernoon.com. Автор делится опытом разработки мобильных приложений с помощью React Native и предлагает создать свое приложение, используя этот фреймворк.
Я был Android-разработчиком и довольно длительное время использовал в работе Java. Лишь недавно я попробовал свои силы в создании мобильных приложений с помощью React Native. Это заставило меня взглянуть на процесс разработки по-новому, если не сказать больше. Цель моей статьи — показать, какие различия я заметил, используя эти два фреймворка в разработке приложений.
Что такое React Native
«React Native позволяет создавать мобильные приложения, используя при этом только JavaScript с такой же структурой, что и у React. Это дает возможность составлять многофункциональный мобильный UI с применением декларативных компонентов».
«Приложения, которые вы создаете с помощью React Native, не являются мобильными веб-приложениями, потому что React Native использует те же компоненты, что и обычные приложения для iOS и Android. Вместо того чтобы использовать язык Swift, Kotlin или Java, вы собираете эти компоненты с помощью JavaScript и React».
Итак, получается, что React Native — это фреймворк, в основе которого лежит React.js, что позволяет разрабатывать кроссплатформенные приложения как для Android, так и для iOS.
Вы спросите, зачем уходить от привычного Java и осваивать JavaScript и React.js? Вот несколько плюсов использования этих языков.
Плюсы: в чем вы выиграете
1. Кроссплатформенная разработка
Основная цель разработчиков — предоставить клиентам сервисы. Никто не хотел бы, чтобы его пользователи были ограничены лишь одной какой-то платформой только потому, что разработчик не может создавать приложения для других платформ. Следовательно, и сам разработчик не должен ограничивать свои способности только потому, что ему или ей комфортно работать с конкретным инструментом разработки.
Фреймворк React Native является портативным, то есть его единая кодовая база, написанная в JavaScript, создаст модули как для Android, так и для iOS.
2. Освоение React
Освоив React Native и JavaScript, вы откроете для себя новый мир front-end разработки применительно, например, к веб-сайтам. Фреймворк React Native основан на тех же компонентах, что и React, поэтому полученные здесь навыки не ограничиваются только разработкой мобильных приложений.
3. Время сборки быстрее, чем в Android Studio
Вы когда-нибудь тратили больше 2–3 минут на сборку, чтобы протестировать/пофиксить базовую функцию, и при этом багфикс растягивался на долгие часы? Решением проблемы станет React Native. С ним на сборку уходит значительно меньше времени. С такой функцией, как «Горячая перезагрузка» (Hot Reloading), разработка и тестирование пользовательского интерфейса — это легко. Благодаря этой функции приложение перезагружается каждый раз, когда JS-файл сохраняется!
4. JavaScript удобен для передачи данных по сети
В React Native вызов API, рендеринг изображений по URL и другие процессы очень просты. Больше не нужно использовать Retrofit, OkHttp, Picasso и т. д. Намного меньше времени тратится на настройку. Когда данные поступают из API на платформе Android, они сначала преобразуются в POJO-модель и лишь затем используются в элементах UI. А вот данные JSON, полученные в React Native, удобны для JavaScript и могут напрямую использоваться для предпросмотра UI. Это позволяет облегчить веб-интерфейс для GET или POST-запросов от REST API.
5. Разработка UI
В React Native в качестве разметки UI выступает модуль flexbox, серьезный конкурент XML-разметки на Android. Flexbox очень популярен в сообществе веб-разработчиков. В React Native UI-элементы в основном должны разрабатываться с нуля, тогда как в нативной разработке для Android библиотека поддержки Google Design Support Library уже подключена. Это дает разработчику свободу в плане интерактивного и адаптивного дизайна.
Минусы: в чем вы, быть может, проиграете
1. Возможно, вы ненавидите JavaScript
Многие люди не любят JavaScript просто за то, что этот язык не похож на традиционные языки, такие как Java, C++ и другие. Подробные негативные отзывы вы можете найти здесь и здесь.
2. Не так уж много сторонних библиотек
Сообщество React Native по-прежнему находится в стадии становления и поддерживает сторонние библиотеки, не такие популярные, как нативная библиотека Android (кстати, оцените слайд-шоу моей библиотеки для Android ).
Пример приложения
Для начала давайте попробуем разработать приложение для извлечения данных из API, чтобы понять, насколько просто работает React Native. Очевидно, что первым шагом является установка React Native. Для этого перейдите на официальный сайт. Также вы найдете там замечательную инструкцию для начинающих — прочтите ее. Мы будем использовать фиктивный API https://jsonplaceholder.typicode.com/photos, который содержит следующие данные:
Обратите внимание, что для Android работа с API с использованием таких библиотек, как Retrofit/OkHttp, — это сложная задача. Однако мы видим, что динамический и итеративный язык JavaScript упрощает эту работу.
Перейдем к созданию проекта MockApp:
react-native init MockApp
cd MockApp
Далее запустите его на вашем виртуальном/локальном устройстве, используя:
На экране появится такое изображение:
Стартовый экран приложения
Приложение для работы с API, которое мы создадим, будет выглядеть вот так:
Так в результате выглядит приложение
Теперь откройте проект в текстовом редакторе и скорректируйте App.js, как показано ниже:
В этом коде довольно много информации. Я дам краткий обзор по всем основным ключевым словам в коде, но продолжайте поиск по каждому ключевому слову, которое вам непонятно. Это займет некоторое время.
1. componentDidMount. Это часть React Native в жизненном цикле приложения. componentDidMount() запускается сразу после того, как компонент был добавлен в дерево компонентов.
2. fetch. Чтобы работать с сетевыми запросами, в React Native существует API-интерфейс Fetch.
3. Переменные состояния (isLoading, dataSource). isLoading — это переменная типа bool, которая показывает, загружены данные API или нет. dataSource — переменная, которая сохраняет ответ JSON от команды fetch.
4. FlatList. Это эквивалент RecyclerView в React Native, только намного проще. Компонент FlatList отображает скролящийся лист данных, которые могут изменятся, хотя и имеют общую структуру. FlatList отлично подходит для работы с длинными списками, в которых количество элементов может меняться с течением времени.
Как мы видим, в списке данных нам не нужно отделять переменные для каждого элемента. В этом и заключается красота динамического языка, то есть языка JavaScript. Тип переменной определяется в реальном времени, поэтому работа даже с большими объемами данных остается простой задачей.
Как мы видим, стили каждого компонента уже определены. Нам нужно задать значения переменных. Это можно сделать следующим способом:
На этом наша работа заканчивается. Нам удалось создать приложение, компоненты которого могут предварительно просматриваться благодаря использованию API.
Источник