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

android emulator always giving error emu-crash-xx-xx.db and quit before it finished opening

$
0
0

I have completed new setup in windows for react native :whenever I am trying to start the emulator from command I am getting this issue , but I can open emulator inside android studio without any problem

> react-native run-android* daemon not running; starting now at tcp:5037* daemon started successfullyinfo Launching emulator...error Failed to launch emulator. Reason: The emulator (INFO    | Storing crashdata in: C:\Users\arunk\AppData\Local\Temp\\AndroidEmulator\emu-crash-34.1.18.db, detection is enabled for process: 13500) quit before it finished opening. You can try starting the emulator manually from the terminal with: C:\Users\arunk\AppData\Local\Android\Sdk/emulator/emulator @INFO    | Storing crashdata in: C:\Users\arunk\AppData\Local\Temp\\AndroidEmulator\emu-crash-34.1.18.db, detection is enabled for process: 13500.warn Please launch an emulator manually or connect a device. Otherwise app may fail to launch.info Installing the app...
BUILD FAILED in 19serror Failed to install the app. Command failed with exit code 1: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081 FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':app:installDebug'. > com.android.builder.testing.api.DeviceException: No online devices found. * Try: > Run with --stacktrace option to get the stack trace. > Run with --info or --debug option to get more log output. > Run with --scan to get full insights. > Get more help at https://help.gradle.org. BUILD FAILED in 19s.

raised issue on github too text

I am trying to run android emulator usign

npm run android 

or

npx react-native run-android

expected : after metro start android emulator should start automaticallybut it is failing everytime and giving this emu-crash.db logs issue

trying to delete that log file tootried to run different version of react native too


Embedding Native Android Activity in React Native

$
0
0

I am making tab bar in android in react native using this library

https://github.com/aksonov/react-native-tabs

I have to open native android activity in one of the page.Can you please let me know how to embed android activity in react native so that tabs will be visible all the time.

Measuring Distance from the Floor in Expo/React Native

$
0
0

I'm currently working on a project in Expo/React Native and need to create a control that will indicate whether the distance from the floor to device is appropriate—it can't be too large or too small. Does anyone know how to measure the distance from the floor within these frameworks? Any pointers or tips would be greatly appreciated!

Missing-asset-registry-path for @react-navigation/elements/lib/commonjs/assets/back-icon-mask.png on RN 70.6

$
0
0
When building my app I get the following error message since I switched to React Native 70.6 (Android and iOS), without @react-navigation everything works. On React Native 69.7, the app runs without problems with the identical @react-navigation versions.Error: Unable to resolve module missing-asset-registry-path from /node_modules/@react-navigation/elements/lib/commonjs/assets/back-icon-mask.png: missing-asset-registry-path could not be found within the project or in these directories:  node_modules> 1 | �PNG  2 |   3 |   4 | IHDR2���gAMA���a cHRMz&�����u0�`:�p��Q<bKGD���̿tIME�    at ModuleResolver.resolveDependency (/node_modules/metro/src/node-haste/DependencyGraph/ModuleResolution.js:178:15)    at DependencyGraph.resolveDependency (/node_modules/metro/src/node-haste/DependencyGraph.js:264:43)    at Object.resolve (/node_modules/metro/src/lib/transformHelpers.js:170:21)    at resolveDependencies (/node_modules/metro/src/DeltaBundler/graphOperations.js:466:33)    at processModule (/node_modules/metro/src/DeltaBundler/graphOperations.js:232:31)    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)    at async addDependency (/node_modules/metro/src/DeltaBundler/graphOperations.js:361:18)    at async Promise.all (index 18)    at async processModule (/node_modules/metro/src/DeltaBundler/graphOperations.js:279:3)    at async addDependency (/node_modules/metro/src/DeltaBundler/graphOperations.js:361:18)

Camera capture stopped working after upgrading from Expo SDK 50 -> 51

$
0
0

So I just upgraded from SDK 50 -> 51 which made my app crash all the time I go to component with a Camera, now i fixed it, my current "take picture" method does not work. Do you guys know how to fix this?

const captureImage = async () => {        if (camRef) {            try {                const imgData = await camRef.current.takePictureAsync({                    base64: false,                    imageType: ImageType.png,                });                setImage(imgData);            } catch (err) {                console.log(err);            }        }    }

I tried using other methods but doesnt work

Expo go instantly crashes without error message (React Native)

$
0
0

Problem:

Hey Stackoverflow. Because of internet issues, I was testing my react native app last week only in the web emulator. Now I wanted to try it in the Expo go, mobile emulator. But as soon as I connect to the project and the js is fully built, the whole app crashes without an error message.

What I have tried to fix it:

I now connected my phone to my windows pc and ran this logcat command: adb logcat *:S ReactNative:V ReactNativeJS:V to get the error message this way. But I can't figure out what the problem is.

The logcat command logs this when I run the app:

10-19 13:54:39.731  9429 11453 I ReactNativeJS: Running "main" with {"initialProps":{"exp":{}},"rootTag":1}10-19 13:54:39.801  9429 11453 W ReactNativeJS: Constants.installationId has been deprecated in favor of generating and storing your own ID. Implement it using expo-application's androidId on Android and a storage API such as expo-secure-store on iOS and localStorage on the web. This API will be removed in SDK 44.10-19 13:54:46.209  9429 11682 I ReactNativeJS: Running "main" with {"initialProps":{"exp":{"initialUri":"exp://192.168.1.111:19000","shell":false,"manifestString":"{\"name\":\"productivity\",\"slug\":\"productivity\",\"version\":\"1.0.0\",\"orientation\":\"portrait\",\"icon\":\".\\/assets\\/icon.png\",\"splash\":{\"image\":\".\\/assets\\/splash.png\",\"resizeMode\":\"contain\",\"backgroundColor\":\"#ffffff\",\"imageUrl\":\"http:\\/\\/192.168.1.111:19000\\/assets\\/.\\/assets\\/splash.png\"},\"updates\":{\"fallbackToCacheTimeout\":0},\"assetBundlePatterns\":[\"**\\/*\"],\"ios\":{\"supportsTablet\":true},\"android\":{\"adaptiveIcon\":{\"foregroundImage\":\".\\/assets\\/adaptive-icon.png\",\"backgroundColor\":\"#FFFFFF\",\"foregroundImageUrl\":\"http:\\/\\/192.168.1.111:19000\\/assets\\/.\\/assets\\/adaptive-icon.png\"}},\"web\":{\"favicon\":\".\\/assets\\/favicon.png\"},\"_internal\":{\"isDebug\":false,\"projectRoot\":\"D:\\\\coding\\\\apps\\\\productivity\",\"dynamicConfigPath\":null,\"staticConfigPath\":\"D:\\\\coding\\\\apps\\\\productivity\\\\app.json\",\"packageJsonPath\":\"D:\\\\coding\\\\apps\\\\productivity\\\\package.json\"},\"sdkVersion\":\"42.0.0\",\"platforms\":[\"ios\",\"android\",\"web\"],\"developer\":{\"tool\":\"expo-cli\",\"projectRoot\":\"D:\\\\coding\\\\apps\\\\productivity\"},\"packagerOpts\":{\"scheme\":null,\"hostType\":\"lan\",\"lanType\":\"ip\",\"devClient\":false,\"dev\":true,\"minify\":false,\"urlRandomness\":\"2s-g42\",\"https\":false},\"mainModuleName\":\"node_modules\\\\expo\\\\AppEntry\",\"__flipperHack\":\"React Native packager is running\",\"debuggerHost\":\"192.168.1.111:19000\",\"logUrl\":\"http:\\/\\/192.168.1.111:19000\\/logs\",\"hostUri\":\"192.168.1.111:19000\",\"bundleUrl\":\"http:\\/\\/192.168.1.111:19000\\/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false&minify=false\",\"iconUrl\":\"http:\\/\\/192.168.1.111:19000\\/assets\\/.\\/assets\\/icon.png\",\"id\":\"UNVERIFIED-192.168.1.111-productivity\",\"isVerified\":true,\"primaryColor\":\"#023C69\"}"}},"rootTag":1}

these are my versions if that is important:

"dependencies": {"@babel/preset-env": "^7.15.8","@react-native-async-storage/async-storage": "^1.15.9","@react-native-community/datetimepicker": "^3.5.2","@react-native-community/masked-view": "^0.1.11","async-storage": "^0.1.0","date-fns": "^2.25.0","expo": "^42.0.4","expo-status-bar": "~1.0.4","react": "16.13.1","react-dom": "16.13.1","react-native": "https://github.com/expo/react-native/archive/sdk-42.0.0.tar.gz","react-native-color-palette": "^2.2.0","react-native-gesture-handler": "^1.10.3","react-native-reanimated": "^1.13.1","react-native-screens": "^3.8.0","react-native-svg": "^12.1.1","react-native-vector-icons": "^8.1.0","react-native-web": "~0.13.12","react-navigation": "^4.4.4","react-navigation-drawer": "^2.7.1","react-navigation-stack": "^2.10.4"  },

I hope you can help me. Feel free to leave a comment with another logcat command that I can run too.

OAuth 2.0 access token expires within an hour [closed]

$
0
0

I've been working on implementing FCM for the chat functionality in my React Native app. I've opted for the HTTP v1 API, which requires an OAuth 2.0 access token. The challenge I'm facing is that this token expires within an hour.

Since I'm running a PHP server (CI) for my app under development, I can't utilize the Service Account or Admin SDK. That means I need to find a way to obtain this token within my React Native code. After some research, it seems like using react-native-app-auth might be the solution, but I'm not posting the push notification even I get the access token on my end. 403 error occurred.

Here is my code:

const getOauthToken = async () => {        const config = {          clientId: '********',          redirectUrl: '******:/oauth2redirect',          scopes: ['email', 'https://www.googleapis.com/auth/firebase.messaging'],          serviceConfiguration: {            authorizationEndpoint: 'https://accounts.google.com/o/oauth2/v2/auth',            tokenEndpoint: 'https://oauth2.googleapis.com/token',          },        };        try {          const result = await authorize(config);          console.log('Access Token=======>>>>>>>>>>>>>>>>>>>>>>>>>', result);          global.authToken = result.accessToken        } catch (error) {          console.log("Error:", error.message);        }      }const sendNotification = (msgArray) => {      const projectID = '******';       const url = `https://fcm.googleapis.com/v1/projects/${projectID}/messages:send`;      const notification_body = `${msgArray[0].text}`      const notification_title = `${global.firstName} ${global.lastName} (${global.vendor_region})`      adminTokens.forEach(async (token) => {        let notificationData = {          message: {              token: token,              notification: {                  body: notification_body,                  title: notification_title,              }          }        };        try {          const response = await axios.post(url, notificationData, {              headers: {'Content-Type': 'application/json','Authorization': `Bearer ${global.authToken}`              }          });          console.log('Notification sent successfully:', response.data);        } catch (error) {            console.error('Error sending notification:', error);        }      });    }

How to ask for notifications permission on Android using react-native 0.68?

$
0
0

My project is running on react-native 0.68.5 and I can't upgrade it, is there a way to ask for notifications using this react native version?

Right now it's working with previous Android versions, but I want my app to ask for these kind of permissions on newer android versions.


How to capture audio from other applications while using GetDisplayMedia for screen sharing in a React Native app?

$
0
0

I've implemented screen sharing using WebRTC in my React Native app, but I'm encountering an issue where the audio from other apps, such as YouTube, is not being captured during screen broadcasting.

Below is the React Native code snippet I'm using for screen sharing:

const screenShareStreamRef = useRef();const [screenShareStream, setScreenShareStream] = useState(null);const screenShareVideoProducer = useRef();const screenShareAudioProducer = useRef();let audioTrack, videoTrack, screenstream;  const startScreenStream = async () => {    try {      const displayStream = await mediaDevices.getDisplayMedia({ video: true });      videoTrack = displayStream.getVideoTracks()[0];      const audioStream = await mediaDevices.getUserMedia({ audio: true });      audioTrack = audioStream.getAudioTracks()[0];      // Combine video and audio tracks into a single MediaStream      screenstream = new MediaStream([videoTrack, audioTrack]);      screenShareStreamRef.current = screenstream;      setScreenShareStream(screenstream);    } catch (error) {      console.error(error);    }})

For both iOS and Android, I've followed the setup provided in this guide: Link to the setup guide.

Additionally, for iOS, I've added the necessary files into the project, as mentioned in the guide: Link to the files.

I'm looking for insights or solutions on how to capture audio from other apps during screen sharing. Any help would be appreciated. Thank you!

React Native WebView not working properly on older Android SDK's (API 29 and below)

$
0
0

I'm developing a React Native application where I'm using WebView to display a webpage. However, I'm encountering an issue specifically on devices running Android SDK lower than 30 (API 29 and below).When I load my website page in the WebView, some buttons and div behaviors (such as collapsible divs and menus) don't seem to respond at all to user interaction. If I open the same website on the device/emulator browser, the behavior is as expected.
At first I thought it was related to the Expo SDK that I was using (SDK 50), but apparently it was not. I created a react native application without Expo and the behavior persisted. Also changed configs in build.gradle (like targetSdkVersion) but it didn't work. After failing to find a solution, I tried to create an app using Flutter to see if the same thing would happen, and it did.

To illustrate the problem I used Slack's homepage, which also replicates my problem. When I click the menu icon on the upper right corner, nothing happens. If I use Android API 30 or above, the menu appears.

My code:

<WebView      ref={webref}      //androidLayerType={'hardware'}      //mixedContentMode="compatibility"      style={$container}      source={{ uri: "https://www.slack.com" }}      /*source={{        uri: `${getAddress}`,        headers: {          Authorization: `Bearer ${getToken}`,        },      }}*/      onError={(error) => console.error(error)}      onHttpError={(error) => console.error(error)}      onOpenWindow={(event) => console.log(event)}      javaScriptCanOpenWindowsAutomatically={true}      domStorageEnabled={true}       javaScriptEnabled={true}      //userAgent={`webview-${Platform.OS === "ios" ? "ios" : "android"}`}      /*originWhitelist={['http://*']}      contentMode={"mobile"}      sharedCookiesEnabled={true}      allowsLinkPreview={true}      allowFileAccess={true}*/    />

Behavior:                                                                                               Expected:

 

Any help or suggestions on how to resolve this issue would be greatly appreciated. Thank you!

Proguard not removing Logs from AAR dependency

$
0
0

My andorid app depends on an aar file. The aar comes with its own proguard file inside. So I unzipped the aar and added the following in the proguard file:

-assumenosideeffects class android.util.Log {    public static *** d(...);    public static *** v(...);    public static *** i(...);    public static *** w(...);    public static *** e(...);}

I then rezipped the aar and compiled my app. Here is the relevant part of my apps's build.gradle:

release {            signingConfig signingConfigs.debug            shrinkResources (findProperty('android.enableShrinkResourcesInReleaseBuilds')?.toBoolean() ?: false)            minifyEnabled enableProguardInReleaseBuilds            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"        }

Proguard is removing all logs from my own app. But I can still see logs coming from the aar.

What am I missing?

Could not find com.google.vr:sdk-base:1.180.0

$
0
0

I am trying to render panaroma image on my react-native application. Tried few packages, but most of the devs suggesting this https://github.com/lightbasenl/react-native-panorama-view.

Since, I have made some changes on build.gradlew for the package. I couldn't able to build the app. Is there anyway to fix this issue

build.gradle (app)

buildscript {    ext {        buildToolsVersion = "34.0.0"        minSdkVersion = 23        compileSdkVersion = 34        targetSdkVersion = 34        ndkVersion = "26.1.10909125"        kotlinVersion = "1.9.22"    }    repositories {        flatDir {            dirs 'libs'        }        google()        mavenCentral()    }    dependencies {        classpath("com.android.tools.build:gradle")        classpath("com.facebook.react:react-native-gradle-plugin")        classpath("org.jetbrains.kotlin:kotlin-gradle-plugin")    }}subprojects { subproject ->    if(project['name'] == 'lightbase_react-native-panorama-view'){        project.configurations { compile { } }    }}apply plugin: "com.facebook.react.rootproject"

build.gradle (react-native-panorama-view)

buildscript {    repositories {        google()        mavenCentral()    }    dependencies {        // Matches recent template from React Native (0.59)        // https://github.com/facebook/react-native/blob/0.59-stable/template/android/build.gradle#L16        classpath 'com.android.tools.build:gradle:3.3.2'    }}apply plugin: 'com.android.library'apply plugin: 'maven-publish'def safeExtGet(prop, fallback) {    rootProject.ext.has(prop) ? rootProject.ext.get(prop) : fallback}// Matches values in recent template from React Native (0.59)// https://github.com/facebook/react-native/blob/0.59-stable/template/android/build.gradle#L5-L9def DEFAULT_COMPILE_SDK_VERSION = 28def DEFAULT_BUILD_TOOLS_VERSION = "28.0.3"def DEFAULT_MIN_SDK_VERSION = 19def DEFAULT_TARGET_SDK_VERSION = 28android {  compileSdkVersion safeExtGet('compileSdkVersion', DEFAULT_COMPILE_SDK_VERSION)  buildToolsVersion safeExtGet('buildToolsVersion', DEFAULT_BUILD_TOOLS_VERSION)  defaultConfig {    minSdkVersion safeExtGet('minSdkVersion', DEFAULT_MIN_SDK_VERSION)    targetSdkVersion safeExtGet('targetSdkVersion', DEFAULT_TARGET_SDK_VERSION)    versionCode 1    versionName "1.0"  }  lintOptions {    abortOnError false  }}repositories {    maven {        // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm        // Matches recent template from React Native (0.59)        // https://github.com/facebook/react-native/blob/0.59-stable/template/android/build.gradle#L30        url "$projectDir/../node_modules/react-native/android"    }    mavenCentral()}dependencies {    implementation 'com.facebook.react:react-native:+'    // Panorama    implementation "androidx.annotation:annotation:1.1.0"    implementation 'com.google.vr:sdk-base:1.180.0'    implementation 'com.google.vr:sdk-common:1.180.0'    implementation 'com.google.vr:sdk-commonwidget:1.180.0'    implementation 'com.google.vr:sdk-panowidget:1.180.0'    implementation 'commons-io:commons-io:2.5'}def configureReactNativePom(def pom) {    def packageJson = new groovy.json.JsonSlurper().parseText(file('../package.json').text)    pom.project {        name packageJson.title        artifactId packageJson.name        version = packageJson.version        group = "nl.lightbase"        description packageJson.description        url packageJson.repository.baseUrl        licenses {            license {                name packageJson.license                url packageJson.repository.baseUrl +'/blob/master/'+ packageJson.licenseFilename                distribution 'repo'            }        }        developers {            developer {                id packageJson.author.username                name packageJson.author.name            }        }    }}afterEvaluate { project ->    // some Gradle build hooks ref:    // https://www.oreilly.com/library/view/gradle-beyond-the/9781449373801/ch03.html    task androidJavadoc(type: Javadoc) {        source = android.sourceSets.main.java.srcDirs        classpath += files(android.bootClasspath)        classpath += files(project.getConfigurations().getByName('compile').asList())        include '**/*.java'    }    task androidJavadocJar(type: Jar, dependsOn: androidJavadoc) {        archiveClassifier  = 'javadoc'        from androidJavadoc.destinationDir    }    task androidSourcesJar(type: Jar) {        archiveClassifier  = 'sources'        from android.sourceSets.main.java.srcDirs        include '**/*.java'    }    android.libraryVariants.all { variant ->        def name = variant.name.capitalize()        def javaCompileTask = variant.javaCompileProvider.get()        task "jar${name}"(type: Jar, dependsOn: javaCompileTask) {            from javaCompileTask.destinationDir        }    }    artifacts {        archives androidSourcesJar        archives androidJavadocJar    }    task installArchives(type: Upload) {        configuration = configurations.archives        repositories{            mavenDeployer {                repository url: "file://${projectDir}/../android/maven"                configureReactNativePom pom            }}    }}

My Expo upgrade from 48 to 51 giving Problems

$
0
0

I am updating my expo project from expo 48 to expo 51 and I am getting same error again and again.

Error Image

And my package.json file after running, npm install expo@latest and npx expo install --fix command

{"name": "BelCitiSolSmartLighting","version": "1.0.0","scripts": {"start": "expo start --dev-client","android": "expo run:android","ios": "expo run:ios","web": "expo start --web","eject": "expo eject"  },"dependencies": {"@expo-google-fonts/pt-serif": "^0.2.2","@react-native-async-storage/async-storage": "1.23.1","@react-native-community/art": "^1.2.0","@react-native-community/datetimepicker": "7.7.0","@react-native-community/netinfo": "11.3.1","@react-native-picker/picker": "2.7.5","@react-navigation/bottom-tabs": "^6.3.1","@react-navigation/drawer": "^6.4.1","@react-navigation/native": "^6.1.6","@react-navigation/native-stack": "^6.6.2","axios": "^0.27.2","axios-auth-refresh": "^3.2.2","crypto-js": "^3.1.9-1","dotenv": "^16.0.1","exceljs": "^4.3.0","expo": "~51.0.4","expo-app-loading": "~2.0.0","expo-barcode-scanner": "~13.0.1","expo-build-properties": "~0.12.1","expo-camera": "~15.0.7","expo-constants": "~16.0.1","expo-crypto": "~13.0.2","expo-device": "~6.0.2","expo-file-system": "~17.0.1","expo-image-manipulator": "~12.0.4","expo-image-picker": "~15.0.4","expo-intent-launcher": "~11.0.1","expo-linking": "~6.3.1","expo-location": "~17.0.1","expo-media-library": "~16.0.3","expo-network": "~6.0.1","expo-permissions": "~14.1.1","expo-screen-orientation": "~7.0.4","expo-secure-store": "~13.0.1","expo-sharing": "~12.0.1","expo-splash-screen": "~0.27.4","expo-status-bar": "~1.12.1","expo-updates": "~0.25.11","fs": "0.0.1-security","link": "^1.5.1","material-icons": "^1.13.10","moment": "^2.29.3","native-base": "^3.4.4","react": "18.2.0","react-dom": "18.2.0","react-hook-form": "^7.45.4","react-native": "0.74.1","react-native-barcode-mask": "^1.2.4","react-native-calendars": "^1.1284.0","react-native-chart-kit": "^6.12.0","react-native-dotenv": "^3.3.1","react-native-dropdown-picker": "^5.4.2","react-native-elements": "^3.4.2","react-native-gesture-handler": "~2.16.1","react-native-indicator": "^1.2.2","react-native-keychain": "^8.0.0","react-native-maps": "1.14.0","react-native-material-menu": "^2.0.0","react-native-modern-datepicker": "^1.0.0-beta.91","react-native-paper": "^4.12.1","react-native-permissions": "^3.8.4","react-native-popable": "^0.4.3","react-native-popup-menu": "^0.15.12","react-native-qrcode-scanner": "^1.5.5","react-native-radio-buttons-group": "^3.0.3","react-native-reanimated": "~3.10.1","react-native-redash": "^16.3.0","react-native-root-siblings": "^4.1.1","react-native-root-toast": "^3.4.0","react-native-safe-area-context": "4.10.1","react-native-screens": "3.31.1","react-native-svg": "15.2.0","react-native-walkthrough-tooltip": "^1.3.1","react-native-web": "~0.19.10","react-navigation": "^4.4.4","recharts": "^2.1.9","rn-tooltip": "^3.0.1","safe-json-stringify": "^1.2.0","socket.io-client": "^2.0.4","victory-native": "^36.5.0"  },"devDependencies": {"@babel/core": "^7.24.0","@types/crypto-js": "^4.1.1","@types/react": "~18.2.79","@types/react-native": "~0.67.6","@types/react-native-vector-icons": "^6.4.10","@types/socket.io-client": "^3.0.0","react-native-vector-icons": "^9.2.0","typescript": "~5.3.3"  },"resolutions": {"@types/react": "~17.0.21","@types/react-native": "~0.64.12","crypto-js": "3.1.9-1","**/crypto-js": "3.1.9-1"  },"private": true,"rnpm": {"assets": ["./assests/fonts/"    ]  }}

Please provide me solution.

Also I unstalled one by one package to see what is problem but not getting solution

React Native Expo Azure Authentication Custom Redirect URI not Working on Android Expo Go App

$
0
0

The custom redirect URI works fine on iPhone Expo Go, but on Android Expo Go, it gets stuck after entering credentials and clicking the Microsoft sign-in button. Even though I'm using the sameredirect URI, it's not working on Android. I'm wondering if there's a specific way to add custom URIs in my Expo Go app that I'm missing.

This is my sample Microsoft Login.

import React, { useEffect, useState } from 'react'import { StyleSheet, View } from 'react-native'import * as WebBrowser from 'expo-web-browser'import * as AuthSession from "expo-auth-session"import LoginPage from './Login'import LandingPage from './LandingPage'import { Platform } from 'react-native'const tenetID = 'TENENTID'const clientID ='CLIENTID'WebBrowser.maybeCompleteAuthSession()export default function OfficeSignIn(props: any) {  const { navigation } = props  const [discovery, $discovery]: any = useState({})  const [authRequest, $authRequest]: any = useState({})  const [authorizeResult, $authorizeResult]: any = useState({})  const scopes = ['openid', 'profile', 'email', 'offline_access']   const domain = `https://login.microsoftonline.com/${tenetID}/v2.0`  const redirectUrl = 'myapp://redirect';   useEffect(() => {    const getSession = async () => {      const d = await AuthSession.fetchDiscoveryAsync(domain);      console.log("Discovery fetched:", d);      const authRequestOptions: AuthSession.AuthRequestConfig = {        prompt: AuthSession.Prompt.Login,        responseType: AuthSession.ResponseType.Code,        scopes: scopes,        usePKCE: true,        clientId: clientID,        redirectUri: redirectUrl,      }      const authRequest = new AuthSession.AuthRequest(authRequestOptions)      $authRequest(authRequest)      $discovery(d)    }    getSession()  }, [])  useEffect(() => {    console.log("Checking for authorization result...");    const getCodeExchange = async () => {      const tokenResult = await AuthSession.exchangeCodeAsync(        {            code: authorizeResult.params.code,            clientId: clientID,            redirectUri:redirectUrl,            extraParams: {              code_verifier: authRequest.codeVerifier || "",            },          },          discovery      )      const { accessToken, refreshToken, issuedAt, expiresIn } = tokenResult      const response = await fetch(`https://graph.microsoft.com/oidc/userinfo`, {        headers: {          Authorization: `Bearer ${accessToken}`,        },      })      const responseJson = await response.json()      console.log('respons',responseJson);      return navigation.navigate('CategoryListing')    }    if(authorizeResult && authorizeResult.type == 'error') {      console.error('Error:', authorizeResult);    }    if(authorizeResult && authorizeResult.type == 'success') {       getCodeExchange()    }  }, [authorizeResult, authRequest])  return (<View style={styles.container}>      {authRequest && discovery ? (<View >          {authorizeResult.type === 'success' ? (<LandingPage />          ) : (<LoginPage              handleLogin={async () => {                const authorizeResult = await authRequest.promptAsync(discovery);                $authorizeResult(authorizeResult);                console.log("Authorize Result:", authorizeResult);              }}            />          )}</View>      ) : (<></>      )}</View>  );}const styles = StyleSheet.create({  container: {    justifyContent: 'center',    alignItems: 'center',    flex: 1,  },})

This is my app.json

{"expo": {"name": "myapp","slug": "myapp","version": "1.0.0","orientation": "portrait","icon": "./assets/icon.png","userInterfaceStyle": "light","splash": {"image": "./assets/splash.png","resizeMode": "contain","backgroundColor": "#ffffff"},"assetBundlePatterns": \["\*\*/\*"\],"ios": {"supportsTablet": true},"android": {"adaptiveIcon": {"foregroundImage": "./assets/adaptive-icon.png","backgroundColor": "#ffffff"}},"web": {"favicon": "./assets/favicon.png"},"scheme":"myapp"}}

Is there are any additional configurations needed in your app.json file for Android compatibility of Expo Go App. Additionally, exploring alternative methods for handling custom URIs in Expo Go, such as deep linking or universal linking, could potentially provide a solution for the issue I'm encountering.

'gradlew.bat' is not recognized as an internal or external command React Native 0.72.7


How to create Android instant app in React Native?

$
0
0

It seems like there isn't any examples, tutorials or guides on the internet for creating Android instant app with react native.

I have an existing react native app and I want to create an Android instant app. The existing app that was created in react native resides in the directory app, and the instant app I created natively resides in the directory instantapp. I can run this instantapp as an instant app in Android Studio, and all it does is to show a text "Hello instant app" on a blank screen.

I can write Android native code to add more ui and features to this instantapp natively, but I would like to do that in react native and using javascript instead of writing native Android code. How can I do that?

How to set default dark text color in React Native without modifying AppTheme or creating a Text wrapper

$
0
0

In my React Native project, for Android, I'd like to set a default dark/light text colors for all Text components. Here are the constraints:

  • I don't want to modify the android/app/src/main/res/style.xml to change the AppTheme parent to Light or Dark from DayNight.
  • I want to avoid to create a custom wrapper component for Text.
  • I'd prefer not to define the color style for every single Text component in my project.

Is there a way to achieve this default light/dark text color behavior in React Native while adhering to these limitations?

I tried manually finding all Text components to set a default color, but that's risky because it would require changing a lot of code at once. Ideally, I'd like a solution that allows me to define a default dark color based on the theme. I was hoping to use the useColorScheme hook and somehow determine the color values from the root of the project to affect the entire application dynamically. While I currently want a light theme, I also need flexibility to switch to DayNight mode and adjust colors accordingly.

How to make WearOS Android App receive message from react-native app native module?

$
0
0

I am trying to use the MessageClient Api https://developers.google.com/android/reference/com/google/android/gms/wearable/MessageClient to send messages between a WearOS Android app and a react-native app using a native module (https://github.com/claired4l/react-native-wear-connectivity/tree/fix/message-client-send-message-interface).

Both apps have the same application ID and the devices are correctly paired.

The communication works perfectly between two android Apps or between two react-native apps. However a hybrid setup of Android and react-native app opposes a heavy resistance. The listener simply never receives any update (no better behaviour using a background service implementing the WearableListenerService).

The code behind sendMessage and onMessageReceived being unknown I am running out of ideas of how to make this work. Has anyone ever encountered this issue and solved it?

Error: ENOENT: /data/user/0/com.notaedeo/databases/dbnotas.db: open failed: EACCES (Permission denied), open "path", in android 10(api 29)

$
0
0

in my app made in react native happen this error:

Error: ENOENT: /data/user/0/com.notaedeo/databases/dbnotas.db: open failed: EACCES (Permission denied), open "path"

This error happen after i copy some files by the app that is being madeI search for the solution and nothing workingand this my androidmanifest.xml:

<manifest><uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"android:maxSdkVersion="28"/><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="28"/><uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" android:maxSdkVersion="28"/>    ...<application android:requestLegacyExternalStorage="true"android:preserveLegacyExternalStorage="true" ... >        ...<activity>             ...</activity></application></manifest> 

Fetch with basic authentication works with Postman but not in Javascript

$
0
0

I would like to access the Windows Device Portal Api (access the Api of a connected Hololens 2 on the same network of the client) but I kept getting a Network Request Failed from Javascript.

The fact is, that request is working well on Postman, but, even when I am stupidly copying the example JavaScript code from Postman, it still doesn't work.

The result on Postman:

{"ComputerName": "HoloLens2-05","Language": "en-US","OsEdition": "Holographic","OsEditionId": 136,"OsVersion": "22621.1272.arm64fre.ni_release_svc_sydney_rel_prod.240403-0940","Platform": "HoloLens 2"}

Here is my setup:

  • React Native 0.73
  • Targeting Android (simulator or device, they both don't work)
  • IDE: VSCode on Windows

What I did:

  1. Copying the code from Postman:
var myHeaders = new Headers();myHeaders.append("Authorization", "Basic base64here");myHeaders.append("Cookie", "CSRF-Token=csrfTokenHere");var raw = "";var requestOptions = {  method: 'GET',  headers: myHeaders,  body: raw,  redirect: 'follow'};fetch("https://hololensnetworkip/api/os/info", requestOptions)  .then(response => response.text())  .then(result => console.log(result))  .catch(error => console.log('error', error));
  1. Set the AndroidManifest in android/src/main:
<uses-permission android:name="android.permission.INTERNET" /><application    android:usesCleartextTraffic="true">
  1. Trying the Windows Device Portal suggestion of applying an "auto-" prefix on the login (https://learn.microsoft.com/en-us/windows/uwp/debug-test-perf/device-portal#csrf-protection-and-scripting):enter image description here

I know the Windows Device Portal facing issues with not valid certificate status, but why is it working on Postman ? Or why is it working with a call from .Net client ?

Thanks anyway for your hints, I'll keep searching on my side.

Viewing all 29495 articles
Browse latest View live


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