Quantcast
Channel: Active questions tagged react-native+android - Stack Overflow
Viewing all 28480 articles
Browse latest View live

Regex for Bank credit transaction SMS [closed]

$
0
0

good day guys,i am currently working on an app with react-native,the goal here is to retrieve users bank sms(credit alerts) and sum the total,i have been able to get and filter the sms using a libary,the problem now is that i need to get the 'amount' from individual sms.Example of the credit sms are:

  • Cr AlertAC NAME: TEST TEST TESTAC#: *4018DESC: NIP FRM FUNSHO EMMANUEL OLUMORDATE:25-Feb-2020 08:39AMT:NGN10,000.00BAL:NGN10,040.41
  • Txn: CreditAc:2XX..11XAmt:NGN 2,366.27Des:TNF-Paystack/Cowrywise WithdrawalCowrywise FinancDate:12-Mar-2020 07:44Bal:NGN 2,347.16

So,the goal now is to get the value of the amount field of these sms.....using regex or whatever method possible,please any help will be appreciated


Issue with Android Emulator no longer connecting to package server

$
0
0

After installing and configuring the react-native-firebase package for my app, running react-native run-android no longer creates a index.android.bundle file. I've been able to work around this by running the following command:

react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res && react-native run-android

However, I now need to run this command every time I make a change to the javascript in my app because the app no longer attempts to connect to the Metro Bundler. I can also not force it to connect by hitting R R and no errors are displayed. The app does launch correctly, just with this large caveat.

I'm not sure where to look here, I'm not an Android/Java Dev. I am on React-Native version 0.59.5

android/build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.buildscript {    ext {        buildToolsVersion = "28.0.3"        minSdkVersion = 16        compileSdkVersion = 28        targetSdkVersion = 28        supportLibVersion = "28.0.0"    }    repositories {        google()        jcenter()    }    dependencies {        classpath 'com.android.tools.build:gradle:3.4.2'        classpath 'com.google.gms:google-services:4.3.0'        // NOTE: Do not place your application dependencies here; they belong        // in the individual module build.gradle files    }}allprojects {    repositories {        mavenLocal()        google()        jcenter()        maven {            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm            url "$rootDir/../node_modules/react-native/android"        }        // ADD THIS        maven {             url 'https://maven.google.com'        }        // ADD THIS        maven { url "https://jitpack.io" }    }}

android/app/build.gradle

apply plugin: "com.android.application"project.ext.vectoricons = [    iconFontNames: [ 'file.icomoon.ttf' ] // Name of the font files you want to copy]apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"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 = falseandroid {    compileSdkVersion 27    buildToolsVersion "27.0.3"    compileSdkVersion rootProject.ext.compileSdkVersion    compileOptions {        sourceCompatibility JavaVersion.VERSION_1_8        targetCompatibility JavaVersion.VERSION_1_8    }    defaultConfig {        applicationId "com.CLIENTNAME"        minSdkVersion rootProject.ext.minSdkVersion        targetSdkVersion rootProject.ext.targetSdkVersion        versionCode 1        versionName "1.0"        vectorDrawables.useSupportLibrary = true        targetSdkVersion 27    }    splits {        abi {            reset()            enable enableSeparateBuildPerCPUArchitecture            universalApk false  // If true, also generate a universal APK            include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"        }    }    buildTypes {        release {            minifyEnabled enableProguardInReleaseBuilds            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"        }    }    // 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, "arm64-v8a": 3, "x86_64": 4]            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-firebase')    implementation project(':react-native-haptic-feedback')    implementation project(':react-native-image-crop-picker')    implementation project(':react-native-video')    implementation project(':@react-native-community_async-storage')    implementation project(':react-native-svg')    implementation project(':react-native-webview')    implementation project(':react-native-vector-icons')    implementation project(':react-native-gesture-handler')    implementation fileTree(dir: "libs", include: ["*.jar"])    implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"    implementation "com.facebook.react:react-native:+"  // From node_modules    // Firebase dependencies    implementation "com.google.android.gms:play-services-base:16.1.0"    implementation "com.google.firebase:firebase-core:17.0.1"    implementation "com.google.firebase:firebase-analytics:17.0.1"}// Run this once to be able to run the application with BUCK// puts all compile dependencies into folder libs for BUCK to usetask copyDownloadableDepsToLibs(type: Copy) {    from configurations.compile    into 'libs'}apply plugin: 'com.google.gms.google-services'

I'm not really sure if there are any other files to place here that could provide context. Please let me know if I'm missing any info here.

I'm expecting that when I run react-native run-android the bundler will run and create the android/app/src/main/res/index.android.bundle file that the app needs to run and that the app will connect to Metro Bundler from the Emulator. This allows me to be able to easily view changes to my JS code in the emulator. There are no error messages to speak of.

How to set android push notification color and icon?

$
0
0

I am using react-native, amplify, and firebase.

I have followed several guides and stack overflow questions to set the android default color and icon for push notifications like this:

<meta-data    android:name="com.google.firebase.messaging.default_notification_icon"    android:resource="@drawable/ic_notification" /><meta-data    android:name="com.google.firebase.messaging.default_notification_color"    android:resource="@color/patch_coral" />

I have a file colors.xml inside of android/app/src/main/res/values/ with this content:

<resources><color name="patch_coral">#E97A6E</color></resources>

And for the icon I have drawable folders inside of android/app/src/main/res/ which contain the ic_notification.png generated in android asset studio as white icons as was instructed in several places.

I have also tested with debug and release builds to see if that would change anything; however, the push notifications still do not have the default icon or color, but it does have the app icon on the right side. Here is an example:

current android push notification example

What needs to be changed or added to get the color and icon to replace the default android color, and square icon?

Running Expo/React Native in Android Device

$
0
0

I have an React Native app developed with Expo, while scanning the QR code works perfectly, when i try to run the app in a connected usb debug succesfully enabled android device with expo start --localhost --android it doesn't launch the app in the device, although it appears everything is ok:

Successfully ran adb reverse. Localhost URLs should work on the connected Android device.

Thanks it advance.

React Native - React Navigation Tab Bar - Custom floating action button

$
0
0

I need some help to use React Native - react navigation library.It is Tab bar, but the Upload button acted as floating action button.

I have try :

const click = () => {  console.log('click');  return (<View><Text>a</Text></View>  );};tabBarOnPress: (tab) => {  click();},// Main Page Navigatorexport const Main = TabNavigator({  Home: {    screen: HomeNavigator,  },  Explore: {    screen: ExploreNavigator,  },  Upload: {    screen: UploadMain,    navigationOptions: ({ navigation }) => ({      tabBarLabel: 'Upload',      tabBarIcon: ({ tintColor }) => (<View><Icon name="camera" size={26} color={tintColor} /></View>      ),      tabBarOnPress: (tab) => {        click();      },    }),  },}, {  tabBarComponent: TabBarBottom,  tabBarPosition: 'bottom',  backBehavior: 'none',  swipeEnabled: false,  lazy: true,  animationEnabled: false,  showIcon: true,  tabBarOptions: {    activeTintColor: 'black',  },});

The Upload button is need to act as floating action button, when it clicked, it already logging, but not rendering the component.Any workaround to create the floating action button?

I've some tricks like this https://github.com/react-navigation/react-navigation/pull/1335

But, it is only click and dispatch navigation, not doing floating action button

Regards,Charlie

react-native logcat Why keep showing: D/EGL_adreno: eglMakeCurrent?

$
0
0

I don't know what this log means.

After this log appears, the application becomes very slow. (UI FPS < 40 )

may I know what is the reason?

04-21 23:43:21.306 15554-15570/***.***.*** D/EGL_adreno: eglMakeCurrent: 0xaf434ac0: ver 3 1 (tinfo 0xaf4394a0)04-21 23:43:21.317 15554-15570/***.***.*** D/EGL_adreno: eglMakeCurrent: 0xaf434ac0: ver 3 1 (tinfo 0xaf4394a0)04-21 23:43:21.856 15554-15570/***.***.*** D/EGL_adreno: eglMakeCurrent: 0xaf434ac0: ver 3 1 (tinfo 0xaf4394a0)04-21 23:43:21.867 15554-15570/***.***.*** D/EGL_adreno: eglMakeCurrent: 0xaf434ac0: ver 3 1 (tinfo 0xaf4394a0)04-21 23:43:22.404 15554-15570/***.***.*** D/EGL_adreno: eglMakeCurrent: 0xaf434ac0: ver 3 1 (tinfo 0xaf4394a0)04-21 23:43:22.412 15554-15570/***.***.*** D/EGL_adreno: eglMakeCurrent: 0xaf434ac0: ver 3 1 (tinfo 0xaf4394a0)04-21 23:43:22.957 15554-15570/***.***.*** D/EGL_adreno: eglMakeCurrent: 0xaf434ac0: ver 3 1 (tinfo 0xaf4394a0)04-21 23:43:22.965 15554-15570/***.***.*** D/EGL_adreno: eglMakeCurrent: 0xaf434ac0: ver 3 1 (tinfo 0xaf4394a0)

Windows error :spawnSync ./gradlew EACCES error when running react native project on emulator

$
0
0

Am trying to run react native using react-native run-android but I get the above error. I was having issues getting my detached expo to run on android emulator and I keep getting this error Error running app. Have you installed the app already using Android Studio? Since you are detached you must build manually. Error: Activity not started, unable to resolve Intent { act=android.intent.action.VIEW dat=....After hours of futile effort i tried running react-native run-android but I keep getting the above error (title). solution online spawnSync ./gradlew EACCES error when running react native project on emulator udara shows its a permission issue and that it can be resolved with chmod 755 android/gradlew since am using a windows system i tried ICACLS "android/gradlew" /grant:r "Administrator:(F)" /Cbut I still get the same error. am not really good with icacls so I may be wrong. any assistance is highly appreciated.My emulator is working perfectly cause i did a adb devices check and its their. I even have the emulator already open on my window

Error : Native Module RNGeocoder tried to override RNGeocoderModule when I use the react-native-geocoder package in react native

$
0
0

I am building a React Native application and In this application, I need to get the location of a Particular area that is Street Address, City and Country.

I am trying to use react-native-geocoder package to get this information.

When I follow the tutorial and edit my MainApplication.java, setting.gradle, build.gradle and my codes as;

The link to the tutotiral and github repo of the packagehttps://github.com/devfd/react-native-geocoder

_getLocationAsync = async () => {    var NY = {          lat: 40.7809261,          lng: -73.9637594        };    Geocoder.geocodePosition(NY).then(res => {     this.setState({       locationObj: res     });     console.log(res)    // res is an Array of geocoding object (see below)    })   .catch(err => console.log(err))    this.setState({        procesingLocation: false,    });   };

I get the following Error on screen of my emulator;

native module RNGeocoder tried to override RNGeocoderModule. Check the getPackages() method in MainApplication.java, it might be that module is being created twice . if this was your intention set canoverrideExistingModule=true

My MainApplication.java looks has the following codes;

import com.devfd.RNGeocoder.RNGeocoderPackage;@Overrideprotected List<ReactPackage> getPackages() {  @SuppressWarnings("UnnecessaryLocalVariable")  List<ReactPackage> packages = new PackageList(this).getPackages();  // Packages that cannot be autolinked yet can be added manually here, for example:  // packages.add(new MyReactNativePackage());  packages.add(new RNGeocoderPackage());  return packages;}

Please any help on this will be appreciated.


How do you debug React Native?

$
0
0

How does one debug their React code with React Native while the app is running in app simulator?

How to Google Cast using React Native Web

$
0
0

I've been looking for a way to use Google Cast on React Native Web i.e. use the SDK on a Web browser on Android and iOS. I haven't found anything so far. Obviously there is the js/html sdk for Chrome but I fail to see how to integrate that into a react-web project.

Is it not possible to use the cast-sdk in a browser in Android or iOS?

Create menu on React Native using StackNavigator with fetching data from API

$
0
0

I am new in react native and doing the menu for ecommerce. There is menu with different nesting depth on server. For example:

Main Category List

[    {"category_id": xxx,        "name": "parent_1",        //level_1        child {"category_id": xxx,        "name": "xxx","parent_id": xxx            //level_2            child {"category_id": xxx,        "name": "xxx","parent_id": xxx                //level_3                 child {"category_id": xxx,        "name": "xxx","parent_id": xxx                    //level_4                    child {"category_id": xxx,        "name": "xxx","parent_id": xxx                        //product_list                        product{"category_id": xxx,        "name": "xxx","description": xxx                        }                    }                }            }        }    },    {"category_id": xxx,       "name": "parent_2",        //level_1        child {"category_id": xxx,        "name": "xxx","parent_id": xxx            //level_2            child {"category_id": xxx,        "name": "xxx","parent_id": xxx                //product_list                product{"category_id": xxx,        "name": "xxx","description": xxx                }            }        }    },    {"category_id": xxx,"name": "parent_3",        child {"category_id": xxx,        "name": "xxx","parent_id": xxx            //level_2            child {"category_id": xxx,        "name": "xxx","parent_id": xxx                //level_3                 child {"category_id": xxx,        "name": "xxx","parent_id": xxx                    //product_list                    product{"category_id": xxx,        "name": "xxx","description": xxx                    }                }            }        }    },    {"category_id": xxx,"name": "parent_4",            //product_list            product{"category_id": xxx,        "name": "xxx","description": xxx            }    },    ...]

In example you can see that categories has vary structure such as parent_category->product_list or parent_category->level_1->level_2->level_3->level_4->product_list.

Question: I cannot create transition between pages after fetching menu data from parent_category to product. How to create flexible menu depending from nesting depth? I think it need two pages Category.js and Product.js. In to the Category.js passed value of category_id and to Product.js value of product_id. Or i need to create page for every category personally?Could you help me?

Main.js

import * as React from 'react';import { Text, View } from 'react-native';import { Icon } from 'native-base';import { NavigationContainer } from '@react-navigation/native';import { createMaterialBottomTabNavigator } from '@react-navigation/material-bottom-tabs';import Home from './page/Home'import Category from './page/Category'import Cart from './page/Cart'function ProfileScreen() {  return (<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}><Text>Профиль!</Text></View>  );}const Tab = createMaterialBottomTabNavigator();export default function Main() {  return (<NavigationContainer><Tab.Navigator      // initialRouteName="Home"      // activeColor="#f0edf6"      // inactiveColor="#fff"      screenOptions={({ route }) => ({          tabBarIcon: ({ focused, color, size }) => {            let iconName;            if (route.name === 'Главная') {              iconName = focused ? 'ios-home' : 'ios-home';            } else if (route.name === 'Каталог') {              iconName = focused ? 'ios-list' : 'ios-list';            } else if (route.name === 'Корзина') {              iconName = focused ? 'ios-cart' : 'ios-cart';            } else if (route.name === 'Профиль') {              iconName = focused ? 'ios-person' : 'ios-person';            }            // You can return any component that you like here!            return <Icon name={iconName} size={100} color="#F79A3D" />;          },        })}      barStyle={{ backgroundColor: '#fff' }}><Tab.Screen name="Главная" component={Home} /><Tab.Screen name="Каталог" component={Category} /><Tab.Screen name="Корзина" component={Cart} /><Tab.Screen name="Профиль" component={ProfileScreen} /></Tab.Navigator></NavigationContainer>  );}

src/Category.js

import React from 'react';import { StyleSheet, Text, FlatList, ActivityIndicator, View, TouchableOpacity,ScrollView} from 'react-native';import {  SearchBar, Avatar } from "react-native-elements";import { Container, Content, List, ListItem, Button, Icon } from 'native-base';import { createStackNavigator } from '@react-navigation/stack';import {NavigationContainer} from '@react-navigation/native';const Stack = createStackNavigator();export default class Category extends React.Component { constructor(props) {    super(props);    this.state  = {      isLoading: true,      dataSource: null,    }  }  componentDidMount() {    return fetch('http://app.site.ru/catalog') //How to pass this value of category_id?      .then (( response ) => response.json())      .then (( responseJson ) =>{        this.setState({          isLoading: false,          dataSource: responseJson,          })        })      .catch((error) => {        console.log(error)      });  }  render() {    if (this.state.isLoading) {      return (<View styles={[styles.container]}><ActivityIndicator size="large" /></View>      )    } else {      let catalog = this.state.dataSource.map((val, key) => {        return (<List key={key}><ListItem><TouchableOpacity              onPress={() => {                ???;              }}><Text>{val.name}</Text></TouchableOpacity></ListItem></List>        );      });      return (<ScrollView>          {catalog}</ScrollView>      );    }  }}

Getting errors while installing react-native app using android studio

$
0
0

Why this error ;

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve project :react-native-restart.

React native android can not find com.android.tools.build:gradle:3.6.3

$
0
0

Any people met the issue Could not resolve all artifacts for configuration ':react-native-fast-image:classpath' and can not find com.android.tools.build:gradle:3.6.3 ? I try open the project structure and see the gradle plugin tool is 3.6.3 and the gradle version is 5.4.6 but i dont know what happen now

The build.gradle file :

// Top-level build file where you can add configuration options common to all sub-projects/modules.buildscript {    /*ext {        buildToolsVersion = "28.0.2"        minSdkVersion = 16        compileSdkVersion = 28        targetSdkVersion = 27        supportLibVersion = "28.0.0"    }*/    repositories {        jcenter()        google()        maven {            url 'https://maven.google.com/'            name 'Google'        }        mavenCentral()    }    dependencies {        classpath 'com.android.tools.build:gradle:3.5.0'        classpath 'com.google.gms:google-services:4.0.1'        // NOTE: Do not place your application dependencies here; they belong        // in the individual module build.gradle files    }}allprojects {    repositories {        configurations.all {            resolutionStrategy.eachDependency { details ->                def requested = details.requested                if (requested.group == 'com.google.android.gms') {                    details.useVersion '12.0.1'                }                if (requested.group == 'com.google.firebase') {                    details.useVersion '12.0.1'                }            }        }        mavenLocal()        mavenCentral()        google()        jcenter()        maven {            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm            url "$rootDir/../node_modules/react-native/android"        }        maven {            url 'https://maven.google.com/'            name 'Google'        }    }}subprojects {    project.configurations.all {        resolutionStrategy.eachDependency { details ->            if (details.requested.group == 'com.android.support'&& !details.requested.name.contains('multidex') ) {                details.useVersion "27.1.1"            }        }    }}ext {    buildToolsVersion = "28.0.3"    minSdkVersion = 16    compileSdkVersion = 28    targetSdkVersion = 28    supportLibVersion = "28.0.0"    googlePlayServicesVersion = "15.0.1"    androidMapsUtilsVersion = "0.5+"}project.ext {    excludeAppGlideModule = true}/*task wrapper(type: Wrapper) {    gradleVersion = '4.7'    distributionUrl = distributionUrl.replace("bin", "all")}*/

Developer Error while logging in with google in react-native + firebase

$
0
0

I am trying to log in with google in my project build in react-native. I am testing it on a real android device. But it is giving DEVELOPER ERROR while signing in. I have added the SHA 1 certificate of the debug.keystore formed in android/app directory of the project to the project setting in firebase console.

ERROR:

This is the error image

The following is how I am implementing it.

import { GoogleSignin } from '@react-native-community/google-signin';import auth from '@react-native-firebase/auth';const GoogleLogin = () => {  useEffect(() => {    GoogleSignin.configure({      webClientId: '************************', // From Firebase Console Settings    });  }, [])  async function onGoogleButtonPress() {    console.log('i am running on google login function')    // Get the users ID token    const { idToken } = await GoogleSignin.signIn();    console.log('idToken :', idToken)    // Create a Google credential with the token    const googleCredential = auth.GoogleAuthProvider.credential(idToken);    // Sign-in the user with the credential    return auth().signInWithCredential(googleCredential);  }  const handleSignIn = () => {    onGoogleButtonPress()      .then(() => {        console.log('Signed in with google.')      })      .catch((err) => console.log('error while signing in with Google:', err))  }  return (<Button      title="Google Sign-In"      onPress={handleSignIn}    />  )}

In handleSignIn method, it is going in .catch.

Any help is appreciated

React Native Android location request timed out

$
0
0

In IOS there isn't a problem while looking for gps coords. It works fine.

On Android side its not stable as IOS. This problem both in real device and emulator. Sometimes it can find location, but sometimes not. Looking for 3days but there wasn't find a solution.

When my app cannot find my location, I tried via Google Maps app, it works like charm.

Here is my code for both IOS and Android;

getCurrentPosition() {    navigator.geolocation.getCurrentPosition(        (position) => {            this.setState({ initialPosition: position });            alert(JSON.stringify(position))            var coords = new Coords();            coords.Latitude = position.coords.latitude;            coords.Longitude = position.coords.longitude;            this.getPharmaciesByCoordinates(coords);        },        (error) => alert(error.message),        { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }    );    this.watchID = navigator.geolocation.watchPosition((position) => {        this.setState({ initialPosition: position });    },        (error) => alert(error.message),        { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }    );}

Any kind of solution is welcome.

Thanks


connect vpn programmatically react native for android ios

$
0
0

I am new to react native, I want to make a VPN client app for Android and IOS. VPN protocol should be IPSec or IKEv2 or any other. I have tried these:

1. OpenVPN

node-openvpn and openvpn-bin but no luck

const openvpnmanager = require('node-openvpn'); **const opts = {  host: '127.0.0.1', // normally '127.0.0.1', will default to if undefined  port: 1337, //port openvpn management console  timeout: 1500, //timeout for connection - optional, will default to 1500ms if undefined  logpath: 'log.txt' //optional write openvpn console output to file, can be relative path or absolute};const auth = {  user: 'vpnUserName',  pass: 'vpnPassword',};const openvpn = openvpnmanager.connect(opts)// will be emited on successful interfacing with openvpn instanceopenvpn.on('connected', () => {  openvpnmanager.authorize(auth);})

2. react native open settings

react-native-device-setting and react-native-open-settings in which they have showed to programmatically open android phone settings like:

install package: npm install react-native-device-settings --save

usage:

import DeviceSettings from 'react-native-device-settings';DeviceSettings.open(); // Open settings menuDeviceSettings.app(); // Open app settings menuDeviceSettings.wifi(); // Open wifi settings menu

but there is no method to open VPN Settings and configure VPN. 47306057 has also asked the same problem

Can anyone help me out in this? Thanks

Activity is very slow to show when screen is locked and app crash when call requestDismissKeyguard()

$
0
0

I need for my call video app a screen to show even when screen is locked. I used this very good tutorial to achieve this and it's working, screen wake when user receives a call.

But my problem is that this screen is very slow, it takes 4-5 seconds to turn screen on, it takes 5 seconds to respond when I press a button...

Also I want the Keyguard to be dismissed when I press imageView button(bring up the UI so the user can enter their credentials: PIN, password, pattern...) so I used requestDismissKeyguard but the app crashes when I call it.

I read that in my case it's better to use a service instead of activity but I don't know how to convert My activity into a service. I'm not very familiar with android development so I don't know where the problem came from.

ReactMethod in ActivityStarterModule.java

@ReactMethodvoid showActivity(String text) {Intent myIntent = new Intent((Application)reactContext.getApplicationContext(), BackgroundCallActivity.class);        myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);        Bundle b = new Bundle();        b.putString("text", text);        myIntent.putExtras(b);        ((Application)reactContext.getApplicationContext()).startActivity(myIntent);    }

My activity in AndroidManifest

...<uses-permission android:name="android.permission.WAKE_LOCK" /><uses-permission android:name="android.permission.DISABLE_KEYGUARD"/><activity        android:name="BackgroundCallActivity"        android:showOnLockScreen="true"        android:screenOrientation="sensorPortrait"/>...

Here's my activity code

package com.my_project;import android.app.Activity;import android.os.Bundle;import androidx.annotation.CallSuper;import androidx.annotation.Nullable;import android.view.View;import android.view.WindowManager;import android.os.Build;import android.app.KeyguardManager;import android.content.Context;import android.widget.TextView;import android.view.MotionEvent;import android.view.View;import android.widget.ImageView;public class BackgroundCallActivity extends Activity {    TextView textView;    @Override    @CallSuper    protected void onCreate(@Nullable Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.background_call_activity);        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1){            setShowWhenLocked(true);            setTurnScreenOn(true);        } else {            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD |                    WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |                    WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);        }        Bundle b = getIntent().getExtras();        String value = b.getString("text");        textView = (TextView)findViewById(R.id.textView);        textView.setText(value);        ImageView imageView = (ImageView)findViewById(R.id.answer);        final TextView mCustomToast = (TextView)findViewById(R.id.textView2);                mCustomToast.setVisibility(View.INVISIBLE);                imageView.setOnTouchListener(new View.OnTouchListener() {                    @Override                    public boolean onTouch(View v, MotionEvent event) {                    KeyguardManager keyguardManager = (KeyguardManager)                    getSystemService(Context.KEYGUARD_SERVICE);                    if( keyguardManager.isKeyguardLocked()) {                        keyguardManager.requestDismissKeyguard(BackgroundCallActivity.this, null);                      } else {                        ActivityStarterModule.triggerAlert("answer");                        finish();                    }                        return false;                    }                });        ImageView imageView1 = (ImageView)findViewById(R.id.hangup);                imageView1.setOnTouchListener(new View.OnTouchListener() {                    @Override                    public boolean onTouch(View v, MotionEvent event) {                        ActivityStarterModule.triggerAlert("reject");                        finish();                        return false;                    }                });    }}

Have you any suggestion to remove this delay and to make requestDismissKeyguard work it will be great.

Could not run the react-native application

$
0
0

I am getting this error while installing application.

More than one file was found with OS independent path 'lib/x86/libc++_shared.so'

How to Activate GPS Icon in react-native?

$
0
0

I want to appear GPS Icon on the status bar when I open app or screen that's contain Map, So I add a function that asks a user at the first time to allow Location permission and it's work very well and I can get Lat/Long but GPS "Location" Icon did not activate so how can I force an app to activate this icon?

GPS

here's my Ask for permission function

 async requestLocationPermission() {    try {      const granted = await PermissionsAndroid.request(        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,        {          title: 'App Location Permission',          message: 'App needs access to your Location ',          buttonNeutral: 'Ask Me Later',          buttonNegative: 'Cancel',          buttonPositive: 'OK',        },      );      if (granted === PermissionsAndroid.RESULTS.GRANTED) {        this.getLocation();      } else {        this.setState({next: false});      }    } catch (err) {      console.log('err ', err);    }  }getLocation = async () => {    const {companyLocation, Domain} = this.props.navigation.state.params;    Geolocation.getCurrentPosition(      position => {        this.setState(          {            mapData: {              latitude: position.coords.latitude,              longitude: position.coords.longitude,              latitudeDelta: 0.015,              longitudeDelta: 0.0121,            },            markerData: {              latitude: position.coords.latitude,              longitude: position.coords.longitude,              latitudeDelta: 0.015,              longitudeDelta: 0.0121,            },            error: null,          },          () => {            let {              latitudeDelta,              longitudeDelta,              ...userLocation            } = this.state.mapData;            let howFar = Math.round(haversine(userLocation, companyLocation));            howFar > Domain              ? (alert('we not work in your area.'),                this.setState({next: false}))              : null;          },        );      },      error => this.setState({error: error.message}),    );    this.watchID = Geolocation.watchPosition(position => {      const latitude = position.coords.latitude;      const longitude = position.coords.longitude;      this.setState({      mapData: {        latitude: latitude,        longitude: longitude,        latitudeDelta: 0.015,        longitudeDelta: 0.0121,      },    });    });  };

View and Search PDF or doc Files in React Native

Viewing all 28480 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>