Android P 自定义 jni
JNI是Java Native Interface的缩写,它提供了若干的API实现了Java和其他语言的通信(主要是C&C++)。从Java1.1开始,JNI标准成为java平台的一部分,它允许Java代码和其他语言写的代码进行交互。JNI一开始是为了本地已编译语言,尤其是C和C++而设计的,但是它并不妨碍你使用其他编程语言,只要调用约定受支持就可以了。使用java与本地已编译的代码交互,通常会丧失平台可移植性。但是,有些情况下这样做是可以接受的,甚至是必须的。例如,使用一些旧的库,与硬件、操作系统进行交互,或者为了提高程序的性能。JNI标准至少要保证本地代码能工作在任何Java 虚拟机环境。
这里教大家怎么再Android的Service中自定义jni,Service以之前一篇博文为例:
Android P中如何自定义一个系统Service
1. 定义native方法
JustArtService.java中添加native方法,在binder调用方法中调用native方法,目的是其他进程应用也可以访问这个方法。
public class JustArtService extends IJustArt.Stub{
private final static String TAG = "JustArtService";
// 定义jni访问接口
private static native String nativeGetWifiInfo();
public JustArtService(){
}
@Override
public String getAllWifiInfo() throws RemoteException {
Slog.d(TAG,"this is a new service for debug");
//调用jni方法
String str = nativeGetWifiInfo();
Slog.d(TAG,str==null?"null info":str);
return str;
}
}
2. 新建jni文件
我在自定义系统service基础上来写这篇博文,所以我将.cpp文件创建在frameworks/base/services/core/jni/com_android_server_justart_JustArtService.cpp
#define LOG_TAG "JustArtService"
#include <android_runtime/AndroidRuntime.h>
#include <jni.h>
//【a】导入jni依赖包(必须)
#include <nativehelper/JNIHelp.h>
#include <nativehelper/ScopedUtfChars.h>
#include <stdio.h>
......
namespace android
{
static char* read_file(const char *path)
{
int fd = -1, size;
static char str[1000];
fd = open(path, O_RDONLY);
if(fd==-1)
{
ALOGE("file not found or no permission");