Android Studio NDK:二、JNI 返回JAVA 实体

本篇是承接!Android Studio NDK基础入门(基于gradle-experimental插件)的基础上进行的

1.编写Books实体类
  /**
 * @author jayqiu
 * @describe
 * @date 2017/3/30 17:21
 */
public class Books {
    private String title;
    private String author;
    private String subject;
    private int book_id;
    public String getTitle() {
    return title;
}
public void setTitle(String title) {
    this.title = title;
}
public String getAuthor() {
    return author;
}
public void setAuthor(String author) {
    this.author = author;
}
public String getSubject() {
    return subject;
}
public void setSubject(String subject) {
    this.subject = subject;
}
public int getBook_id() {
    return book_id;
}
public void setBook_id(int book_id) {
    this.book_id = book_id;
}
}
2.编写MyNdk.java
  /**
 * @author jayqiu
 * @describe
 * @date 2017/3/30 13:52
 */
public class MyNdk {
    static {
      System.loadLibrary("MyNdk");
  }
    public  native int getAdd(int a,int b);
    public  native  Books getBooks(Books books);
}
3.MyNdk.c生成Java_com_threehalf_mynewjni_MyNdk_getBooks 方法
JNIEXPORT jobject JNICALL
Java_com_threehalf_mynewjni_MyNdk_getBooks(JNIEnv *env, jobject instance, jobject books) {
    jclass objectClass = (*env)->FindClass(env, "com/threehalf/mynewjni/Books");// java 实体类对应的位置
    jfieldID title = (*env)->GetFieldID(env,objectClass, "title", "Ljava/lang/String;");//book title
    jfieldID book_id =(*env)->GetFieldID(env,objectClass, "book_id", "I");//book id

    (*env)->SetObjectField(env,books, title, (*env)->NewStringUTF(env,"C 语言"));//设置booktitle
    (*env)->SetIntField(env,books, book_id, 10);// 设置 book id
    return  books;
}
4.MainActivity
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView textView = (TextView) findViewById(R.id.tv_name);

        // textView.setText(new MyNdk().getAdd(10,20)+"");
        Books books = new Books();
        books = (Books) new MyNdk().getBooks(books);
        textView.setText("ID:"+books.getBook_id() + "书名:" + books.getTitle());
    }
}
5.运行结果
Android Studio NDK:二、JNI 返回JAVA 实体_第1张图片
8.png
6.GetFieldID Java基础类型对应的符号
Java类型 符号
boolean Z
byte B
char C
short S
int I
long L
float F
double D
void V
objects对象 Lfully-qualified-class-name; L类名;
Arrays数组 [array-type [数组类型
methods方法 (argument-types)return-type(参数类型)返回类型

Android Studio NDK:三、打包SO
DOME 下载
Star 我的GitHub

你可能感兴趣的:(Android Studio NDK:二、JNI 返回JAVA 实体)