您的位置:首页 > 移动开发 > Android开发

android NDK使用

2013-11-06 10:48 489 查看
/article/5851785.html

/article/4260339.html

1. 创建eclipse 工程

2. 添加java代码

package com.example.helloapp2;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class HelloApp2 extends Activity {

Button mButton1;

public native int helloCtest ();

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hello_app2);
}

@Override
protected void onResume()
{
// TODO Auto-generated method stub
super.onResume();

mButton1 =(Button) findViewById(R.id.button1);
mButton1.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
System.out.println("onclick");
int value=helloCtest ();
System.out.println("value:"+value);

}
});

}

static {
System.loadLibrary("hello");
}

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

}


3. 编写c代码

3.1 生成.h文件

$cd ./workspace2/helloApp2/bin/classes

$javah com.example.helloapp2.HelloApp2

3.2 编写.c 文件

#include <string.h>
#include <jni.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>

JNIEXPORT jint JNICALL
Java_com_example_helloapp2_HelloApp2_helloCtest(JNIEnv *env, jobject thiz)
{
int fd;

fd = open("/dev/hello", O_RDWR);
if(fd < 0)
printf("Can't open /dev/hello!\n");
else
{
ioctl(fd, 1);
close(fd);
}

return 0;
}


3.3 编写Android.mk

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)
LOCAL_MODULE := hello
LOCAL_SRC_FILES := hello.c

include $(BUILD_SHARED_LIBRARY)


3.4 生成.so共享库文件



4. eclipse编译

eclipse中刷新工程,重新编译生成apk, libhello.so共享库会打包到apk内。

ps:

本例中需要 chmod 777 /dev/hello
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: