问题描述如题。下来我贴代码:
这是含有native函数的java文件
public class ProgressBarOperation {
static {
System.loadLibrary("Pressure");
}
public native void startMonitor();
public native void stopMonitor();
}
native函数所在的java文件不能继承Activity之类的。是我哪里搞错了还是什么原因,求大神解释。
接下来就是主文件,继承Activity的
public class MainActivity extends Activity implements OnClickListener {
private ProgressBar progressBar;
private ProgressBarOperation operation;
private Button btn_start, btn_stop;
static {
System.loadLibrary("Pressure");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
operation = new ProgressBarOperation();
btn_start = (Button)findViewById(R.id.btn_start);
btn_start.setOnClickListener(this);
btn_stop = (Button)findViewById(R.id.btn_stop);
btn_stop.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.btn_start) {
new Thread(new Runnable() {
@Override
public void run() {
operation.startMonitor();
}
}).start();
} else if (v.getId() == R.id.btn_stop) {
operation.stopMonitor();
}
}
public void setPressure(int pressure) {
Log.e("pressure", "" + pressure);
progressBar.setProgress(pressure);
}
}
接下来就是自己编写jni文件了。中间自动生成头文件就不说了
我把整个cpp文件全部贴过来
#include <jni.h>
#include <stdlib.h>
#include <unistd.h>
#include "com_example_pressuretest_ProgressBarOperation.h"
int getPressure() {
return rand() % 100;
}
int flag = JNI_TRUE;
JNIEXPORT void JNICALL Java_com_example_pressuretest_ProgressBarOperation_startMonitor(
JNIEnv *env, jobject obj) {
while (flag) {
sleep(1);
//拿到字节码对象
jclass clazz = env->FindClass("com/example/pressuretest/MainActivity");
jmethodID methodId = env->GetMethodID(clazz, "setPressure", "(I)V");
jobject dpobj= env->NewObject(clazz, methodId);
env->CallVoidMethod(dpobj, methodId, getPressure());
}
}
JNIEXPORT void JNICALL Java_com_example_pressuretest_ProgressBarOperation_stopMonitor(
JNIEnv *env, jobject obj) {
flag = JNI_FALSE;
}
env->CallVoidMethod(dpobj, methodId, getPressure());这句话一直报错,错误提示也看不来究竟错在哪里