FileSystemException: Creation failed, path = '/storage/emulated/0/4k' (OS Error: Permission denied, errno = 13) Flutter - android

I have added every thing required to download files to local storage still I'm getting this error
In Manifest
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_MEDIA_LOCATION"/>
android:requestLegacyExternalStorage="true"
android:hardwareAccelerated="true"
In pubspec.yaml
permission_handler: ^6.1.1
In Build.gradle
compileSdkVersion 30
minSdkVersion 22
targetSdkVersion 30
Future<bool> _requestPermission(Permission permission, Permission permission3,
Permission permission4) async {
print("xxxx IN ");
if (await permission.isGranted) {
print('xxxx ohhh');
return true;
} else {
await permission.request();
.then((value) => () {
print("xxxx value" + value.toString());
if (value == PermissionStatus.granted) {
print("xxxx PERMISSION GRANTED ");
return true;
} else {
print("xxxx PERMISSION DENIED ");
}
})
.whenComplete(() => print('xxxx COMPLETED'))
.onError((error, stackTrace) => () {
print("xxxx onError " + error);
print("xxxx onError " + stackTrace.toString());
})
.catchError((onError) => () {
print('xxxx catchError ' + onError.toString());
});
print("xxxx OUT ");
// var result2 = await permission3.request();
// var result3 = await permission4.request();
}
return false;
}
from this function see what's printed
not getting printed from then()...
Please Please help me out :)

Use android:requestLegacyExternalStorage="true" in the application tag not in <activity> tag:
<application
android:requestLegacyExternalStorage="true" >

what is work for me this
permission_handler: ^8.3.0 // use this version
and in your code
final status = await Permission.storage.request();
var state = await Permission.manageExternalStorage.status;
var state2 = await Permission.storage.status;
if (status.isGranted) {
directory = (await getExternalStorageDirectory())!;
}
if (!state2.isGranted) {
await Permission.storage.request();
}
if (!state.isGranted) {
await Permission.manageExternalStorage.request();
}
if (!await directory!.exists()) {
await directory.create(recursive: true);
}
and in the my permissions
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE">
</uses-permission>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-
permission>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission
android:name="android.permission.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION"/>

Related

react native - crash the app when I call scan function with react-native-ble-manager

I used for the first time react-native-ble-manager.
The app has all the permissions, however when I run the BleManager.scan() the app is closing without any error or logs.
I know the code is a little ugly but it's just for testing, the first second I run the bluetooth manager start and after 5 seconds I run the scan.
But the crash happen immediately after 5 seconds.
Any idea why?
import BleManager from 'react-native-ble-manager';
const BleManagerModule = NativeModules.BleManager;
const bleManagerEmitter = new NativeEventEmitter(BleManagerModule);
const handleDiscoverPeripheral = (peripheral) => {
console.log('Got ble peripheral', peripheral);
if (!peripheral.name) {
peripheral.name = 'NO NAME';
}
peripherals.set(peripheral.id, peripheral);
setList(Array.from(peripherals.values()));
}
const handleStopScan = () => {
console.log('Scan is stopped');
}
let interval;
let gImageShow = true;
let gTime = 0;
BleManager.enableBluetooth()
.then(() => {
// Success code
console.log("The bluetooth is already enabled or the user confirm");
})
.catch((error) => {
// Failure code
console.log("The user refuse to enable bluetooth");
});
function App(props) {
const [shouldShow, setShouldShow] = useState(gImageShow);
useEffect(() => {
interval = setInterval(() => {
if (gTime == 1)
{
BleManager.start({showAlert: true});
bleManagerEmitter.addListener('BleManagerDiscoverPeripheral', handleDiscoverPeripheral);
bleManagerEmitter.addListener('BleManagerStopScan', handleStopScan );
PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION).then((result) => {
if (result) {
console.log("Permission is OK");
}
});
}
if (gTime == 5)
{
BleManager.scan([], 10, true);
}
gImageShow = !gImageShow;
setShouldShow(gImageShow);
gTime = gTime + 1;
},1000);
return () => clearInterval(interval);
}, []);
useEffect(() => {
});
the manifest is like:
xmlns:tools="http://schemas.android.com/tools"
package="com.diagnostic_ble">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" android:maxSdkVersion="28"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" tools:targetApi="Q"/>
<!-- Needed only if your app looks for Bluetooth devices. -->
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<uses-permission-sdk-23 android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
The problem has been solved. The new android 12 (I think from this one), needs a different permission that it hasn't been updated in react-native-ble-manager webpage.
In the manifest you need to add
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
Also, In the app.js you need to call once requestPermissions();
that it can be like
const requestPermissions = async () => {
if (Platform.OS === 'android') {
const apiLevel = await DeviceInfo.getApiLevel();
if (apiLevel < 31) {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
title: 'Location Permission',
message: 'Bluetooth Low Energy requires Location',
buttonNeutral: 'Ask Later',
buttonNegative: 'Cancel',
buttonPositive: 'OK',
},
);
} else {
const result = await requestMultiple([
PERMISSIONS.ANDROID.BLUETOOTH_SCAN,
PERMISSIONS.ANDROID.BLUETOOTH_CONNECT,
PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION,
]);
const isGranted =
result['android.permission.BLUETOOTH_CONNECT'] ===
PermissionsAndroid.RESULTS.GRANTED &&
result['android.permission.BLUETOOTH_SCAN'] ===
PermissionsAndroid.RESULTS.GRANTED &&
result['android.permission.ACCESS_FINE_LOCATION'] ===
PermissionsAndroid.RESULTS.GRANTED;
}
} else {
}
};

React native image picker camera crashes

I am using image picker in react native but an error occurs:
file:///storage/emulated exposed beyond app through clipdata.item
On ios, the camera opens normally. and in android i can pick an image from gallery normally.
My code:
const selectFile = (itemI,inputValue) => {
let options = {
title: 'Select Image',
maxWidth:800,
maxHeight:800,
quality:0.2,
storageOptions: {
skipBackup: true,
path: 'images',
},
includeBase64: true,
saveToPhotos:true
};
ImagePicker.showImagePicker(options, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else if (response.customButton) {
console.log(
'User tapped custom button: ',
response.customButton
);
alert(response.customButton);
} else {
//let source = response;
// You can also display the image using data:
let source = {
uri: 'data:image/jpeg;base64,' + response.data
};
filePath[itemI]=source;
addItemCustom(" ");
}
});
};
I tried to add:
<uses-feature android:name="android.hardware.camera.any" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<application
....
android:requestLegacyExternalStorage="true"
...>
but the error is the same.

path provider flutter download file

I want to download the file in my app and I used Dio, path_provider, permission_handler
so I should write something in the android manifest for android and info for ios.
and I did it.
but it did not work and I've get this error when I clicked on the download button:
I/flutter (11919): Directory: '/storage/emulated/0/Android/data/com.example.podkadeh/files'
I/flutter (11919): FileSystemException: Cannot open file, path = '/storage/emulated/0/podkadeh/Image/image.jpg' (OS Error: Permission denied, errno = 13)
I/flutter (11919): Problem Downloading File
this OS Error: Permission denied, errno = 13
I wrote this lines in manifest:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_MEDIA_LOCATION"/>
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"
tools:ignore="ScopedStorage"/>
<uses-permission android:name="android.permission"
and wrote this in Application:
android:requestLegacyExternalStorage="true"
but still, it's not working well and I can't download it
here is my code for download file:
class DownloadImage extends StatefulWidget {
const DownloadImage (
{Key? key,})
: super(key: key);
#override
_DownloadImage State createState() => _DownloadImage State();
}
class _DownloadImageState extends State<DownloadImage > {
Future<bool> saveImageUrl(String url, String fileName) async {
Directory? directory;
try {
if (Platform.isAndroid) {
if (await _requestPermission(Permission.storage)) {
directory = await getExternalStorageDirectory();
String newPath = "";
print(directory);
List<String> paths = directory!.path.split("/");
for (int x = 1; x < paths.length; x++) {
String folder = paths[x];
if (folder != "Android") {
newPath += "/" + folder;
} else {
break;
}
}
newPath = newPath + "/podkadeh" + "/Image";
directory = Directory(newPath);
} else {
return false;
}
} else {
if (await _requestPermission(Permission.photos)) {
directory = await getTemporaryDirectory();
} else {
return false;
}
}
File saveFile = File(directory.path + "/$fileName");
if (!await directory.exists()) {
await directory.create(recursive: true);
}
if (await directory.exists()) {
await dio.download(url, saveFile.path,
onReceiveProgress: (value1, value2) {
setState(() {
progress = value1 / value2;
});
});
if (Platform.isIOS) {
await ImageGallerySaver.saveFile(saveFile.path,
isReturnPathOfIOS: true);
}
return true;
}
return false;
} catch (e) {
print(e);
return false;
}
}
Future<bool> _requestPermission(Permission permission) async {
if (await permission.isGranted) {
return true;
} else {
var result = await permission.request();
if (result == PermissionStatus.granted) {
return true;
}
}
return false;
}
downloadFile() async {
setState(() {
loading = true;
progress = 0;
});
bool downloadedImage = await saveImageUrl(
"https://test.podkadeh.ir/image-cache/Ep-61c9c0152ab37f246dd35a65-500.jpg",
"image.jpg");
if (downloadedImage) {
print("File Downloaded");
} else {
print("Problem Downloading File");
}
setState(() {
loading = false;
});
}
#override
Widget build(BuildContext context) {
return (progress != 0 && progress != 100)
? CircularProgressIndicator(
backgroundColor: loading ? Colors.amber : Colors.black,
valueColor:
AlwaysStoppedAnimation(loading ? Colors.blue : Colors.pink),
strokeWidth: progress,
value: progress,
)
: IconButton(
icon: SvgPicture.asset(MyIcons.frame, color: MyColors.black,height: 20,width: 20,),
onPressed: downloadFile,
padding: const EdgeInsets.all(10),
);
}
}
by the way I use compileSdkVersion 31 and I use this in gradle.properties :
android.useAndroidX=true
android.enableJetifier=true
I solved this problem with the following solution:
instead of just asking for Permission.storage i added two more permission requests Permission.accessMediaLocation , Permission.manageExternalStorage in order to support all versions of Android.
try {
if (Platform.isAndroid) {
if (await _requestPermission(Permission.storage) &&
await _requestPermission(Permission.accessMediaLocation) &&
await _requestPermission(Permission.manageExternalStorage)) {
directory = await getExternalStorageDirectory();
String newPath = "";
print(directory);
.......
the result was:
Performing hot restart...
Syncing files to device Android SDK built for x86...
Restarted application in 2,177ms.
I/flutter ( 3712): Directory: '/storage/emulated/0/Android/data/com.example.untitled/files'
I/flutter ( 3712): File Downloaded

React Native android permission is not showing

The react native android permission pop-up is not showing, I cannot download a file. It works on a simulator but not on a real phone.
Here is my permission function :
const requestAndroidStoragePermission = async () => {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
{
title: "File access",
message:
"The app needs files access to download your performance.",
}
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
this.setState({ storagePermission: true });
this.setState({ showExportModal: true });
} else {
console.log("Files permission denied");
}
} catch (err) {
console.warn(err);
}
};
I have the permission on my AndroidManifest.xml :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:targetSdkVersion="29" />
Someone have an idea ?

how to use storage Permission in flutter?

I want to create flutter apps for downloading files from internet now I want to Check the storage permissions like the code below but I get the error: The method 'PermissionHandler' isn't defined what should I do?
Future<bool> _requestPermissions() async {
var permission = await PermissionHandler().checkPermissionStatus(PermissionGroup.storage);
if (permission != PermissionStatus.granted) {
await PermissionHandler().requestPermissions([PermissionGroup.storage]);
permission = await PermissionHandler().checkPermissionStatus(PermissionGroup.storage);
}
return permission == PermissionStatus.granted;
}
note:i have added the following permissions on AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Categories

Resources