Android Studio NDK:二、JNI 返回JAVA 實體

jayqiu發表於2018-08-30

本篇是承接!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.執行結果

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

相關文章