0

出于某种原因,我只能从我的主要活动中调用本机函数,而不能从我创建的任何自定义视图中调用。这是一个示例文件(我遵循了一个教程,但将类重命名为http://mindtherobot.com/blog/452/android-beginners-ndk-setup-step-by-step/

请参阅本机函数“getNewString”的用法。

package com.example.native;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.os.Bundle;
import android.view.View;

public class NativeTestActivity extends Activity
{   
    static
    {
        System.loadLibrary("nativeTest");
    }

    private native String getNewString();

    @Override public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);        
        this.setContentView(new BitmapView(this));

        String hello = getNewString(); // This line works fine
        new AlertDialog.Builder(this).setMessage(hello).show();
    }
}

class BitmapView extends View
{
    static
    {
        System.loadLibrary("nativeTest");
    }

    private native String getNewString();

    public BitmapView(Context context)
    {
        super(context);

        String hello = getNewString(); // This line throws the UnsatisfiedLinkError
        new AlertDialog.Builder(this.getContext()).setMessage(hello).show();
    }
}

如何在自定义视图中调用本机函数?

我已将该应用程序构建为 Android 2.2 应用程序。我正在我的 HTC Desire 上运行该应用程序。我有最新的 SDK (9) 和最新的 NDK (r5)。

4

1 回答 1

3

您的问题是您试图从它不属于的类中调用本机函数。

您在 c 文件中定义了以下 JNI 函数:

jstring Java_com_example_native_NativeTestActivity_getNewString()

这表明本地函数在加载时将与NativeTestActivity类中声明为本地的方法绑定。因此,当您尝试从View类中调用它时,它找不到任何要绑定的函数。

在这种情况下,它将查找以下函数(当然,您的 .so 中不存在该函数):

jstring Java_com_example_native_BitmapView_getNewString()

如果您仍然希望能够从不同的类调用相同的函数,您可以在可以从任何您想要的类访问的容器类中声明它。

例如:

爪哇代码

package com.example.native;
public class NativeHelper {
     public native String getNewString();
     static
     {
         System.loadLibrary("nativeTest");
     }
}

c代码:

jstring Java_com_example_native_NativeHelper_getNewString(JNIEnv* env, jobject javaThis)
{
     return (*env)->NewStringUTF(env, "Hello from native code!");
}
于 2010-12-22T03:49:18.423 回答