Android NDK(r9d)开发简介

来源:互联网 发布:淘宝女装宝贝描述 编辑:程序博客网 时间:2024/05/22 08:18

重新复习一下Android NDK开发

1 创建项目,添加加载lib代码

package com.jni.test;import android.app.Activity;import android.os.Bundle;import android.view.Menu;import android.widget.TextView;public class HelloWorld extends Activity {private TextView mTextView;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);mTextView = (TextView) findViewById(R.id.textview);mTextView.setText(getHello());// 调用本地方法,设置字符串}static {System.loadLibrary("hello-jni");// 加载的lib库名称}private native String getHello();// 需要实现的本地方法@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.hello_world, menu);return true;}}
main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context=".HelloWorld" >    <TextView        android:id="@+id/textview"        android:layout_width="wrap_content"        android:layout_height="wrap_content" /></RelativeLayout>


2 实现.so库

2.1 生成.h文件

在src目录下使用javah命令生成.h文件

/adt-bundle-windows-x86/eclipse/workspace/HelloWorld/src$ javah com.jni.test.HelloWorld
2.2 实现.cpp文件

在工程中创建jni文件夹,将src文件夹中的.h文件移动到jni目录中。

根据.h文件中生成的函数,在.cpp中实现它

com_jni_test_HelloWorld.cpp

#include "com_jni_test_HelloWorld.h"JNIEXPORT jstring JNICALL Java_com_jni_test_HelloWorld_getHello  (JNIEnv * env, jobject obj) {return env->NewStringUTF("Hello World");}
实现很简单,就返回一个字符串。

注意,C和C++中对于env的调用时不一样的。

2.3 编写.mk

为了生成.so库,需要编写一个Android.mk文件。

注意,生成.so库的.mk文件名是固定的,不可以修改。

Android.mk

LOCAL_PATH := $(call my-dir)include $(CLEAR_VARS)LOCAL_MODULE    := hello-jniLOCAL_SRC_FILES := com_jni_test_HelloWorld.cppinclude $(BUILD_SHARED_LIBRARY)
2.4 编译.so库
使用ndk_build.cmd hello-jni生成hello-jni.so

或者在工程配置中增加ndk的builder

参见http://blog.csdn.net/leilu2008/article/details/12495273


3 编译链接整个工程,运行emulator







0 0