通过系统框架的JNI读取文件例子-附源码

android的JNI开发有两种,一种是基于应用程序的,一种是基于系统框架的。

基于应用程序的比较简单,之前已经有所了解,今天实践了一下基于系统框架的JNI读取文件的操作。


效果图:

通过系统框架的JNI读取文件例子-附源码

总体框架:

1.应用程序调用API

2.JAVA层编写API接口,调用JNI层函数

3.JNI实现读取文件的操作,并根据要求返回读取的文件


主要层次为:

1.应用程序调用API

try{
  1. Stringmstr=helloService.getText();//apiforreadfile
  2. newAlertDialog.Builder(JniTestActivity.this)
  3. .setMessage(mstr)
  4. .show();
  5. Log.i(JAVA_DEBUG,"done");
  6. }catch(RemoteExceptione){
  7. Log.e(JAVA_DEBUG,"RemoteExceptionwhilereadingvaluefromhelloService.sayHello().");
  8. }

2.JAVA层编写API接口,调用JNI层函数

aidl文件,定义接口规范:

packageandroid.os;
  1. interfaceIHelloService{
  2. StringgetText();
  3. }
java文件,指定native函数来实现接口的功能

packagecom.android.server;
  1. importandroid.content.Context;
  2. importandroid.os.IHelloService;
  3. importandroid.util.Slog;
  4. publicclassHelloServiceextendsIHelloService.Stub{
  5. privatestaticfinalStringTAG="HelloService";
  6. publicStringgetText(){
  7. returngetText_native();
  8. }
  9. privatestaticnativeStringgetText_native();
  10. };

3.JNI实现读取文件的操作,并根据要求返回读取的文件

#defineLOG_TAG"HelloService"
  1. #include"jni.h"
  2. #include"JNIHelp.h"
  3. #include"android_runtime/AndroidRuntime.h"
  4. #include<utils/misc.h>
  5. #include<utils/Log.h>
  6. #include<stdio.h>
  7. #include<fcntl.h>
  8. namespaceandroid
  9. {
  10. #defineTEXT_SUPPLY_PATH"/system/usr/getText.txt"
  11. #definePATH_MAX_LEN4096
  12. staticintreadFromFile(constchar*path,char*buf,size_tsize);
  13. staticjstringhello_getText(JNIEnv*env,jobjectclazz){
  14. charpath[PATH_MAX_LEN];
  15. charbuf[50];
  16. LOGI("HelloJNI:gettextfromdevice.");
  17. snprintf(path,sizeof(path),"%s",TEXT_SUPPLY_PATH);
  18. intlength=readFromFile(path,buf,sizeof(buf));
  19. LOGI("HelloJNI:filelength=%d.",length);
  20. return(env)->NewStringUTF(buf);
  21. }
  22. staticintreadFromFile(constchar*path,char*buf,size_tsize)
  23. {
  24. if(!path)
  25. return-1;
  26. intfd=open(path,O_RDONLY,0);
  27. if(fd==-1){
  28. LOGE("Couldnotopen'%s'",path);
  29. return-1;
  30. }
  31. size_tcount=read(fd,buf,size);
  32. if(count>0){
  33. count=(count<size)?count:size-1;
  34. while(count>0&&buf[count-1]=='\n')count--;
  35. buf[count]='\0';
  36. }else{
  37. buf[0]='\0';
  38. }
  39. close(fd);
  40. returncount;
  41. }
  42. staticconstJNINativeMethodmethod_table[]={
  43. {"getText_native","()Ljava/lang/String;",(void*)hello_getText},
  44. };
  45. intregister_android_server_HelloService(JNIEnv*env){
  46. returnjniRegisterNativeMethods(env,"com/android/server/HelloService",method_table,NELEM(method_table));
  47. }
  48. };

注意事先把文件准备把,存放的路径为:TEXT_SUPPLY_PATH"/system/usr/getText.txt"

主要是以上3个层次,省略了*.mk文件的修改细节,了解原理即可。