Having trouble reading a file in Android 11 due to a Capacitor Filesystem error

I attempted to access a file within my emulator using the readFile function of Capacitor filesystem. The file I am trying to manipulate is located in the Download folder of the emulator, and upon execution, the function returned the following error:

Error: File does not exist

Furthermore, I also tried utilizing the copy function to move this file to a directory where I could work with it. However, this action resulted in the following error:

Error: The source object does not exist

After performing permission tests within the application, I received a status of granted.

Despite my efforts to resolve these issues by researching online and tweaking the parameters of Directory in my filesystem service functions, all attempts still led to the same errors. It's worth noting that accessing the filesystem was successful on Android 10 with identical parameters.

All tests were conducted on an emulator running Pixel 4 with Android 11 (API30).

In the android.xml file, under the application tag, I included

android:requestLegacyExternalStorage="true"
, along with the following user-permissions:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />

homePage.ts

with copy

// file_dir_path = file:///storage/emulated/0/Download/
// file_name = file.kml
// path = 'MyApp/project' + this.projectId + '/temp'
return this.filesystem.copyFileToManegeDirectory(file_dir_path + file_name, path + '/test').then(fileAs64 => {
    console.log(fileAs64).
});

with read

// file_dir_path = file:///storage/emulated/0/Download/
// file_name = file.kml
return readFile(file_dir_path + file_name).then(fileAs64 => {
    console.log(fileAs64);
});

FilesystemService

/** Copy Files */
// fileToCopy = file:///storage/emulated/0/Download/file.kml
copyFileToManegeDirectory(fileToCopy: string, directoryToGo: string): Promise<any> {
    return Filesystem.checkPermissions().then(permission => {
        console.log(permission)
        return Filesystem.copy({
            from: fileToCopy,
            directory: Directory.ExternalStorage,
            to: directoryToGo,
            toDirectory: Directory.External
        }).then(result => {
            console.log(result);
        })
    });
}

/** Read a file and returns a string base 64 */
readFile(path: string): Promise<string> {
    return Filesystem.readFile({
        path: path
    }).then(result => {
        return result.data;
    });
}

I am trying to ascertain the feasibility of accessing files outside of the app’s scoped folder on Android 11. My application necessitates importing files that may reside anywhere on the device as chosen by the user.

Ionic info


   Ionic CLI                     : 6.15.1-testing.0 (C:\Users\Gabriel Vieira\AppData\Roaming\npm\node_modules\@ionic\cli)
   Ionic Framework               : @ionic/angular 
5.6.8
   @angular-devkit/build-angular : 12.0.2
   @angular-devkit/schematics    : 12.0.2
   @angular/cli                  : 12.0.2
   @ionic/angular-toolkit        : 4.0.0

Capacitor:

   Capacitor CLI      : 3.0.0
   @capacitor/android : 3.0.0
   @capacitor/core    : 3.0.0
   @capacitor/ios     : not installed

Utility:

   cordova-res : 0.15.3
   native-run  : 1.4.0

System:

   NodeJS : v14.16.1 (C:\Program Files (x86)\nodejs\node.exe)
   npm    : 6.14.12
   OS     : Windows 10

npx cap doctor

Latest Dependencies:

  @capacitor/cli: 3.0.1
  @capacitor/core: 3.0.1
  @capacitor/android: 3.0.1

Installed Dependencies:

  @capacitor/ios: not installed
  @capacitor/cli: 3.0.0
  @capacitor/android: 3.0.0
  @capacitor/core: 3.0.0

EDIT

Attempts to adjust the target SDK to versions 28 and 29 did not alleviate the error.

According to documentation, adding the tag MANAGE_EXTERNAL_STORAGE is necessary when attempting to access files beyond scoped storage. Despite already having this parameter in my manifest, I remain unable to read external content.

While examining filesystem permissions using both checkPermissions() and requestPermissions(), both functions indicate publicStorage: 'granted'.

Answer №1

Ensure that the correct target is specified in the android/variables.gradle. If it does not work as expected, consider opening an issue on the Capacitor GitHub page.

ext {
    compileSdkVersion = 29
    targetSdkVersion = 29
    ...
}

Avoid using MANAGE_EXTERNAL_STORAGE unless absolutely necessary, as it may complicate deployment to the Google Play Store. Refer to Google's support page for more information. Additionally, make sure to set

android:requestLegacyExternalStorage="true"
in your AndroidManifest file, and include the following user permissions:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Determining the size of a TextView using Robolectric

When I call measure(0, 0) on a TextView, the view adjusts its measured width and height to fit the current font and text size requirements: public class TestTextViewSize extends AndroidTestCase { public void checkWidth() { TextView view = new ...

Declaring TypeScript functions with variable numbers of parameters

Is it possible to define a custom type called OnClick that can accept multiple types as arguments? How can I implement this feature so that I can use parameters of different data types? type OnClick<..> = (..) => void; // example usage: const o ...

The absence of essential DOM types in a TypeScript project is causing issues

Recently, I've been working on setting up a web app in TypeScript but I seem to be missing some essential types that are required. Every time I compile using npm run build, it keeps throwing errors like: Error TS2304: Cannot find name 'HTMLEleme ...

Angular: Utilizing the new HttpClient to map HTTP responses

Within my application, I have a standard API service that communicates with the backend using requests structured like this: post<T>(url: string, jsonObject: object): Observable<T> { return this.http.post<T>(url, JSON.stringify(json ...

PHP Firebase notification is appearing in the notification tray but is not popping up on the screen

Using php, I am implementing push notifications through Firebase for my Android app built in Unity. Currently, the app is successfully receiving notifications and displaying them in the notification tray, but they are not appearing as pop-up notifications ...

Declare, condition, and output all in a single statement

Is there a method to condense the content inside the function below into a single line? I want to avoid declaring check. function Example { const check = this.readByUuidCheck(props) if (check) return this.readByUuid(check) } I am seeking ways to ...

Walking towards the Android activity from the left side, gradually moving to the right

Can anyone tell me the type of Android Activity depicted in the image? It allows you to input configurations and hide them with a swipe gesture. ...

Resolving callback definition issue: Can be assigned to constraint, yet may be instantiated with a distinct subtype. ( TS 2345 )

Seeking insight on the typing issue causing a compiler error in the code snippet below. Any suggestions for maintaining type-safety without resorting to any or as? Avoiding these workarounds is important to me. The challenge lies in the evidence() call, c ...

When I attempt to translate R.string in FragmentPagerAdapter, an unusual number suddenly pops up before me

Struggling to insert a text translation into a FragmentPagerAdapter, I've tried various methods like using return (R.string.Chats) + ""; An unusual occurrence for me is the appearance of a strange number in three tabs. Image: https://i.sst ...

Angular application parametrization

My application consists of an Angular front-end, an app layer, and a DB layer. The architecture can be seen in this image. To serve the JS front-end bits to the client and proxy requests from the client to the app layer, I am using an nginx instance. If I ...

Errors encountered when using TypeScript with destructured variables and props not being recognized

I have a function that returns data. The object is structured with properties such as headerMenu, page, content, and footer. These properties are defined in DataProps interface. When I try to destructure the data object using the line: const { headerMenu, ...

The issue of "ReferenceError: Cannot access '<Entity>' before initialization" occurs when using a OneToMany relationship with TypeORM

There are two main actors involved in this scenario: User and Habit. The relationship between them is defined by a OneToMany connection from User to Habit, and vice versa with a ManyToOne. User Entity import {Entity, PrimaryGeneratedColumn, Column, Creat ...

The type 'Dispatch<SetStateAction<boolean>>' cannot be assigned to type 'boolean'

Currently, I am attempting to transfer a boolean value received from an onChange function to a state variable. let [toggleCheck, setToggleCheck] =useState(false);` <input type="checkbox" id={"layout_toggle"} defaultChecked={toggleCh ...

Angular TypeScript test checking file size with Jasmine

Seeking optimal method for testing File size during input type="file" change event. Currently, my test specification appears as follows: it('attach file with too large size', () => { const file: File = { name: 'filename', ...

Guide on accessing an element from a predicate object in Typescript while using Angular

I'm trying to wrap my head around how to access an element that exists on an object of a specific type but is defined as a type predicate. For example, let's say we have a Team defined as: let team$: Observable<ErrorModel | Team> The res ...

ASP.NET WebService unable to insert values into SQL Server database

As someone who is relatively new to the world of programming, I recently delved into WebService using ASP.NET C# in Microsoft Visual Studio 2017. My next step was incorporating KSoap2 into Android Studio with the intention of inserting user data into an SQ ...

How can I display an ngx spinner after a delay of 1 second?

I am uncertain about the answer I came across on this platform. intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const time = 900; const spinnerLogic = () => { if (this.isRequestServed ...

Unable to call Ionic component function using ref in Vue3

I'm attempting to utilize the closeSlidingItems method of the IonList element in order to automatically close the sliding item after clicking a button that appears from behind once the item is slid to the right. My approach involved referencing IonLi ...

Enhancing external TypeScript modules

Currently, I am delving into the realm of enhancing external modules in TypeScript. I am diligently studying the official documentation and the DefinitelyTyped guides, poring over examples, and so forth. At this point, my goal is to incorporate custom prop ...

Encountering the error message "express.default is not a function" while attempting to start the node server within a container

Whenever I try to start my node server in a remote container, I keep encountering an error stating "express.default is not a function." Can anyone help me figure this out? Here's the content of my main.ts file: import * as express from 'express& ...