通过系统框架的JNI读取文件例子-附源码
android的JNI开发有两种,一种是基于应用程序的,一种是基于系统框架的。
java文件,指定native函数来实现接口的功能
基于应用程序的比较简单,之前已经有所了解,今天实践了一下基于系统框架的JNI读取文件的操作。
效果图:
总体框架:
1.应用程序调用API
2.JAVA层编写API接口,调用JNI层函数
3.JNI实现读取文件的操作,并根据要求返回读取的文件
主要层次为:
1.应用程序调用API
- Stringmstr=helloService.getText();//apiforreadfile
- newAlertDialog.Builder(JniTestActivity.this)
- .setMessage(mstr)
- .show();
- Log.i(JAVA_DEBUG,"done");
- }catch(RemoteExceptione){
- Log.e(JAVA_DEBUG,"RemoteExceptionwhilereadingvaluefromhelloService.sayHello().");
- }
2.JAVA层编写API接口,调用JNI层函数
aidl文件,定义接口规范:
- interfaceIHelloService{
- StringgetText();
- }
- importandroid.content.Context;
- importandroid.os.IHelloService;
- importandroid.util.Slog;
- publicclassHelloServiceextendsIHelloService.Stub{
- privatestaticfinalStringTAG="HelloService";
- publicStringgetText(){
- returngetText_native();
- }
- privatestaticnativeStringgetText_native();
- };
3.JNI实现读取文件的操作,并根据要求返回读取的文件
- #include"jni.h"
- #include"JNIHelp.h"
- #include"android_runtime/AndroidRuntime.h"
- #include<utils/misc.h>
- #include<utils/Log.h>
- #include<stdio.h>
- #include<fcntl.h>
- namespaceandroid
- {
- #defineTEXT_SUPPLY_PATH"/system/usr/getText.txt"
- #definePATH_MAX_LEN4096
- staticintreadFromFile(constchar*path,char*buf,size_tsize);
- staticjstringhello_getText(JNIEnv*env,jobjectclazz){
- charpath[PATH_MAX_LEN];
- charbuf[50];
- LOGI("HelloJNI:gettextfromdevice.");
- snprintf(path,sizeof(path),"%s",TEXT_SUPPLY_PATH);
- intlength=readFromFile(path,buf,sizeof(buf));
- LOGI("HelloJNI:filelength=%d.",length);
- return(env)->NewStringUTF(buf);
- }
- staticintreadFromFile(constchar*path,char*buf,size_tsize)
- {
- if(!path)
- return-1;
- intfd=open(path,O_RDONLY,0);
- if(fd==-1){
- LOGE("Couldnotopen'%s'",path);
- return-1;
- }
- size_tcount=read(fd,buf,size);
- if(count>0){
- count=(count<size)?count:size-1;
- while(count>0&&buf[count-1]=='\n')count--;
- buf[count]='\0';
- }else{
- buf[0]='\0';
- }
- close(fd);
- returncount;
- }
- staticconstJNINativeMethodmethod_table[]={
- {"getText_native","()Ljava/lang/String;",(void*)hello_getText},
- };
- intregister_android_server_HelloService(JNIEnv*env){
- returnjniRegisterNativeMethods(env,"com/android/server/HelloService",method_table,NELEM(method_table));
- }
- };
注意事先把文件准备把,存放的路径为:TEXT_SUPPLY_PATH"/system/usr/getText.txt"
主要是以上3个层次,省略了*.mk文件的修改细节,了解原理即可。