Calling native libraries in Flutter using Platform Channels

haz :

Using platform channels, Flutter can interop with the native platform (i.e. reading battery level). On Android, this would require calling a Java method.

I'd like to use a third-party Java SDK (for AWS Cognito). Can I put this library somewhere in my /android, and interact with it? If so, how can I do that?

Richard Heap :

If you haven't already got a plugin project started, create one.

Gather the third party jars somewhere - don't put them in the pluginproject/android/... folder.

Open the plugin project in your IDE - in my case IDEA - and add the third party jars to the Java classpath. (In IDEA, click Project Structure / Modules / select pluginName_android / Dependencies tab / green PlusSign / jars or directories - and select the individual jars or the whole folder. Leave the scope as compile and don't check export.)

Implement your android-specific code in Java (or Kotlin) in pluginproject/android/src/main/java/com/yourcompany.../.../PluginnamePlugin.java, where you will now be able to use the classes declared by the third party jars.

Add the dependencies to gradle so that it will compile. In pluginproject/android/build.gradle (NOTE - there are several build.gradles) add this at the end - after the android {} section

dependencies {
    implementation files('../../../java/someapi/somejar.jar')
}

The path must be relative to the pluginproject/android folder. You can specify a whole folder with this syntax instead

implementation fileTree(dir: '../../../somewhere/somefolder', include: ['*.jar'])

Run the example application provided in the plugin project.

I'm not sure why it's not possible to put the third party jars in, say, pluginproject/android/lib, but that causes a dex error for me, whereas, leaving them outside of the pluginproject/ folder works.

I've only ever used well-behaved third party jars (no JNI, don't create their own Threads, etc).

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=460307&siteId=1