React-Native: Trying to use custom XML into AndroidManifest.xml - android

I'm creating an Android app in React-Native, and I have a problem with a fetch with an API for the signup. So, I tried creating a file in android/app/src/main/assets/xml
react_native_config.xml
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="false">localhost</domain>
<domain includeSubdomains="false">10.0.2.2</domain>
<domain includeSubdomains="false">10.0.3.2</domain>
<domain includeSubdomains="false">MyDomain</domain>
</domain-config>
</network-security-config>
And I add it in AndroidManifest.xml
<application
android:name=".MainApplication"
android:label="#string/app_name"
android:icon="#mipmap/ic_launcher"
android:roundIcon="#mipmap/ic_launcher_round"
android:allowBackup="false"
android:theme="#style/AppTheme"
android:networkSecurityConfig="#xml/react_native_config"> // THERE
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
android:windowSoftInputMode="adjustResize">
<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>
But when I compile the app I receive this error:
android/app/build/intermediates/merged_manifests/debug/AndroidManifest.xml:24: AAPT: error: resource xml/react_native_config not found
Do you know How can I solve?

To use fetch API in react native you don't need to add XML file.Just Enable Internet permission like this
<manifest>
...
<uses-permission android:name="android.permission.INTERNET" />
<application ...
</manifest>
and use fetch API as-
GET-
function getMoviesFromApiAsync() {
return fetch(url)
.then((response) => response.json())
.then((responseJson) => {
return responseJson;
})
.catch((error) => {
console.error(error);
});
}
POST-
fetch(url, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
}),
}).then((response) => response.json())
.then((responseJson) => {
return responseJson;
})
.catch((error) => {
console.error(error);
});

Related

Disabling "New Tag collected" message on android

As a normal behaviour, Android shows up a "New Tag collected" message when it reads an NFC tag.
However, I do not want this message to appear when I use my app.
I searched for many solutions on the internet, but with no success.
Any ideas about what I can do?
I will share the function I use to get the tag's ID and my AndroidManifest.xml.
const readNFC = async (): Promise<string | undefined> => {
return new Promise(async (resolve, reject) => {
try {
await NfcManager.requestTechnology(NfcTech.NdefFormatable);
const tag = await NfcManager.getTag();
if (Platform.OS === 'ios') {
await NfcManager.setAlertMessageIOS('TAG detect');
}
NfcManager.cancelTechnologyRequest();
if (tag) {
resolve(tag.id);
}
} catch (er) {
reject('An error has occurred.');
}
});
};
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.newronda">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.NFC" />
<uses-permission android:name="android.permission.CAMERA" />
<application
android:name=".MainApplication"
android:label="#string/app_name"
android:icon="#mipmap/ic_launcher"
android:roundIcon="#mipmap/ic_launcher_round"
android:allowBackup="false"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode"
android:launchMode="singleTask"
android:windowSoftInputMode="adjustResize"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="application/vnd.hello.sample.nfcmanager" />
</intent-filter>
</activity>
</application>
</manifest>

React native, registerHeadlessTask does not call my function

The notification appears on the top (The app is running....) but the function is not getting called. I can't find any error. Anyone knows what might be causing the issue?
I create a package and add it like this packages.add(new BackgroundPackage());
This is my index.js
import { AppRegistry } from 'react-native';
import App from './App';
import { name as appName } from './app.json';
const MyHeadlessTask = async () => {
console.log('Should be headless');//<--this is not getting called
};
AppRegistry.registerHeadlessTask('Background', () => MyHeadlessTask);//<<--this
AppRegistry.registerComponent(appName, () => App);
This is my AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.printerandroid">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<application
android:name=".MainApplication"
android:label="#string/app_name"
android:icon="#mipmap/ic_launcher"
android:roundIcon="#mipmap/ic_launcher_round"
android:allowBackup="false"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode"
android:launchMode="singleTask"
android:windowSoftInputMode="adjustResize"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name="com.printerandroid.BackgroundService" >
</service>
<service android:name="com.printerandroid.BackgroundEventService"/>
<receiver
android:name="com.printerandroid.BootUpReceiver"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
</application>
</manifest>
You must register component like this
function MyHeadlessTask({ isHeadless }) {
if (isHeadless) {
// App has been launched in the background by iOS, ignore
return null;
}
return <App />;
}
function App() {
// Your application
}
AppRegistry.registerComponent('app', () => MyHeadlessTask);
Also, don't forget to make the changes as mentioned here.

Ionic 5 Capacitor 3 sqlite.requestPermission() not showing dialog box

I am trying to use CapacitorSQLite with capacitor 3. When I call SQLite.requestPermission() its not showing any dialog box asking for permission and the code seems to be never returning from that call as I can see logs before that call but not after.
code look like
async init(): Promise<void> {
if (this.platform.is('android')) {
try {
const sqlite:any = CapacitorSQLite;
console.log('setting permission handler');
this.handlerPermissions = sqlite.addListener(
'androidPermissionsRequest', async (data:any) => {
if (data.permissionGranted === 1) {
console.log('Perm granted');
this.setupDatabase();
} else {
console.log("Permission not granted");
}
});
console.log('REQUESTING PERMS');
await sqlite.requestPermissions();
} catch (e) {
console.log('error on perm req',e);
const alert = await this.alertCtrl.create({
header: 'No DB access',
message: e.message,
buttons: ['OK']
});
await alert.present();
}
} else {
console.log('not running on android platform');
const alert = await this.alertCtrl.create({
header: 'Not android',
message: this.platform.platforms()[0],
buttons: ['OK']
});
await alert.present();
this.setupDatabase();
}
}
can see the following logs
'setting permission handler'
'REQUESTING PERMS'
but am also expecting one of the following as well
'Perm granted'
"Permission not granted"
'error on perm req'
here's AndroidManifest.xml
<?xml version='1.0' encoding='utf-8'?>
<manifest package="io.ionic.starter" xmlns:android="http://schemas.android.com/apk/res/android">
<application android:allowBackup="true" android:icon="#mipmap/ic_launcher" android:label="#string/app_name" android:roundIcon="#mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="#style/AppTheme" android:usesCleartextTraffic="true">
<activity android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode" android:label="#string/title_activity_main" android:launchMode="singleTask" android:name="io.ionic.starter.MainActivity" android:theme="#style/AppTheme.NoActionBarLaunch">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider android:authorities="${applicationId}.fileprovider" android:exported="false" android:grantUriPermissions="true" android:name="androidx.core.content.FileProvider">
<meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="#xml/file_paths" />
</provider>
</application>
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
Am I missing anything? Capacitor doc says plug will have user-permission that need to be added but couldn't see any for sqlite.
Thanks a lot
You do not need specific permissions for this plugin. Check the documentation for examples of how to use this plugin in Angular, React or Vue depends on what you need.

Unhandled Exception: Bad state: Insecure HTTP is not allowed by platform - usesClearTextTraffic not worked

I'm trying to run a basic API call in Flutter using PHP and a MySQL database, but I'm receiving an error which reads:
E/flutter ( 7461): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: Bad state: Insecure HTTP is not allowed by platform
What I've Tried
I have tried the solution proposed here: Bad state: Insecure HTTP is not allowed by platform:
and here: https://www.programmersought.com/article/49295775092/
Sample Code
home.dart
import 'package:flutter/material.dart';
import 'package:flutter_crud/env.sample.dart';
import 'dart:convert';
import 'package:http/http.dart';
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
void getData() async{
Response response = await get(Uri.parse("${Env.URL_PREFIX}/list"));
Map data = jsonDecode(response.body);
print(data);
}
#override
void initState() {
super.initState();
getData();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter CRUD API'),
centerTitle: true,
),
body:Center(
child: Text('Hello'),
)
);
}
}
The URI prefix comes from env.sample.dart:
class Env{
static String URL_PREFIX = "http://[my.IP.address.here]/flutter_crud";
}
In the debug/AndroidManifest.xml:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="jacobcollinsdev.flutter_crud">
<uses-permission android:name="android.permission.INTERNET"/>
<application android:usesCleartextTraffic="true"/>
</manifest>
In the main/AndroidManifest.xml file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="jacobcollinsdev.flutter_crud">
<uses-permission android:name="android.permission.INTERNET" /> <------- I added this line
<application
android:label="flutter_crud"
android:icon="#mipmap/ic_launcher"
android:usesCleartextTraffic="true"
android:networkSecurityConfig="#xml/network_security_config"> <------ I added this line
<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:theme="#style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<meta-data
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="#style/NormalTheme"
/>
<meta-data
android:name="io.flutter.embedding.android.SplashScreenDrawable"
android:resource="#drawable/launch_background"
/>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<meta-data
android:name="flutterEmbedding"
android:value="2" />
<uses-library
android:name="org.apache.http.legacy"
android:required="false" /> <-------I added this code block
</application>
</manifest>
Finally, I have also created this file in android/app/main/res/xml/network_security_config.xml:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config clearTextTrafficPermitted="true">
<trust-anchors>
<certificates src="system" />
</trust-anchors>
</base-config>
</network-security-config>
So far nothing has resolved the error and I'm all out of ideas. Any feedback would be grand!
simply these lines in
android/app/src/main/AndroidManifest.xml
1). Add <uses-permission android:name="android.permission.INTERNET" />
before application tag
2). Add android:usesCleartextTraffic="true" inside application tag
You should try loading your images from a SSL certificate domain. That is using HTTPS rather than HTTP.
So for your case, replace "http://[my.IP.address.here]/flutter_crud" to use https://.
remove This
class Env{
static String URL_PREFIX = "http://[my.IP.address.here]/flutter_crud";
}
add this
class Env{
static String URL_PREFIX = "https://[my.IP.address.here]/flutter_crud";
}
use https://
instead of http://

Ionic 5 - Angular: Access to XMLHttpRequest has been blocked by CORS policy

I am trying to call an api in ionic. i get following error in my console.
Access to XMLHttpRequest at
'https://apiresource.com/appservices/get_services' from origin
'http://localhost:8100' has been blocked by CORS policy: No
'Access-Control-Allow-Origin' header is present on the requested
resource.
Below is my code for API call
services.page.ts
import { Component, OnInit } from '#angular/core';
import {HttpClient, HttpClientModule} from '#angular/common/http';
import {NavController} from '#ionic/angular';
#Component({
selector: 'app-services',
templateUrl: './services.page.html',
styleUrls: ['./services.page.scss'],
})
export class ServicesPage implements OnInit {
services: any;
constructor(private http: HttpClient, private navctrl: NavController) {
}
ngOnInit() {
this.http.get('https://apiresource.com/appservices/get_services').subscribe(data => {
console.log('my data: ', data);
alert(JSON.stringify(data));
});
}
}
network_security_config.xml
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true">
<trust-anchors>
<certificates src="system" />
</trust-anchors>
</base-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">apiresource.com</domain>
</domain-config>
</network-security-config>
Config.xml
<platform name="android">
<edit-config file="app/src/main/AndroidManifest.xml" mode="merge" target="/manifest/application" xmlns:android="http://schemas.android.com/apk/res/android">
<application android:usesCleartextTraffic="true" />
<application android:networkSecurityConfig="#xml/network_security_config" />
</edit-config>
....................
I have tried on different solutions found from Google and above is all that i have in my code .
Please help

Categories

Resources