Created
June 19, 2018 14:18
-
-
Save dengue8830/8dfb01842882db040c32369893034897 to your computer and use it in GitHub Desktop.
react-native-mauron85-background-geolocation+react-native-firebase+react-native-maps
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<manifest xmlns:android="http://schemas.android.com/apk/res/android" | |
package="com.xxx"> | |
<uses-permission android:name="android.permission.INTERNET" /> | |
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/> | |
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> | |
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> | |
<!-- RNFirebase notifications --> | |
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> | |
<uses-permission android:name="android.permission.VIBRATE" /> | |
<application | |
android:name=".MainApplication" | |
android:label="@string/app_name" | |
android:icon="@mipmap/ic_launcher" | |
android:allowBackup="false" | |
android:theme="@style/AppTheme"> | |
<!-- Mensages firebase --> | |
<service android:name="io.invertase.firebase.messaging.RNFirebaseMessagingService"> | |
<intent-filter> | |
<action android:name="com.google.firebase.MESSAGING_EVENT" /> | |
</intent-filter> | |
</service> | |
<service android:name="io.invertase.firebase.messaging.RNFirebaseInstanceIdService"> | |
<intent-filter> | |
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/> | |
</intent-filter> | |
</service> | |
<!-- Para recibir mensajes en background --> | |
<service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" /> | |
<!-- | |
The API key for Google Maps-based APIs is defined as a string resource. | |
(See the file "res/values/google_maps_api.xml"). | |
Note that the API key is linked to the encryption key used to sign the APK. | |
You need a different API key for each encryption key, including the release key that is used to | |
sign the APK for publishing. | |
You can define the keys for the debug and release targets in src/debug/ and src/release/. | |
--> | |
<meta-data | |
android:name="com.google.android.geo.API_KEY" | |
android:value="@string/google_maps_key" /> | |
<!-- RNFirebase config para icono y color de notificacion --> | |
<!-- Set custom default icon. This is used when no icon is set for incoming notification messages. | |
See README(https://goo.gl/l4GJaQ) for more. --> | |
<!-- <meta-data | |
android:name="com.google.firebase.messaging.default_notification_icon" | |
android:resource="@mipmap/ic_launcher" /> --> | |
<!-- Set color used with incoming notification messages. This is used when no color is set for the incoming | |
notification message. See README(https://goo.gl/6BKBk7) for more. --> | |
<!-- <meta-data | |
android:name="com.google.firebase.messaging.default_notification_color" | |
android:resource="@color/colorAccent" /> --> | |
<!-- RNfirebase notification adds: android:launchMode="singleTop" --> | |
<activity | |
android:name=".MainActivity" | |
android:label="@string/app_name" | |
android:configChanges="keyboard|keyboardHidden|orientation|screenSize" | |
android:windowSoftInputMode="adjustResize" | |
android:launchMode="singleTop"> | |
<intent-filter> | |
<action android:name="android.intent.action.MAIN" /> | |
<category android:name="android.intent.category.LAUNCHER" /> | |
</intent-filter> | |
</activity> | |
<activity android:name="com.facebook.react.devsupport.DevSettingsActivity" /> | |
</application> | |
</manifest> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
apply plugin: "com.android.application" | |
import com.android.build.OutputFile | |
/** | |
* The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets | |
* and bundleReleaseJsAndAssets). | |
* These basically call `react-native bundle` with the correct arguments during the Android build | |
* cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the | |
* bundle directly from the development server. Below you can see all the possible configurations | |
* and their defaults. If you decide to add a configuration block, make sure to add it before the | |
* `apply from: "../../node_modules/react-native/react.gradle"` line. | |
* | |
* project.ext.react = [ | |
* // the name of the generated asset file containing your JS bundle | |
* bundleAssetName: "index.android.bundle", | |
* | |
* // the entry file for bundle generation | |
* entryFile: "index.android.js", | |
* | |
* // whether to bundle JS and assets in debug mode | |
* bundleInDebug: false, | |
* | |
* // whether to bundle JS and assets in release mode | |
* bundleInRelease: true, | |
* | |
* // whether to bundle JS and assets in another build variant (if configured). | |
* // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants | |
* // The configuration property can be in the following formats | |
* // 'bundleIn${productFlavor}${buildType}' | |
* // 'bundleIn${buildType}' | |
* // bundleInFreeDebug: true, | |
* // bundleInPaidRelease: true, | |
* // bundleInBeta: true, | |
* | |
* // whether to disable dev mode in custom build variants (by default only disabled in release) | |
* // for example: to disable dev mode in the staging build type (if configured) | |
* devDisabledInStaging: true, | |
* // The configuration property can be in the following formats | |
* // 'devDisabledIn${productFlavor}${buildType}' | |
* // 'devDisabledIn${buildType}' | |
* | |
* // the root of your project, i.e. where "package.json" lives | |
* root: "../../", | |
* | |
* // where to put the JS bundle asset in debug mode | |
* jsBundleDirDebug: "$buildDir/intermediates/assets/debug", | |
* | |
* // where to put the JS bundle asset in release mode | |
* jsBundleDirRelease: "$buildDir/intermediates/assets/release", | |
* | |
* // where to put drawable resources / React Native assets, e.g. the ones you use via | |
* // require('./image.png')), in debug mode | |
* resourcesDirDebug: "$buildDir/intermediates/res/merged/debug", | |
* | |
* // where to put drawable resources / React Native assets, e.g. the ones you use via | |
* // require('./image.png')), in release mode | |
* resourcesDirRelease: "$buildDir/intermediates/res/merged/release", | |
* | |
* // by default the gradle tasks are skipped if none of the JS files or assets change; this means | |
* // that we don't look at files in android/ or ios/ to determine whether the tasks are up to | |
* // date; if you have any other folders that you want to ignore for performance reasons (gradle | |
* // indexes the entire tree), add them here. Alternatively, if you have JS files in android/ | |
* // for example, you might want to remove it from here. | |
* inputExcludes: ["android/**", "ios/**"], | |
* | |
* // override which node gets called and with what additional arguments | |
* nodeExecutableAndArgs: ["node"], | |
* | |
* // supply additional arguments to the packager | |
* extraPackagerArgs: [] | |
* ] | |
*/ | |
project.ext.react = [ | |
entryFile: "index.js" | |
] | |
apply from: "../../node_modules/react-native/react.gradle" | |
/** | |
* Set this to true to create two separate APKs instead of one: | |
* - An APK that only works on ARM devices | |
* - An APK that only works on x86 devices | |
* The advantage is the size of the APK is reduced by about 4MB. | |
* Upload all the APKs to the Play Store and people will download | |
* the correct one based on the CPU architecture of their device. | |
*/ | |
def enableSeparateBuildPerCPUArchitecture = false | |
/** | |
* Run Proguard to shrink the Java bytecode in release builds. | |
*/ | |
def enableProguardInReleaseBuilds = false | |
android { | |
compileSdkVersion 26 | |
buildToolsVersion "27.0.3" | |
defaultConfig { | |
applicationId "com.xxx" | |
minSdkVersion 16 | |
targetSdkVersion 26 | |
versionCode 1 | |
versionName "1.0" | |
ndk { | |
abiFilters "armeabi-v7a", "x86" | |
} | |
} | |
splits { | |
abi { | |
reset() | |
enable enableSeparateBuildPerCPUArchitecture | |
universalApk false // If true, also generate a universal APK | |
include "armeabi-v7a", "x86" | |
} | |
} | |
signingConfigs { | |
release { | |
storeFile file("xxx.jks") | |
storePassword "xxx" | |
keyAlias "xxx" | |
keyPassword "xxx" | |
// Para usar esta forma, hay que crear un keystore y pegarlo en android/app, esta forma se explica bien en la doc de react native para generar release | |
// storeFile file(MYAPP_RELEASE_STORE_FILE) | |
// storePassword MYAPP_RELEASE_STORE_PASSWORD | |
// keyAlias MYAPP_RELEASE_KEY_ALIAS | |
// keyPassword MYAPP_RELEASE_KEY_PASSWORD | |
} | |
} | |
buildTypes { | |
release { | |
minifyEnabled enableProguardInReleaseBuilds | |
proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" | |
signingConfig signingConfigs.release | |
} | |
} | |
// applicationVariants are e.g. debug, release | |
applicationVariants.all { variant -> | |
variant.outputs.each { output -> | |
// For each separate APK per architecture, set a unique version code as described here: | |
// http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits | |
def versionCodes = ["armeabi-v7a":1, "x86":2] | |
def abi = output.getFilter(OutputFile.ABI) | |
if (abi != null) { // null for the universal-debug, universal-release variants | |
output.versionCodeOverride = | |
versionCodes.get(abi) * 1048576 + defaultConfig.versionCode | |
} | |
} | |
} | |
} | |
dependencies { | |
implementation project(':react-native-mauron85-background-geolocation') | |
implementation(project(':react-native-firebase')) { | |
transitive = false | |
} | |
// Excluimos la dependencia para importarla por separado para coexistencia con otros que dependen de playservices | |
// como sugieren aca https://github.com/react-community/react-native-maps/blob/master/docs/installation.md#android | |
implementation(project(':react-native-maps')){ | |
exclude group: 'com.google.android.gms', module: 'play-services-base' | |
exclude group: 'com.google.android.gms', module: 'play-services-maps' | |
} | |
// Importamos play services por separado para que pueda coexistir esta dependencia con | |
// una unica version para firebase y para maps | |
implementation 'com.google.android.gms:play-services-base:15.0.0' | |
implementation 'com.google.android.gms:play-services-maps:15.0.1' | |
// Firebase | |
implementation "com.google.firebase:firebase-core:15.0.2" | |
implementation "com.google.firebase:firebase-messaging:15.0.2" | |
// Add this line if you wish to use badge on Android | |
// implementation "me.leolin:ShortcutBadger:1.1.21@aar" | |
implementation project(':react-native-linear-gradient') | |
implementation fileTree(dir: "libs", include: ["*.jar"]) | |
implementation "com.android.support:appcompat-v7:23.0.1" | |
implementation "com.facebook.react:react-native:+" // From node_modules | |
} | |
// Run this once to be able to run the application with BUCK | |
// puts all compile dependencies into folder libs for BUCK to use | |
task copyDownloadableDepsToLibs(type: Copy) { | |
from configurations.compile | |
into 'libs' | |
} | |
apply plugin: 'com.google.gms.google-services' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
distributionBase=GRADLE_USER_HOME | |
distributionPath=wrapper/dists | |
zipStoreBase=GRADLE_USER_HOME | |
zipStorePath=wrapper/dists | |
distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Project-wide Gradle settings. | |
# IDE (e.g. Android Studio) users: | |
# Gradle settings configured through the IDE *will override* | |
# any settings specified in this file. | |
# For more details on how to configure your build environment visit | |
# http://www.gradle.org/docs/current/userguide/build_environment.html | |
# Specifies the JVM arguments used for the daemon process. | |
# The setting is particularly useful for tweaking memory settings. | |
# Default value: -Xmx10248m -XX:MaxPermSize=256m | |
# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 | |
# When configured, Gradle will run in incubating parallel mode. | |
# This option should only be used with decoupled projects. More details, visit | |
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects | |
# org.gradle.parallel=true | |
android.useDeprecatedNdk=true | |
# BUG: con la actualizacion de gradle para poder usar firebase (segun rnfirebase) se producia un error al haecr | |
# el assembleRelease sobre un archivo de drawable, | |
# https://github.com/react-navigation/react-navigation/issues/3097 | |
# este tambien puede ayudar: https://github.com/facebook/react-native/issues/5787 | |
# FIX: agregando esto aqui. Hay otras opciones en el primer link pero este es el menos agresivo | |
android.enableAapt2=false |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// NOTE: its a good practice wrap any lib with your | |
// custom implementation layer, its centralizes all changes (even lib changes) in one place. | |
import BackgroundGeolocation from 'react-native-mauron85-background-geolocation'; | |
import { Storage } from '../utils/storage'; | |
import { APIs } from '../utils/APIs'; | |
import { Alert } from 'react-native'; | |
import { PermisosUtil } from '../utils/permisosUtils'; | |
export enum LocationEvent { | |
START = 'start', | |
STOP = 'stop', | |
ERROR = 'error' | |
} | |
export enum LocationError { | |
GPS_DESACTIVADO = 'GPS_DESACTIVADO', | |
PERMISOS_NO_OTORGADOS = 'PERMISOS_NO_OTORGADOS' | |
} | |
type CheckStatus = { | |
isRunning: boolean; | |
locationServicesEnabled: boolean; | |
authorization: AuthorizationStatus; | |
hasPermissions: boolean; | |
}; | |
type AuthorizationStatus = number; | |
/** | |
* Implementado con: https://github.com/mauron85/react-native-background-geolocation | |
* Ver ejemplo en: https://github.com/mauron85/react-native-background-geolocation-example/blob/master/src/scenes/Main.js | |
* FIXED: mismo problema con title notificacion: https://github.com/mauron85/react-native-background-geolocation/issues/154 | |
*/ | |
export class LocationService { | |
static updateInterval = 10000; | |
static async initTracker(usuarioId: string) { | |
// const usuario = await Storage.getUsuario(); | |
BackgroundGeolocation.configure({ | |
desiredAccuracy: BackgroundGeolocation.PASSIVE_ACCURACY, | |
stationaryRadius: 50, | |
distanceFilter: 500, | |
notificationTitle: 'En pedido', | |
notificationText: 'habilitado', | |
debug: false, | |
startOnBoot: false, | |
stopOnTerminate: false, | |
locationProvider: BackgroundGeolocation.DISTANCE_FILTER_PROVIDER, | |
interval: LocationService.updateInterval, | |
fastestInterval: 5000, | |
activitiesInterval: LocationService.updateInterval, | |
stopOnStillActivity: false, | |
// notificationIconSmall: 'ic_launcher', | |
maxLocations: 10000, | |
saveBatteryOnBackground: true, | |
pauseLocationUpdates: false, | |
url: `${APIs.ACTUALIZAR_UBICACION}/${usuarioId}`, | |
// httpHeaders: { | |
// 'X-FOO': 'bar' | |
// }, | |
// customize post properties | |
postTemplate: { | |
latitud: '@latitude', | |
longitud: '@longitude' | |
} | |
}); | |
// BackgroundGeolocation.on('error', (error) => { | |
// console.log('locationservice error:', error); | |
// }); | |
// BackgroundGeolocation.on('start', () => { | |
// console.log('locationservice has been started'); | |
// }); | |
// BackgroundGeolocation.on('stop', () => { | |
// console.log('locationservice has been stopped'); | |
// }); | |
} | |
static async startTracker() { | |
const otorgado = await PermisosUtil.solicitarPermisoDeUbicacion(); | |
if (!otorgado) { | |
throw new Error(LocationError.PERMISOS_NO_OTORGADOS); | |
} | |
const status = await LocationService.getStatus(); | |
if (!status.locationServicesEnabled) { | |
throw new Error(LocationError.GPS_DESACTIVADO); | |
} | |
// you don't need to check status before start | |
BackgroundGeolocation.start(); //triggers start on start event | |
} | |
static stopTracker() { | |
BackgroundGeolocation.stop(); | |
} | |
/** | |
* Devuelve true si se ejecuto start, false en otro caso. | |
*/ | |
static async toggleTracker(): Promise<boolean> { | |
const status = await LocationService.getStatus(); | |
if (status.isRunning) { | |
BackgroundGeolocation.stop(); | |
return false; | |
} else { | |
await LocationService.startTracker(); | |
return true; | |
} | |
} | |
static async getStatus(): Promise<CheckStatus> { | |
return new Promise<CheckStatus>((resolve, reject) => { | |
BackgroundGeolocation.checkStatus((status: CheckStatus) => { | |
// console.log('checkstatus', status); | |
resolve(status); | |
}); | |
}); | |
} | |
static addListener(event: LocationEvent, cb: (error?: any) => void) { | |
BackgroundGeolocation.on(event, cb); | |
} | |
static removeAllListeners() { | |
BackgroundGeolocation.events.forEach(event => | |
BackgroundGeolocation.removeAllListeners(event) | |
); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.xxx; | |
import android.app.Application; | |
import com.facebook.react.ReactApplication; | |
import com.marianhello.bgloc.react.BackgroundGeolocationPackage; | |
import io.invertase.firebase.RNFirebasePackage; | |
import io.invertase.firebase.messaging.RNFirebaseMessagingPackage; | |
import io.invertase.firebase.notifications.RNFirebaseNotificationsPackage; | |
import com.airbnb.android.react.maps.MapsPackage; | |
import com.BV.LinearGradient.LinearGradientPackage; | |
import com.facebook.react.ReactNativeHost; | |
import com.facebook.react.ReactPackage; | |
import com.facebook.react.shell.MainReactPackage; | |
import com.facebook.soloader.SoLoader; | |
import java.util.Arrays; | |
import java.util.List; | |
public class MainApplication extends Application implements ReactApplication { | |
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { | |
@Override | |
public boolean getUseDeveloperSupport() { | |
return BuildConfig.DEBUG; | |
} | |
@Override | |
protected List<ReactPackage> getPackages() { | |
return Arrays.<ReactPackage>asList( | |
new MainReactPackage(), | |
new BackgroundGeolocationPackage(), | |
new RNFirebasePackage(), | |
new RNFirebaseMessagingPackage(), | |
new RNFirebaseNotificationsPackage(), | |
new MapsPackage(), | |
new LinearGradientPackage() | |
); | |
} | |
@Override | |
protected String getJSMainModuleName() { | |
return "index"; | |
} | |
}; | |
@Override | |
public ReactNativeHost getReactNativeHost() { | |
return mReactNativeHost; | |
} | |
@Override | |
public void onCreate() { | |
super.onCreate(); | |
SoLoader.init(this, /* native exopackage */ false); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "xxx", | |
"version": "0.0.1", | |
"private": true, | |
"proxy": "http://localhost:8080", | |
"scripts": { | |
"start": "node node_modules/react-native/local-cli/cli.js start --config ../../../../rn-cli.config.js", | |
"test": "jest", | |
"android": "react-native run-android", | |
"ios": "react-native run-ios", | |
"server": "react-native start" | |
}, | |
"dependencies": { | |
"axios": "0.18.0", | |
"geolib": "2.0.24", | |
"react": "16.3.1", | |
"react-native": "0.55.4", | |
"react-native-firebase": "4.2.0", | |
"react-native-geocoding": "0.3.0", | |
"react-native-gifted-chat": "0.4.3", | |
"react-native-linear-gradient": "2.3.0", | |
"react-native-maps": "0.19.0", | |
"react-native-masked-text": "1.7.1", | |
"react-native-mauron85-background-geolocation": "0.5.0-alpha.34", | |
"react-native-parallax-scroll-view": "0.21.0", | |
"react-native-picker-select": "3.1.1", | |
"react-native-snap-carousel": "3.7.0", | |
"react-native-step-indicator": "0.0.7", | |
"react-native-swipe-list-view": "1.0.3", | |
"react-navigation": "2.0.1", | |
"react-redux": "5.0.7", | |
"redux": "4.0.0", | |
"redux-devtools-extension": "2.13.2", | |
"redux-thunk": "2.3.0", | |
"underscore": "1.9.0", | |
"validator": "10.3.0" | |
}, | |
"devDependencies": { | |
"@types/axios": "0.14.0", | |
"@types/geolib": "2.0.23", | |
"@types/jest": "22.2.3", | |
"@types/node": "9.6.8", | |
"@types/react": "16.3.14", | |
"@types/react-native": "0.55.14", | |
"@types/react-navigation": "1.5.11", | |
"@types/react-redux": "6.0.2", | |
"@types/react-test-renderer": "16.0.1", | |
"@types/redux": "3.6.0", | |
"@types/underscore": "1.8.8", | |
"@types/validator": "9.4.1", | |
"babel-jest": "22.4.4", | |
"babel-preset-react-native": "4.0.0", | |
"jest": "22.4.4", | |
"react-native-typescript-transformer": "1.2.5", | |
"react-test-renderer": "16.3.1", | |
"ts-jest": "22.4.6", | |
"typescript": "2.8.3" | |
}, | |
"jest": { | |
"preset": "react-native", | |
"transform": { | |
"^.+\\.tsx?$": "ts-jest" | |
}, | |
"testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$", | |
"moduleFileExtensions": [ | |
"ts", | |
"tsx", | |
"js", | |
"jsx", | |
"json", | |
"node" | |
], | |
"modulePaths": [ | |
"<rootDir>" | |
] | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { PermissionsAndroid } from 'react-native'; | |
export class PermisosUtil { | |
static async solicitarPermisoDeUbicacion(): Promise<boolean> { | |
try { | |
const result = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION); | |
return result === PermissionsAndroid.RESULTS.GRANTED; | |
} catch (err) { | |
console.warn(err); | |
return false; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Top-level build file where you can add configuration options common to all sub-projects/modules. | |
buildscript { | |
repositories { | |
jcenter() | |
google() | |
} | |
dependencies { | |
classpath 'com.android.tools.build:gradle:3.1.2' | |
// Agregado para firebase, teoricamente no deberia chocar en nada con maps | |
// porque es google-services y no play-services | |
// El que si puede chocar es play-services-maps en app/build.gradle | |
// https://rnfirebase.io/docs/v4.2.x/installation/android#3.-Add-Firebase-modules | |
// https://github.com/react-community/react-native-maps/blob/master/docs/installation.md#android | |
classpath 'com.google.gms:google-services:3.2.1' | |
// NOTE: Do not place your application dependencies here; they belong | |
// in the individual module build.gradle files | |
} | |
} | |
allprojects { | |
repositories { | |
mavenLocal() | |
jcenter() | |
maven { | |
// All of React Native (JS, Obj-C sources, Android binaries) is installed from npm | |
url "$rootDir/../node_modules/react-native/android" | |
} | |
google() | |
} | |
} | |
ext { | |
compileSdkVersion = 26 | |
targetSdkVersion = 26 | |
buildToolsVersion = "27.0.3" | |
supportLibVersion = "27.1.0" | |
// La lib para obtener las posiciones en background pone esa linea pero funciona sin ella | |
// Mejor la dejamos asi por si acaso ya que hay otras libs que tambien usan play services | |
// googlePlayServicesVersion = "11.8.0" | |
gradle3EXPERIMENTAL = "yes" | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
rootProject.name = 'xxx' | |
include ':react-native-mauron85-background-geolocation-common' | |
project(':react-native-mauron85-background-geolocation-common').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-mauron85-background-geolocation/android/common') | |
include ':react-native-mauron85-background-geolocation' | |
project(':react-native-mauron85-background-geolocation').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-mauron85-background-geolocation/android/lib') | |
include ':react-native-firebase' | |
project(':react-native-firebase').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-firebase/android') | |
include ':react-native-maps' | |
project(':react-native-maps').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-maps/lib/android') | |
include ':react-native-linear-gradient' | |
project(':react-native-linear-gradient').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-linear-gradient/android') | |
include ':app' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { PureComponent } from 'react'; | |
import { | |
StyleSheet, | |
View, | |
StatusBar, | |
ScrollView, | |
Platform | |
} from 'react-native'; | |
import AppStyles from '../themes/AppStyles'; | |
import Colors from '../themes/Colors'; | |
import Metrics from '../themes/Metrics'; | |
import Fonts from '../themes/Fonts'; | |
import HeaderBar from './header-bar/HeaderBar'; | |
import SettingItem from './setting-item/SettingItem'; | |
import HeaderProfile from './header-profile/HeaderProfile'; | |
import Config from '../config'; | |
import { Switch } from 'react-native'; | |
import { Linking } from 'react-native'; | |
import { Picker } from 'react-native'; | |
import { Alert } from 'react-native'; | |
import { Storage } from '../utils/storage'; | |
import { NavigationScreenProp } from 'react-navigation'; | |
import { Routes } from '../AppNavigator'; | |
import { LocationService, LocationError, LocationEvent } from '../services/locationService'; | |
interface NavigationState { | |
params: NavigationParam; | |
} | |
interface NavigationParam { | |
} | |
interface Props { | |
navigation: NavigationScreenProp<NavigationState, NavigationParam>; | |
} | |
interface State { | |
isDisponible: boolean; | |
isTracking: boolean; | |
} | |
export default class SettingScreen extends PureComponent<Props, State> { | |
constructor(props: Props) { | |
super(props); | |
this.state = { | |
isDisponible: false, | |
isTracking: false | |
}; | |
this.onToggleDisponible = this.onToggleDisponible.bind(this); | |
this.onLocationTrackerStarted = this.onLocationTrackerStarted.bind(this); | |
this.onLocationTrackerStopped = this.onLocationTrackerStopped.bind(this); | |
this.onLocationTrackerError = this.onLocationTrackerError.bind(this); | |
// Primero debe hacerse el bind | |
LocationService.addListener(LocationEvent.START, this.onLocationTrackerStarted); | |
LocationService.addListener(LocationEvent.STOP, this.onLocationTrackerStopped); | |
LocationService.addListener(LocationEvent.ERROR, this.onLocationTrackerError); | |
} | |
async componentWillMount() { | |
const status = await LocationService.getStatus(); | |
this.setState({ | |
isTracking: status.isRunning | |
}); | |
} | |
componentWillUnmount() { | |
LocationService.removeAllListeners(); | |
} | |
onLocationTrackerStarted() { | |
console.log('started'); | |
this.setState({ | |
isTracking: true | |
}); | |
} | |
onLocationTrackerStopped() { | |
console.log('stopped'); | |
this.setState({ | |
isTracking: false | |
}); | |
} | |
onLocationTrackerError(error: any) { | |
console.log('error', error); | |
alert('Se produjo un error al empezar a seguir tu ubicación. Inténtalo de nuevo'); | |
} | |
onToggleDisponible(value: boolean) { | |
this.setState({ isDisponible: value }); | |
} | |
async onToggleLocationTracker() { | |
try { | |
await LocationService.toggleTracker(); | |
} catch (error) { | |
switch (error.message) { | |
case LocationError.PERMISOS_NO_OTORGADOS: | |
alert('Necesitamos que nos des permiso para seguir tu ubicación'); | |
break; | |
case LocationError.GPS_DESACTIVADO: | |
alert('Debes activar el gps para poder seguir tu ubicación'); | |
break; | |
default: | |
alert('Ups! se produjo un error, vuelve a intentarlo'); | |
} | |
} | |
} | |
render() { | |
return ( | |
<View style={[AppStyles.mainContainer]}> | |
<StatusBar | |
backgroundColor="white" | |
barStyle="dark-content" | |
hidden={false} | |
/> | |
<HeaderBar | |
title={'Mi Perfil'} | |
carrito={false} | |
search={false} | |
/> | |
<ScrollView style={{ flex: 1, marginTop: Platform.OS === 'ios' ? 20 : 0 }}> | |
<SettingItem | |
icon={require('../resources/icons/gps.png')} | |
text={'Siguiendome'} | |
onPress={() => { }} | |
hasSwitch={true} | |
onSwitchValueChange={this.onToggleLocationTracker} | |
switchValue={this.state.isTracking} | |
/> | |
</ScrollView> | |
</View > | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment