Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling native libraries in Flutter using Platform Channels

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?

like image 315
haz Avatar asked Apr 25 '18 10:04

haz


2 Answers

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).

like image 91
Richard Heap Avatar answered Sep 19 '22 18:09

Richard Heap


Yes you can.

You can see the documentation on that or if you want you can see tutorial. It is helpful if you are using SDK that gives you native code for both Android and iOS, otherwise it will be difficult. Good luck!

like image 28
goops17 Avatar answered Sep 21 '22 18:09

goops17