开发者

Monodroid, Interop betwen Java and C#

开发者 https://www.devze.com 2023-04-05 14:39 出处:网络
We have a big Java application under Android (\"big\" just means it\'s too much work to translate the application). We must access to an engine written in .Net (this engine is also too \"big\" ...). T

We have a big Java application under Android ("big" just means it's too much work to translate the application). We must access to an engine written in .Net (this engine is also too "big" ...). This engine is only calcula开发者_StackOverflow中文版tion.

We therefore seek a solution with monodroid. Our main problem is interop betwen monodroid and Java. At this time, we get :

  • call a Java function in a .jar library from a Mono application

But we can not call and start a Java activity. Is it possible ?

The second problem is that we do not know how to communicate from Java to Mono. Is it also possible?


There are several ways to call integrate Java and managed code, depending on what exactly you want to do.

Java to Managed

If you need to call some managed method, you may be able to use Android Callable Wrappers, which are generated for every Java.Lang.Object subclass. However, there are a number of limitations, so that may not be ideal.

If you need to create an Activity, you can use Context.startActivity(), the same as you would in Java. You can view the generated obj\Debug\android\AndroidManifest.xml to determine the appropriate class name to use, or you can use e.g. ActivityAttribute.Name to manually control the Java-side name. (Using ActivityAttribute.Name is not recommended, as it slows down type loading.)

The same is true for Services: use Context.startContext() and continue on your merry way.

If you need to share data, the easiest way would be to use a ContentProvider. ContentProviders are usually intended for cross-process data sharing, but they should be usable intra-process as well, when you need to share data between Java & managed code and you hit the limitations of Android Callable Wrappers.

Managed to Java

By and large, calling Java code from C# is the mirror of Java code calling C#: you can use e.g. Context.StartActivity() to start a Java activity, use a Java-side ContentProvider through the the Context.ContentResolver property, etc.

An example of starting a Java activity from managed code is the GoogleMaps sample, in which Context.StartActivity() is used to launch the included Java activity.

You can also use Java Native Interface (JNI) support to create Java instances from managed code and invoke methods on those instances. This is painful and brittle, but it works and allows invoking APIs that aren't otherwise exposed.


You can easily call Java activity from native code like this:

var intent = new Intent().SetClassName(this,"com.myapp.java.JavaActivity");
StartActivity(intent);

As I understood from this article you can invoke native code from Java via ACW, but I think that it's too difficult

0

精彩评论

暂无评论...
验证码 换一张
取 消