[英]How to integrate C++ into Android Java application?
我想使用C ++在后台运行服务,该服务将处理图像。 但是我不能用C ++编写整个应用程序,因为它是一个协作项目,我该如何用C ++创建一个android服务,然后从Java编写的应用程序中调用/运行它?
您应该查看Java本机接口(JNI)
请记住,我没有尝试使用Android或Android API做任何事情,但这是我与JNI合作处理运行Java 8嵌入式版本的Linux ARM芯片的经验。
您将需要交叉编译要用于android操作系统的任何C ++文件。 打包JAR使其在Andrioid设备上运行时,您将需要包含可静态链接到的已编译二进制文件。 您可以使用本机方法从Java调用C ++方法,并且可以在C ++程序中存储指向JVM的指针,并从C ++进行方法的回调。
如果您正在使用诸如maven之类的程序打包项目,则可以使用一些插件自动为您完成此操作。
这是我们用于为嵌入式Linux操作系统编译的配置。 (您必须出于自己的目的对此进行修改)
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>native-maven-plugin</artifactId>
<version>1.0-alpha-7</version>
<extensions>true</extensions>
<configuration>
<javahOS>linux</javahOS>
<jdkIncludePath>${embeddedJDKIncludePath}</jdkIncludePath>
</configuration>
<executions>
<execution>
<id>javah</id>
<phase>generate-sources</phase>
<configuration>
<!-- trigger javah execution -->
<javahClassNames>
<javahClassName> LIST CLASS NAMES </javahClassName>
</javahClassNames>
<javahOS>linux</javahOS
<javahOutputDirectory>${project.build.directory}/include</javahOutputDirectory>
<javahProvider>default</javahProvider>
<javahVerbose>true</javahVerbose>
</configuration>
<goals>
<goal>javah</goal>
</goals>
</execution>
</executions>
</plugin>
当然,您希望将LIST CLASS NAMES
替换为要为其生成C ++ JNI绑定的类的实际列表。
然后可以这样声明类:
class RunService extends JNIWrapper {
public native boolean runService();
//More methods if you want. You can pass pretty much anything back
//and forth between native code.
}
您还需要编写在C ++文件中加载的JNIWrapper类。 这个JNIWrapper文件看起来像这样。
static
{
try
{
if( !libraryLoaded )
{
// create temporary file
jniLibrary = File.createTempFile([name of some temporary file]);
// flag for delete on exit
jniLibrary.deleteOnExit();
byte [] buffer = new byte[1024];
int readBytes;
InputStream is = JNIWrapper.class.getResourceAsStream([link to directory inside your compiled JAR where your C++ binary has been placed]);
OutputStream os = new FileOutputStream(jniLibrary);
try
{
while((readBytes = is.read(buffer)) != -1 )
{
os.write(buffer, 0, readBytes);
}
}
finally
{
os.close();
is.close();
}
libraryLoaded = true;
}
System.load(jniLibrary.getAbsolutePath());
}
catch( Exception ex )
{
ex.printStackTrace();
System.exit(1);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.