001_Android Studio使用CMake工具和C语言混合编译

1.官方例子

Android Studio到2.2版本之后,在新建工程时,界面上多了一个Include C++ Support的选项。勾选它之后将会创建一个默认的C++与JAVA混编的示例工程。下面简单介绍一下这个工程

1.1 新建工程

勾选"include C++ support",然后点击"next",选择“Empty Activity”,最后点击“Finish”,这样和C++混合编译的工程就创建完毕。
勾选C++
.
选择空

1.2 混和编译的差异

项目打开后选择“Project”选项查看目录结构,工程里多出了.externalNativeBuild文件夹、cpp文件夹、CMakeLists.txt,如下图:

3项

  • 这三项说明如下:

    1. externalNativeBuild文件夹:通过cmake工具编译输出的文件, 显示支持的各种硬件等信息。系统生成。
    2. cpp文件夹:存放C/C++代码文件,native-lib.cpp文件是该示例工程中自带的,可以根据自己需求修改。
    3. CMakeLists.txt文件:CMake工具编译C语言的脚本配置的文件。需要根据自己需求进行相应的修改。
  • app目录下的build.gradle文件中有两处不一样,如下图所示:
    !Build差异

  • MainActiviy文件中调用C++文件内容的方式如下图:

    • 前面表示加载哪个C++文件;
    • 后面表示对C++文件中的函数进行引用说明。
      调用方式
package com.zhoujiazhao.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    // Used to load the 'native-lib' library on application startup.
    static {
        System.loadLibrary("native-lib");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Example of a call to a native method
        TextView tv = (TextView) findViewById(R.id.sample_text);
        tv.setText(stringFromJNI());
    }

    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    public native String stringFromJNI();
}
  • 此外,C++文件中的函数名要和自己工程的包名和引用的类名要对应,我的是Java_com_zhoujiazhao_myapplication_MainActivity
#include <jni.h>
#include <string>

extern "C"
JNIEXPORT jstring

JNICALL
Java_com_zhoujiazhao_myapplication_MainActivity_stringFromJNI(
        JNIEnv *env,
        jobject /* this */) {
    std::string hello = "Hello from C++";
    return env->NewStringUTF(hello.c_str());
}

创建C源码

2.在其它工程中添加和C混合编译

2.1 创建“cpp"文件夹和“c"源码

这里文件名为“hello.c”

//
// Created by jiazhao on 2018-06-28.
//

#include <jni.h>


jint Java_com_zhoujiazhao_zhaoc_MainActivity_Add(
        JNIEnv *env,
        jobject obj, jint a, jint b) {
    return a + b;
}

build.gradle文件修改

2.2 build.gradle文件中添加如下代码:

        externalNativeBuild {
            cmake {
                cppFlags ""
            }
        }
        
    externalNativeBuild {
        cmake {
            path "CMakeLists.txt"
        }
    }

build.gradle文件修改

2.3 创建CMakeLists.txt文件

这里部分代码可以从官方示例工程里面直接拷贝过来,进行修改,需根据C文件名进行修改,如下图所示:

CmakeLists文件修改

# For more information about using CMake with Android Studio, read the
# documentation: https://d.android.com/studio/projects/add-native-code.html

# Sets the minimum version of CMake required to build the native library.

cmake_minimum_required(VERSION 3.4.1)

# Creates and names a library, sets it as either STATIC
# or SHARED, and provides the relative paths to its source code.
# You can define multiple libraries, and CMake builds them for you.
# Gradle automatically packages shared libraries with your APK.

add_library( # Sets the name of the library.
             hello

             # Sets the library as a shared library.
             SHARED

             # Provides a relative path to your source file(s).
             src/main/cpp/hello.c )

# Searches for a specified prebuilt library and stores the path as a
# variable. Because CMake includes system libraries in the search path by
# default, you only need to specify the name of the public NDK library
# you want to add. CMake verifies that the library exists before
# completing its build.

find_library( # Sets the name of the path variable.
              log-lib

              # Specifies the name of the NDK library that
              # you want CMake to locate.
              log )

# Specifies libraries CMake should link to your target library. You
# can link multiple libraries, such as libraries you define in this
# build script, prebuilt third-party libraries, or system libraries.

target_link_libraries( # Specifies the target library.
                       hello

                       # Links the target library to the log library
                       # included in the NDK.
                       ${log-lib} )

2.4 C文件中函数的调用的方法和官方示例工程类似,MainActivity文件如下:

package com.zhoujiazhao.zhaoc;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    static {
        System.loadLibrary("hello");
    }

    private TextView mTextView = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTextView = (TextView)findViewById(R.id.hello_text_view);
        mTextView.setText("aaa:" + Integer.toString(Add(3, 5)));
    }

    public native int Add(int a, int b);
}

2.5生产xx.so库

点击菜单“Build -> Make project”生成.so文件

.so文件目录:app-build-intermediates-cmake-debug-obj

so库目录

写博客不容易,需要大家多多支持。想了解更多,本人也可以提供有赏服务
在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在 Android Studio使用 C 语言来收发短信,需要使用 Android NDK (Native Development Kit) 和 Android SMS Manager API。 以下是一个简单的示例代码,可以使用 C 语言来发送短信: ``` #include <jni.h> #include <android/log.h> #include <stdlib.h> #include <string.h> jstring Java_com_example_smsapp_MainActivity_sendSMS(JNIEnv* env, jobject obj, jstring phoneNumber, jstring message) { jclass smsManagerClass = (*env)->FindClass(env, "android/telephony/SmsManager"); jmethodID getDefaultMethod = (*env)->GetStaticMethodID(env, smsManagerClass, "getDefault", "()Landroid/telephony/SmsManager;"); jobject smsManager = (*env)->CallStaticObjectMethod(env, smsManagerClass, getDefaultMethod); const char* phoneNumberCStr = (*env)->GetStringUTFChars(env, phoneNumber, NULL); jstring destinationAddress = (*env)->NewStringUTF(env, phoneNumberCStr); const char* messageCStr = (*env)->GetStringUTFChars(env, message, NULL); jstring text = (*env)->NewStringUTF(env, messageCStr); jmethodID sendTextMessageMethod = (*env)->GetMethodID(env, smsManagerClass, "sendTextMessage", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Landroid/app/PendingIntent;Landroid/app/PendingIntent;)V"); (*env)->CallVoidMethod(env, smsManager, sendTextMessageMethod, destinationAddress, NULL, text, NULL, NULL); (*env)->ReleaseStringUTFChars(env, phoneNumber, phoneNumberCStr); (*env)->ReleaseStringUTFChars(env, message, messageCStr); return (*env)->NewStringUTF(env, "SMS sent successfully!"); } ``` 在此示例代码中,`sendSMS` 函数是一个 JNI (Java Native Interface) 函数,可以从 Java 代码中调用。在此函数中,我们首先获取 `SmsManager` 的实例,然后将目标电话号码和消息转换为 C 字符串并创建相应的 Java 字符串对象。最后,我们调用 `sendTextMessage` 方法来发送短信。 在 Android Studio使用 NDK 编译此代码时,需要编写一个 CMake 或 ndk-build 脚本来指定编译器、链接等设置。可以参考 Android NDK 文档来了解更多信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值