使用NDk的场景:

1.某些方法,是使用C,C++本地代码实现的,然后,我想在Java中调用这些方法。这个时候,就需要使用到JNI技术。

 

应用NDK的时候,分两个部分,Java部分,JNI层部分,本地代码部分。

Java部分,看一个例子:

public class JNIActivity extends Activity {
  
  static{
    
    System.loadLibrary("myjni");
  }
  
  public native String getMessage();
  
  

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    
    TextView textView = new TextView(this);
    textView.setText(getMessage());
    
    setContentView(textView);
  }


  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.jni, menu);
    return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
      return true;
    }
    return super.onOptionsItemSelected(item);
  }
}

Java部分,要做的事情就是:1.声明要使用的本地方法,使用关键字native。2.加载包含实现该方法的库(在windows平台下是dll;在类Unix平台下是.so)。

 

JNI层部分,则应用了JNI部分的知识,比如:

#include <jni.h>
#include "include/HelloJNI.h"

JNIEXPORT jstring JNICALL Java_com_mytest_JNIActivity_getMessage
          (JNIEnv *env, jobject thisObj) {
   return (*env)->NewStringUTF(env, "Hello from native code!");
}

 

用一个简单的例子说明NDK的开发步骤:

1.一个使用本地方法的Java类JNIActivity,声明使用C,C++代码实现的本地方法使用native关键字;载入动态库,此时动态库还没有生成。

结果如下:

public class JNIActivity extends Activity {
  
  static{
    
    System.loadLibrary("myjni");
  }
  
  public native String getMessage();
  
  

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    
    TextView textView = new TextView(this);
    textView.setText(getMessage());
    
    setContentView(textView);
  }


  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.jni, menu);
    return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
      return true;
    }
    return super.onOptionsItemSelected(item);
  }
}
View Code

相关文章: