我需要一个简单的Java服务,它从系统启动开始,并使用共享库和一些使用POSIX线程的功能。在实现JNI接口时,我遇到了一些问题,它不允许我从本机代码进行Java方法调用。 GetMethodID()返回非NULL,所以我认为它做得很好。此外,没有任何可以帮助的可疑错误。所以我添加了很多输出来记录并准备了一个简单的java测试。 (所有代码都列在下面,但项目也可以在this repository at github中找到)
项目文件清单:
服务:
原生代码:
其他:
下面列出了所有文件。
我在测试服务中尝试了以下逻辑:
1.服务已启动:
TestService.java :
package com.example.testservice;
import java.lang.String;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
public class TestService extends Service {
private Looper mServiceLooper;
private ServiceHandler mServiceHandler;
private TestController testCtrl = null;
private static final String TAG = "TestService";
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
Log.e(TAG, msg.toString());
Log.e(TAG, "IT WORKS");
}
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
public void onDestroy() {
Toast.makeText(this, "Test service stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "Test has been stopped");
}
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "onCreate");
HandlerThread thread = new HandlerThread("ServiceStartArguments",
android.os.Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
@Override
public void onStart(Intent intent, int startid)
{
if (testCtrl != null) {
Log.d(TAG, "Service already running.");
return;
}
Log.d(TAG, "Starting test controller");
testCtrl = new TestController();
Log.d(TAG, "Test controller has started");
}
}
2.它创建了TestController类(大多数逻辑必须在其中),它创建了TestNative类。
interface TestListener.java :
package com.example.testservice;
public interface TestListener {
public void stringJavaMethod(String regStr);
}
TestController.java :
package com.example.testservice;
import android.util.Log;
public class TestController implements TestListener {
private static final String TAG = "TestController";
private TestNative mTestNative = null;
TestController() {
Log.d(TAG, "Starting test native");
mTestNative = new TestNative(this);
}
@Override
public void stringJavaMethod(String regStr) {
Log.d(TAG, "Callback called!!!!\n");
Log.e(TAG, regStr);
}
}
TestNative.java:
package com.example.testservice;
import android.os.Handler;
import android.util.Log;
public class TestNative implements TestListener {
static {
System.loadLibrary("log");
System.loadLibrary("layer-jni");
}
private static final String TAG = "TestNative";
private Handler mHandler;
private TestListener mDelegate;
TestNative(TestListener t) {
mDelegate = t;
mHandler = new Handler();
startAthread();
}
@Override
public void stringJavaMethod(final String regStr) {
Log.d(TAG, "IT WORKS?" + regStr);
mHandler.post(new Runnable() {
public void run() {
Log.e(TAG, "CALLED!\n");
mDelegate.stringJavaMethod(regStr);
}
});
}
/* native interface */
public static native void startAthread();
}
3.TestNative类要求本机库通过startAthread()方法开始工作
4.Native代码存储JVM,为调用对象创建一个全局引用并启动一个线程
5.Thread将自己附加到JVM并获取一个新的JNIEnv *指针。然后,它使用在步骤#4获得的全局对象链接查找Java方法ID,然后尝试定期调用此方法。
唯一的原生资源是 layer-jni.c :
#include "logcat.h"
#include "layer-jni.h"
#include <jni.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <android/asset_manager.h>
#include <android/asset_manager_jni.h>
JavaVM *jvm = NULL;
/* removed jObj UPD3 */
// jobject jObj;
/* added see UPD2 */
jclass jCls;
/******************/
static int run = 0;
static pthread_t t;
/* jobject -> jclass */
void callVoidMethodString(JNIEnv *env, jclass jcl, jmethodID jmid, const char *str);
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *ajvm, void *dummy) {
return JNI_VERSION_1_6;
}
void *thread_func(void *dummy) {
run = 1;
JNIEnv *env = NULL;
if (JNI_EDETACHED == (*jvm)->GetEnv(jvm, (void**)&env, JNI_VERSION_1_6)) {
if ( 0 != (*jvm)->AttachCurrentThread(jvm, &env, NULL)) {
DBG_INFO("Cannot attach JNIEnv!\n");
}
}
/* UPD2 - jObj -> jCls */
jmethodID jmid = (*env)->GetMethodID(env, jCls, "stringJavaMethod", "(Ljava/lang/String;)V");
if (!jmid) {
DBG_ERR("Cannot find java method...Terminating\n");
return NULL;
}
while(run) {
struct timespec ts = {.tv_sec = 1, .tv_nsec = 0 };
nanosleep(&ts, NULL);
DBG_INFO("Trying to call method\n");
callVoidMethodString(env, jCls, jmid, "***** Native2Java call works! *****\n");
}
(*jvm)->DetachCurrentThread(jvm);
return NULL;
}
JNIEXPORT void JNICALL
Java_com_example_testservice_TestNative_startAthread( JNIEnv* env,
jobject thiz)
{
DBG_INFO("enter startAthread()\n");
if (JNI_OK != (*env)->GetJavaVM(env, &jvm)) {
DBG_ERR("Cannot access Java VM! Terminating call.\n");
return;
}
DBG_INFO("Caching class tc...\n");
/* Updated: jObj replaced with jCls */
jCls = thiz;
jobject globalRef = (*env)->NewGlobalRef(env, jCls);
(*env)->DeleteLocalRef(env, jCls);
jCls = globalRef;
if (NULL == jCls) {
DBG_ERR("Cannot cache class TronNative!\n");
return;
}
/* UPD3: removed block below */
/* Added see UPD2 */
/*DBG_INFO("Caching class TestNative...\n");
*jclass clazz = (*env)->FindClass(env, "com/example/testservice/TestNative");
*if ((*env)->ExceptionCheck(env) == JNI_TRUE){
* (*env)->ExceptionDescribe(env);
* DBG_ERR("Exception while looking for TestNative class.\n");
* return;
*}
*jCls = (jclass)(*env)->NewGlobalRef(env, clazz);
*
*if ((*env)->ExceptionCheck(env) == JNI_TRUE){
* (*env)->ExceptionDescribe(env);
* DBG_ERR("Exception while trying to globalize TestNative class.\n");
* return;
*}
*(*env)->DeleteLocalRef(env, clazz);
*/
/*****************/
if (pthread_create(&t, NULL, thread_func, NULL)) {
DBG_ERR("Cannot create thread!\n");
}
}
static unsigned call_count = 0;
/* jobject -> jclass */
void callVoidMethodString(JNIEnv *env, jclass jcl, jmethodID jmid, const char *str) {
jstring jstr = (*env)->NewStringUTF(env, str);
char calls_str[50] = {0};
sprintf(calls_str, "calls:%u\n", call_count++);
(*env)->CallVoidMethod(env, jcl, jmid, jstr);
if ((*env)->ExceptionCheck(env)) {
DBG_ERR("There is some exceptional situation!\n");
(*env)->ExceptionDescribe(env);
(*env)->ExceptionClear(env);
}
(*env)->DeleteLocalRef(env, jstr);
DBG_INFO(calls_str);
}
6.因此,在调用本机代码中的CallVoidMethod()时,不会调用java方法“public void stringJavaMethod(final String regStr)”。没有任何错误,没有方法调用...
启动测试服务时得到的日志输出:
11-12 14:05:05.396: I/GAV2(18672): Thread[GAThread,5,main]: No campaign data found.
11-12 14:05:05.586: I/Autostart(16419): Starting service...
11-12 14:05:05.586: D/dalvikvm(18934): Late-enabling CheckJNI
11-12 14:05:05.586: I/ActivityManager(441): Start proc com.example.testservice for service com.example.testservice/.TestService: pid=18934 uid=10097 gids={50097, 3003, 1028}
11-12 14:05:05.606: D/dalvikvm(18934): Debugger has detached; object registry had 1 entries
11-12 14:05:05.696: D/dalvikvm(441): GC_EXPLICIT freed 1485K, 39% free 16961K/27776K, paused 3ms+7ms, total 89ms
11-12 14:05:05.736: I/TestService(18934): onCreate
11-12 14:05:05.736: D/TestService(18934): Starting test controller
11-12 14:05:05.736: D/TestController(18934): Starting test native
11-12 14:05:05.736: D/dalvikvm(18934): No JNI_OnLoad found in /system/lib/liblog.so 0x420e0a08, skipping init
11-12 14:05:05.736: D/dalvikvm(18934): Trying to load lib /data/app-lib/com.example.testservice-1/liblayer-jni.so 0x420e0a08
11-12 14:05:05.736: D/dalvikvm(18934): Added shared lib /data/app-lib/com.example.testservice-1/liblayer-jni.so 0x420e0a08
11-12 14:05:05.736: I/JNITestService(18934): enter startAthread()
11-12 14:05:05.736: I/JNITestService(18934): Caching class tc...
11-12 14:05:05.736: D/TestService(18934): Test controller has started
11-12 14:05:06.736: I/JNITestService(18934): Trying to call method
11-12 14:05:06.736: I/JNITestService(18934): calls:0
11-12 14:05:07.736: I/JNITestService(18934): Trying to call method
11-12 14:05:07.736: I/JNITestService(18934): calls:1
...etc
因此,Java代码中没有任何关于从本机代码调用而没有java方法调用的消息。这就是问题所在。因此,我计划在日志中看到一个字符串“ Native2Java调用正常工作! \ n”作为参数传递给JNI调用。
Android.mk的列表:
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
ANDROID_NDK := /home/michael/Downloads/android-ndk-r8e
LOCAL_MODULE := layer-jni
LOCAL_SRC_FILES := layer-jni.c
LOCAL_LDLIBS := -llog
TARGET_ARCH_ABI := armeabi-v7a
include $(BUILD_SHARED_LIBRARY)
Application.mk:
APP_ABI := armeabi-v7a
APP_PLATFORM := android-9
#APP_CPPFLAGS := -D__GXX_EXPERIMENTAL_CXX0X__ -std=gnu++11
STLPORT_FORCE_REBUILD := true
APP_STL := stlport_shared
的AndroidManifest.xml:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.testservice"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.USE_SIP"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name">
<service android:name=".TestService" android:exported="true">
<intent-filter>
<action android:name="com.example.testservice.TestService">
</action>
</intent-filter>
</service>
<receiver android:name=".autostart">
<intent-filter>
<action
android:name="android.intent.action.BOOT_COMPLETED">
</action>
</intent-filter>
</receiver>
</application>
</manifest>
我非常感谢有人可以帮我提出建议或想法,我必须检查/修复我的逻辑。
UPD:如果我将Java方法更改为静态,将GetMethodID()更改为GetStaticMethodID(),将CallVoidMethod()更改为CallStaticVoidMethod(),它将开始工作:
11-12 17:44:27.406: D/TestNative(21444): IT WORKS?***** Native2Java call works! *****
11-12 17:44:27.406: I/JNITestService(21444): calls:38
11-12 17:44:28.406: I/JNITestService(21444): Trying to call method
11-12 17:44:28.406: D/TestNative(21444): IT WORKS?***** Native2Java call works! *****
11-12 17:44:28.406: I/JNITestService(21444): calls:39
11-12 17:44:29.426: I/JNITestService(21444): Trying to call method
仍然不知道非静态成员无法工作的原因......
UPD2:固定调用GetMethodID() - 用jCls替换jObj。如果通过FindClass()获得jCls,则结果保持不变(没有调用,没有错误)。如果jCls是通过GetObjectClass()而不是FindClass()获得的 - 那么在尝试使用这个新的jCls获取方法id时会发生异常:
11-12 18:17:59.926: D/TestService(22540): Test controller has started
11-12 18:17:59.926: E/JNITestService(22540): Cannot find java method...Terminating
11-12 18:17:59.926: W/dalvikvm(22540): threadid=12: thread exiting with uncaught exception (group=0x4198b700)
11-12 18:17:59.926: E/AndroidRuntime(22540): FATAL EXCEPTION: Thread-6532
11-12 18:17:59.926: E/AndroidRuntime(22540): java.lang.NoSuchMethodError: no method with name='stringJavaMethod' signature='(Ljava/lang/String;)V' in class Ljava/lang/Class;
11-12 18:17:59.926: E/AndroidRuntime(22540): at dalvik.system.NativeStart.run(Native Method)
UPD3 :删除jObj,现在只使用jCls。而startAthread的参数已经修复。但仍然没有错误,没有调用(非静态方法,静态版本的方法正在工作)。
答案 0 :(得分:2)
jmethodID jmid = (*env)->GetMethodID(env, jObj, "stringJavaMethod", "(Ljava/lang/String;)V");
GetMethodID的使用不正确。第二个参数应该是jclass类型,而不是像你正在使用的jobject。
要将jobject转换为jclass,请使用
jclass GetObjectClass(JNIEnv *env, jobject obj);
此外,您应该使用GetStaticMethodID
,因为您的目标方法是静态的
修改1 :
检查public static native void startAthread()
的本机方法签名不正确。它应该是
JNIEXPORT void JNICALL Java_Test_startAthread(JNIEnv *, jclass);
目前
JNIEXPORT void JNICALL Java_Test_startAthread(JNIEnv *, jobject);
这种差异解释了为什么当你将相应的Java函数更改为static时它的工作原理,因为你实际上一直有一个jclass对象,而不是一个jobject。
修改2
现在函数声明是正确的,问题很明显:你试图在没有类实例的情况下调用实例方法。您需要将静态startAthread
函数更改为非静态并保存实例对象,否则您需要将调用的Java方法更改为静态。根据您的实际实施情况,选择适合您的那个。