0

Can anyone explain or provide a link that explains how the getFilesDir() works. I know that it returns a path on the internal storage of the specific package name. But i wanted to know how does it returns the path? Is the folder directly created when the app is installed or is it created when the method is first called? and other similar questions.

GParekar
  • 1,209
  • 1
  • 8
  • 15

1 Answers1

1

Here is the stock implementation of Context, known as ContextImpl.

The implementation of getFilesDir(), as of Android 6.0, is:

@Override
public File getFilesDir() {
    synchronized (mSync) {
        if (mFilesDir == null) {
            mFilesDir = new File(getDataDirFile(), "files");
        }
        return createFilesDirLocked(mFilesDir);
    }
}

createFilesDirLocked() goes through some complicated gyrations to create the directory, if needed:

// Common-path handling of app data dir creation
private static File createFilesDirLocked(File file) {
    if (!file.exists()) {
        if (!file.mkdirs()) {
            if (file.exists()) {
                // spurious failure; probably racing with another process for this app
                return file;
            }
            Log.w(TAG, "Unable to create files subdir " + file.getPath());
            return null;
        }
        FileUtils.setPermissions(
                file.getPath(),
                FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
                -1, -1);
    }
    return file;
}

Is the folder directly created when the app is installed or is it created when the method is first called?

AFAIK, it is created when the method is called. You can test this yourself: write an app, then install it on an emulator but don't run it. Use the Android Device Monitor or adb shell to see if the directory exists.

and other similar questions

You are welcome to peruse the Java code for Android's framework classes at your leisure.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491