我需要通过c ++代码从本机方法生成linux命令。
这是我的班级 Test.java
public class Test {
static { System.loadLibrary("NDK1"); }
public native String exec(String cmd);
}
然后我通过这个命令创建标题.h:
$ javah -classpath ../bin/classes com.example.new1.Test
之后,在此路径com.example.new1中创建标题.h 然后我创建 jni 文件并复制.h文件并创建.cpp文件并在其中包含.h。
#include <string>
#include <iostream>
#include <stdio.h>
#include <jni.h>
#include "com_example_new1_Test.h"
std::string exec(const char* cmd) {
FILE* pipe = popen(cmd, "r");
if (!pipe) return "ERROR";
char buffer[128];
std::string result = "";
while(!feof(pipe)) {
if(fgets(buffer, 128, pipe) != NULL)
result += buffer;
}
pclose(pipe);
return result;
}
JNIEXPORT jstring JNICALL Java_com_example_new1_Test_exec(JNIEnv* env, jobject javaThis , jstring cmd) {
const char * res;
//res = env->GetStringUTFChars(cmd ) ;
// const char* utf_string;
jboolean isCopy;
res = env->GetStringUTFChars(cmd, &isCopy);
/* ... use string ... */
if (isCopy == JNI_TRUE) {
(env)->ReleaseStringUTFChars(cmd, res);
}
std::string result = exec(res);
return (env)->NewStringUTF((const char* )result.c_str());
}
然后拨打 NDK
$ /cygdrive/c/android-ndk-r4/ndk-build
make: Warning: File `/cygdrive/c/android-ndk-r4/build/core/import-locals.mk' has modification time 140582392 s in the future
Cygwin : Generating dependency file converter script
Compile++ thumb : NDK1 <= NDK1.cpp
Prebuilt : libgnustl_static.a <= <NDK>/sources/cxx-stl/gnu- libstdc++/4.6/libs/armeabi/
SharedLibrary : libNDK1.so
Install : libNDK1.so => libs/armeabi/libNDK1.so
Compile++ thumb : NDK1 <= NDK1.cpp
Prebuilt : libgnustl_static.a <= <NDK>/sources/cxx-stl/gnu- libstdc++/4.6/libs/armeabi-v7a/
SharedLibrary : libNDK1.so
Install : libNDK1.so => libs/armeabi-v7a/libNDK1.so
make: warning: Clock skew detected. Your build may be incomplete.
当我运行我的应用程序时没有出现错误或异常,但没有从本机方法返回值! 这是运行日志
03-03 22:59:55.343: E/SpannableStringBuilder(9257): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
03-03 22:59:55.343: E/SpannableStringBuilder(9257): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
03-03 23:00:08.527: E/Trace(9852): error opening trace file: No such file or directory (2)
03-03 23:00:08.717: D/libEGL(9852): loaded /system/lib/egl/libEGL_mali.so
03-03 23:00:08.727: D/libEGL(9852): loaded /system/lib/egl/libGLESv1_CM_mali.so
03-03 23:00:08.727: D/libEGL(9852): loaded /system/lib/egl/libGLESv2_mali.so
03-03 23:00:08.747: D/OpenGLRenderer(9852): Enabling debug mode 0
03-03 23:00:21.960: D/dalvikvm(9852): Trying to load lib /data/data/com.example.new1/lib/libNDK1.so 0x41a1d8f8
03-03 23:00:21.980: D/dalvikvm(9852): Added shared lib /data/data/com.example.new1/lib/libNDK1.so 0x41a1d8f8
03-03 23:00:21.980: D/dalvikvm(9852): No JNI_OnLoad found in /data/data/com.example.new1/lib/libNDK1.so 0x41a1d8f8, skipping init
有什么问题?顺便说一句,我通过“iwconfig”作为linux命令,它取决于命令是什么?我还需要AndroidManifest的任何许可吗?