C++ 适合 Android 开发吗?

Is C++ suitable for Android development?

例如,我想创建一个基于 GPS 的简单应用程序,制作 waypoints,在地图上显示它们等。那么,是否可以仅使用 C++ 制作这样的应用程序,而无需有 Java 来源吗?会不会比在 Java 上做同样的事情更难?

是的,搜索 Android NDK。显然这有点麻烦,你会经常使用它!

So, is it possible to make such an app using C++ only, without any Java sources?

没有。如果您想接收 GPS 坐标,没有任何 Java 代码是无法做到这一点的。

可以 编写一个应用程序,其中 Java 用作本机代码的精简包装器,使用 JNI 在 Java 和 C++ 之间交换数据.然而...

Would it be more difficult than making the same on Java?

是的!此外,该应用程序 可能 最终成为:

  • 较慢。
  • 更麻烦。
  • 更难理解和维护。

对于 Android 开发,Java 只是自然的、正常的、默认的语言,而 C++ 用于奇异的特殊任务,通常是那些涉及真正密集计算的任务。当你需要它的时候你就使用它,而不是因为你没有"want to"写在Java或者因为"Java is slow".

编写正确的 JNI 代码也并非易事。例如,如果不阅读文档,很容易将局部引用和全局引用弄错,因为编译器无法检测到它们的错误用法。

正如 official documentation of the Android Native Development Kit 所说:

Before downloading the NDK, you should understand that the NDK will not benefit most apps. As a developer, you need to balance its benefits against its drawbacks. Notably, using native code on Android generally does not result in a noticable performance improvement, but it always increases your app complexity. In general, you should only use the NDK if it is essential to your app—never because you simply prefer to program in C/C++.

它还说:

You cannot access features such as Services and Content Providers natively, so if you want to use them or any other framework API, you can still write JNI code to do so.