Skip to content

Conversation

@bparrishMines
Copy link
Contributor

@bparrishMines bparrishMines commented Aug 7, 2025

https://developer.android.com/guide/components/processes-and-threads

Pre-Review Checklist

If you need help, consider asking for advice on the #hackers-new channel on Discord.

Note: The Flutter team is currently trialing the use of Gemini Code Assist for GitHub. Comments from the gemini-code-assist bot should not be taken as authoritative feedback from the Flutter team. If you find its comments useful you can update your code accordingly, but if you are unsure or disagree with the feedback, please feel free to wait for a Flutter team member's review for guidance on which automated comments should be addressed.

Footnotes

  1. Regular contributors who have demonstrated familiarity with the repository guidelines only need to comment if the PR is not auto-exempted by repo tooling. 2 3

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request refactors the Android implementation of path_provider to use jnigen and JNI instead of Pigeon for platform communication. This is a significant architectural change. While the implementation looks mostly correct, there are several potential memory leaks due to unreleased JNI objects. I've added specific comments on how to fix them.

A major concern is the removal of all existing tests without adding new ones to cover the new JNI-based implementation. The repository's style guide states that "Code should be tested"[^1]. Given the low-level nature of JNI interop, having a solid test suite is critical to ensure correctness and prevent regressions. Please add tests for the new implementation.

Comment on lines 61 to 66
final JArray<File?>? files = _applicationContext.getExternalCacheDirs();
if (files != null) {
return _toStringList(files);
}

return null;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The JArray<File?> object returned by getExternalCacheDirs() is a JNI object that needs to be released to avoid a memory leak. The current implementation does not release it.

    final JArray<File?>? files = _applicationContext.getExternalCacheDirs();
    if (files == null) {
      return null;
    }
    try {
      return _toStringList(files);
    } finally {
      files.release();
    }

Comment on lines 73 to 80
final JArray<File?>? files = _applicationContext.getExternalFilesDirs(
type != null ? _toNativeStorageDirectory(type) : null,
);
if (files != null) {
return _toStringList(files);
}

return null;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The JArray<File?> object returned by getExternalFilesDirs() is a JNI object that needs to be released to avoid a memory leak. The current implementation does not release it.

    final JArray<File?>? files = _applicationContext.getExternalFilesDirs(
      type != null ? _toNativeStorageDirectory(type) : null,
    );
    if (files == null) {
      return null;
    }
    try {
      return _toStringList(files);
    } finally {
      files.release();
    }

Comment on lines 122 to 134
final Iterator<File?> filesIterator = files.iterator;
while (filesIterator.moveNext()) {
final File? file = filesIterator.current;
if (file != null) {
final String? path =
file.getAbsolutePath()?.toDartString(releaseOriginal: true);
if (path != null) {
paths.add(path);
}

file.release();
}
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

There are two potential memory leaks here:

  1. The iterator returned by files.iterator is a JIterator, which is a JNI object that must be released.
  2. If file.getAbsolutePath() or toDartString() throws an exception, file.release() will not be called.

Both can be fixed by using try...finally blocks to ensure release() is always called.

  final Iterator<File?> filesIterator = files.iterator;
  try {
    while (filesIterator.moveNext()) {
      final File? file = filesIterator.current;
      if (file != null) {
        try {
          final String? path =
              file.getAbsolutePath()?.toDartString(releaseOriginal: true);
          if (path != null) {
            paths.add(path);
          }
        } finally {
          file.release();
        }
      }
    }
  } finally {
    (filesIterator as JObject).release();
  }

Comment on lines 40 to 43
final File? file = _applicationContext.getCacheDir();
final String? path = file?.getPath()?.toDartString(releaseOriginal: true);
file?.release();
return path;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

To ensure that the File object is always released, even if getPath() or toDartString() throws an exception, it's safer to use a try...finally block.

    final File? file = _applicationContext.getCacheDir();
    if (file == null) {
      return null;
    }
    try {
      return file.getPath()?.toDartString(releaseOriginal: true);
    } finally {
      file.release();
    }

Comment on lines 48 to 54
final File? dir = _applicationContext.getExternalFilesDir(null);
if (dir != null) {
final String? path =
dir.getAbsolutePath()?.toDartString(releaseOriginal: true);
dir.release();
return path;
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

To ensure that the File object (dir) is always released, even if an exception occurs, it's best practice to use a try...finally block.

    final File? dir = _applicationContext.getExternalFilesDir(null);
    if (dir == null) {
      return null;
    }
    try {
      return dir.getAbsolutePath()?.toDartString(releaseOriginal: true);
    } finally {
      dir.release();
    }

@bparrishMines bparrishMines changed the title Pp jnigen [path_provider_android] Changes internal implementation to use JNI Aug 7, 2025
@bparrishMines
Copy link
Contributor Author

cc @stuartmorgan-g for early review

@bparrishMines
Copy link
Contributor Author

@HosseinYousefi Have you seen this error on Windows for JNI:

Changed 65 dependencies!
10 packages have newer versions incompatible with dependency constraints.
Try `flutter pub outdated` for more information.
Building Windows application...                                 
Nuget.exe not found, trying to download or use cached version.
CMake Error at C:/Program Files (x86)/Microsoft Visual Studio/2019/Community/Common7/IDE/CommonExtensions/Microsoft/CMake/CMake/share/cmake-3.19/Modules/FindPackageHandleStandardArgs.cmake:218 (message):
  Could NOT find JNI (missing: JAVA_AWT_LIBRARY JAVA_JVM_LIBRARY
  JAVA_INCLUDE_PATH JAVA_INCLUDE_PATH2 JAVA_AWT_INCLUDE_PATH)
Call Stack (most recent call first):
  C:/Program Files (x86)/Microsoft Visual Studio/2019/Community/Common7/IDE/CommonExtensions/Microsoft/CMake/CMake/share/cmake-3.19/Modules/FindPackageHandleStandardArgs.cmake:582 (_FPHSA_FAILURE_MESSAGE)
  C:/Program Files (x86)/Microsoft Visual Studio/2019/Community/Common7/IDE/CommonExtensions/Microsoft/CMake/CMake/share/cmake-3.19/Modules/FindJNI.cmake:382 (FIND_PACKAGE_HANDLE_STANDARD_ARGS)
  flutter/ephemeral/.plugin_symlinks/jni/src/CMakeLists.txt:32 (find_package)


Building Windows application...                                    11.5s
Unable to generate build files

@HosseinYousefi
Copy link

This is similar to getsentry/sentry-dart#3033

So I write what I wrote there here as well:

@HosseinYousefi maybe you can confirm

issue: we're using JNI on Android but also means Flutter Desktop targets are affected due to flutter's plugin system. we don't use any JNI api during runtime on Desktop -> will end users need java installed in that case on Desktop using the app?

End users don't need to have Java installed as long as we're not using JNI on Windows (which I assume we're not here).

This is an issue with Flutter's plugin system. You could technically spawn JVM and use package:jni on Windows. This will be solved once we use the newly introduced build hooks for building package:jni's native library instead. Sentry could pass a parameter to specify that it's only using JNI on android and not on desktop.

Originally posted by @HosseinYousefi in #3033

I can fix this by making the windows build show a warning instead of an error if it couldn't find JDK.

path: 'lib/src/third_party/path_provider.g.dart'
structure: 'single_file'

## Classes / packages for which bindings need to be generated.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does jnigen support include-based filtering yet? It was added to jnigen, and instead of a generated file that was huge, like the 12k lines in this PR, it's only about 600.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems to be blocked on dart-lang/native#2962.

@stuartmorgan-g
Copy link
Collaborator

Oops, I lost a comment because GitHub won't let me save a comment on the deleted file for reason. I had this on the deleted Dart unit tests:

I would expect these tests to be moved to the integration test runner rather than removed, so that we are still unit testing how we handle specific responses to from the system layer.

@Piinks
Copy link
Contributor

Piinks commented Dec 15, 2025

Greetings from stale PR triage! 👋
Is this change still on your radar?

@stuartmorgan-g
Copy link
Collaborator

The PR was blocked by jni breaking Windows, but I believe jni 0.15.2 resolves the blocker.

@stuartmorgan-g
Copy link
Collaborator

I pushed a bunch of changes:

  • Merged in latest master
  • Updated to latest jni/jnigen
  • Switched to the new Dart API generator approach instead of the config yaml
  • Removed all of the native plugin code (the entire android/ directory)
  • Added a minimal Dart unit test that registration works, so that we still have the Dart unit test structure set up.
  • Added a facade with a stub export for web, to avoid compilation errors from transitive includes, as with path_provider_foundation.
  • Minor style changes.

Currently we're gated on jni moving to the main publisher (although we could decide to change that policy; nothing would actually prevent us from shipping with the labs dependency), and ideally on dart-lang/native#2962 allowing us to do filtering, but that shouldn't matter much in practice since the analyzer handles the current file reasonably, and tree shaking should prevent most of the code from ever ending up in a build.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants