当前位置: 首页 > news >正文

贵阳建设企业网站精准客源 获客

贵阳建设企业网站,精准客源 获客,企业网站变成app的方法,互联网创新创业大赛项目计划书文章目录小结Android JNI使用CAndroid JNI读写本地文件有关权限创建文件夹访问 /storage/emulated/0/访问/data/data/example.jniwritefile/时间戳Cant determine type for tag参考小结 进行Android JNI C读写本地文件,取得了想要的效果。 Android JNI使用C 对于…

文章目录

  • 小结
  • Android JNI使用C++
  • Android JNI读写本地文件
    • 有关权限
    • 创建文件夹
    • 访问 /storage/emulated/0/
    • 访问/data/data/example.jniwritefile/
    • 时间戳
    • Can't determine type for tag
  • 参考

小结

进行Android JNI C++读写本地文件,取得了想要的效果。

Android JNI使用C++

对于Android的本地文件的操作,由于涉及到安全问题,并不是十分直接。
具体创建Andriod JNI应用,可以参考CSDN: android studio 3.2 使用jni 和 Add C and C++ code to your project

Android JNI读写本地文件

有关权限

要使用Android JNI读写本地文件,首先需要解决权限和授权的问题。否则会出现各种各样的错误。我碰到的有errno = 2 (No such file or directory) 和 errno = 13 (Permission denied),具体错误码如下:

errno错误码:
errno0 :     Successerrno1 :     Operation not permittederrno2 :     No such file or directoryerrno3 :     No such processerrno4 :     Interrupted system callerrno5 :     Input/output errorerrno6 :     No such device or addresserrno7 :     Argument list too longerrno8 :     Exec format errorerrno9 :     Bad file descriptorerrno10 :    No child processeserrno11 :    Resource temporarily unavailableerrno12 :    Cannot allocate memoryerrno13 :    Permission deniederrno14 :    Bad addresserrno15 :    Block device requirederrno16 :    Device or resource busyerrno17 :    File existserrno18 :    Invalid cross-device linkerrno19 :    No such deviceerrno20 :    Not a directoryerrno21 :    Is a directoryerrno22 :    Invalid argumenterrno23 :    Too many open files in systemerrno24 :    Too many open fileserrno25 :    Inappropriate ioctl for deviceerrno26 :    Text file busyerrno27 :    File too largeerrno28 :    No space left on deviceerrno29 :    Illegal seekerrno30 :    Read-only file systemerrno31 :    Too many linkserrno32 :    Broken pipeerrno33 :    Numerical argument out of domainerrno34 :    Numerical result out of rangeerrno35 :    Resource deadlock avoidederrno36 :    File name too longerrno37 :    No locks availableerrno38 :    Function not implementederrno39 :    Directory not emptyerrno40 :    Too many levels of symbolic linkserrno41 :    Unknown error 41errno42 :    No message of desired typeerrno43 :    Identifier removederrno44 :    Channel number out of rangeerrno45 :    Level 2 not synchronizederrno46 :    Level 3 haltederrno47 :    Level 3 reseterrno48 :    Link number out of rangeerrno49 :    Protocol driver not attachederrno50 :    No CSI structure availableerrno51 :    Level 2 haltederrno52 :    Invalid exchangeerrno53 :    Invalid request descriptorerrno54 :    Exchange fullerrno55 :    No anodeerrno56 :    Invalid request codeerrno57 :    Invalid sloterrno58 :    Unknown error 58errno59 :    Bad font file formaterrno60 :    Device not a streamerrno61 :    No data availableerrno62 :    Timer expirederrno63 :    Out of streams resourceserrno64 :    Machine is not on the networkerrno65 :    Package not installederrno66 :    Object is remoteerrno67 :    Link has been severederrno68 :    Advertise errorerrno69 :    Srmount errorerrno70 :    Communication error on senderrno71 :    Protocol errorerrno72 :    Multihop attemptederrno73 :    RFS specific errorerrno74 :    Bad messageerrno75 :    Value too large for defined datatypeerrno76 :    Name not unique on networkerrno77 :    File descriptor in bad stateerrno78 :    Remote address changederrno79 :    Can not access a needed sharedlibraryerrno80 :    Accessing a corrupted sharedlibraryerrno81 :    .lib section in a.out corruptederrno82 :    Attempting to link in too manyshared librarieserrno83 :    Cannot exec a shared librarydirectlyerrno84 :    Invalid or incomplete multibyte orwide charactererrno85 :    Interrupted system call should berestartederrno86 :    Streams pipe errorerrno87 :    Too many userserrno88 :    Socket operation on non-socketerrno89 :    Destinationaddress requirederrno90 :    Message too longerrno91 :    Protocol wrong type for socketerrno92 :    Protocol not availableerrno93 :    Protocol not supportederrno94 :    Socket type not supportederrno95 :    Operation not supportederrno96 :    Protocol family not supportederrno97 :    Address family not supported byprotocolerrno98 :    Address already in useerrno99 :    Cannot assign requested addresserrno100 :   Network is downerrno101 :   Network is unreachableerrno102 :   Network dropped connection onreseterrno103 :   Software caused connection aborterrno104 :   Connection reset by peererrno105 :   No buffer space availableerrno106 :   Transport endpoint is alreadyconnectederrno107 :   Transport endpoint is notconnectederrno108 :   Cannot send after transportendpoint shutdownerrno109 :   Too many references: cannot spliceerrno110 :   Connection timed outerrno111 :   Connection refusederrno112 :   Host is downerrno113 :   No route to hosterrno114 :   Operation already in progresserrno115 :   Operation now in progresserrno116 :   Stale NFS file handleerrno117 :   Structure needs cleaningerrno118 :   Not a XENIX named type fileerrno119 :   No XENIX semaphores availableerrno120 :   Is a named type fileerrno121 :   Remote I/O errorerrno122 :   Disk quota exceedederrno123 :   No medium founderrno124 :   Wrong medium typeerrno125 :   Operation cancelederrno126 :   Required key not availableerrno127 :   Key has expirederrno128 :   Key has been revokederrno129 :   Key was rejected by serviceerrno130 :   Owner diederrno131 :   State not recoverableerrno132 :   Operation not possible due toRF-killerrno133 :   Unknown error 133errno134 :   Unknown error 134errno135 :   Unknown error 135errno136 :   Unknown error 136errno137 :   Unknown error 137errno138 :   Unknown error 138errno139 :   Unknown error 139

有关权限的问题的具体解决办法可能参考此篇文章:CSDN: Android文件读写权限 fopen errno=13

默认设置是App可以访问本应用所在的目录, 例如/data/data/example.jniwritefile/,这里example.jniwritefile是应用名字。但是要访问其它存储,需要考虑到权限问题。

权限的问题的解决办法是在AndroidManifest.xml加了几个文件操作权限,并在application中加入了android:requestLegacyExternalStorage="true",文件具体如下:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/><uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" tools:ignore="ProtectedPermissions" /><uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"tools:ignore="ScopedStorage" /><applicationandroid:allowBackup="true"android:dataExtractionRules="@xml/data_extraction_rules"android:fullBackupContent="@xml/backup_rules"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:roundIcon="@mipmap/ic_launcher_round"android:supportsRtl="true"android:theme="@style/Theme.JNIWriteFile"android:requestLegacyExternalStorage="true"tools:targetApi="31"><activityandroid:name=".MainActivity"android:exported="true"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter><meta-dataandroid:name="android.app.lib_name"android:value="" /></activity></application></manifest>

以下Java代码是在应用启动时开启弹窗让用户确认开启权限。


@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);verifyStoragePermission(this);...此处省略...}private static final int REQUEST_EXTERNAL_STORAGE = 1;private static String[] PERMISSIONS_STORAGE = {"android.permission.READ_EXTERNAL_STORAGE","android.permission.WRITE_EXTERNAL_STORAGE"};public void verifyStoragePermission(Activity activity){try{int permission = ActivityCompat.checkSelfPermission(activity,"android.permission.WRITE_EXTERNAL_STORAGE");if(permission!= PackageManager.PERMISSION_GRANTED){ActivityCompat.requestPermissions(activity,PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);}}catch (Exception e){e.printStackTrace();e.printStackTrace();}}

创建文件夹

mkdir函数需要包括头文件:#include <sys/stat.h>,参考CSDN: 文件编程:创建目录mkdir()函数,具体C代码如下:

//方便用日志查看#define LOG_D(...)  __android_log_print(ANDROID_LOG_DEBUG, "jni", __VA_ARGS__)...
省略
...int errNum = 0;if(0 == access(WriteFileFolder,0)) {//目录存在} else{if(0 == mkdir(WriteFileFolder,777)) {}else {LOG_D("open fail errno = %d, reason = %s", errNum, strerror(errNum));}}
...

访问 /storage/emulated/0/

/storage/emulated/0/是可以通过Android手机文件应用/文件浏览器进行访问的。
首先,需要获取获取手机内部存储卡的根目录,Java代码获取比较方便,这里使用Android ndk来获取。
参考CSDN: Android ndk获取手机内部存储卡的根目录 和 CSDN: Android Native APP开发笔记:文件存储与访问 ,代码如下:

    //get the external file directoryjclass envcls = env->FindClass("android/os/Environment"); //获得类引用if (envcls == nullptr) return 0;//找到对应的类,该类是静态的返回值是FilejmethodID id = env->GetStaticMethodID(envcls, "getExternalStorageDirectory", "()Ljava/io/File;");//调用上述id获得的方法,返回对象即File file=Enviroment.getExternalStorageDirectory()//其实就是通过Enviroment调用 getExternalStorageDirectory()jobject fileObj = env->CallStaticObjectMethod(envcls,id);//通过上述方法返回的对象创建一个引用即File对象jclass flieClass = env->GetObjectClass(fileObj); //或得类引用//在调用File对象的getPath()方法获取该方法的ID,返回值为String 参数为空jmethodID getpathId = env->GetMethodID(flieClass, "getPath", "()Ljava/lang/String;");//调用该方法及最终获得存储卡的根目录jstring pathStr = (jstring)env->CallObjectMethod(fileObj,getpathId);const char* pathStrC = env->GetStringUTFChars(pathStr,NULL);char WriteFileFolder[100];sprintf(WriteFileFolder, "%s/DocumentTest", pathStrC);

以下代码实现了在前面创建的 /storage/emulated/0/DocumentTest目录下创建5个文件,目录是放在以上所获取的变量WriteFileFolder里的,文件名以JohnTest开头,以时间戳来命名的TXT文件,创建文件后写入This is test to write to file! Timestamp:并加上时间戳。

FILE *dumpFile = NULL;for (int j = 0; j < 5; j++) {time_t currentTime;struct tm *sCurrentTime;time(&currentTime); /*获取time_t类型当前时间*/LOG_D("Current time = %s", ctime(&currentTime));putenv("TZ=Asia/Singapore");//sCurrentTime = gmtime(&currentTime);sCurrentTime = localtime(&currentTime);char dumpfileName[100];sprintf(dumpfileName, "%s/JohnTest%04d%02d%02d%02d%02d%02d.txt",WriteFileFolder,sCurrentTime->tm_year + 1900,sCurrentTime->tm_mon + 1,sCurrentTime->tm_mday,sCurrentTime->tm_hour,sCurrentTime->tm_min,sCurrentTime->tm_sec);dumpFile = fopen(dumpfileName, "w+");char rpucData[100];sprintf(rpucData, "This is test to write to file! Timestamp: %s", ctime(&currentTime));if (dumpFile == NULL) {int errNum = 0;errNum = errno;LOG_D("open fail errno = %d, reason = %s", errNum, strerror(errNum));} else {fwrite(rpucData, sizeof(char), (unsigned) strlen(rpucData), dumpFile);fclose(dumpFile);}}

程序运行后会在相应的目录里写入5个TXT文件,并写入相应的内容。

访问/data/data/example.jniwritefile/

访问/data/data/example.jniwritefile/ 并不需要申请权限,类似以上程序,只需要进行以下修改:

...
省略
...sprintf(dumpfileName, "/data/data/example.jniwritefile/JohnTest%04d%02d%02d%02d%02d%02d.txt",sCurrentTime->tm_year + 1900,sCurrentTime->tm_mon + 1,sCurrentTime->tm_mday,sCurrentTime->tm_hour,sCurrentTime->tm_min,sCurrentTime->tm_sec);dumpFile = fopen(dumpfileName, "w+");

时间戳

有关时间戳的问题可以参考CSDN: C语言应用(1)——Unix时间戳和北京时间的相互转换 , cppreference.com: gmtime, gmtime_r, gmtime_s 和 CSDN: c++ 时间类型详解 time_t

这里使用了localtime函数,注意localtimegmtime的时差,例如新加坡/北京时间与GMT时间隔了8个小时。

        putenv("TZ=Asia/Singapore");//sCurrentTime = gmtime(&currentTime);sCurrentTime = localtime(&currentTime);

Can’t determine type for tag

参考Can’t determine type for tag macro name=“m3_comp_assist_chip_container_shape”>?attr/shapeAppearanceCornerSmall
这个问题在build.gradle(:app)里通过修改几个版本号解决,我使用了以下版本:

dependencies {implementation 'androidx.appcompat:appcompat:1.4.0'implementation 'com.google.android.material:material:1.6.0'implementation 'androidx.constraintlayout:constraintlayout:2.1.4'testImplementation 'junit:junit:4.13.2'androidTestImplementation 'androidx.test.ext:junit:1.1.3'androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}

参考

C library function - fopen()
CSDN: android通过JNI用C/C++创建本地文件
CSDN: android studio 3.2 使用jni
CSDN Android JNI读取本地文件和读取文件并且写入其他文件
Stackoverflow: Android NDK fopen returns error 2 “No such file or directory” on a file I know exits
Stackoverlfow: Write file to location other than SDcard using Android NDK?
Stackoverlfow: File Operations in Android NDK
CSDN: Android Native APP开发笔记:文件存储与访问
Add C and C++ code to your project
Can’t determine type for tag macro name=“m3_comp_assist_chip_container_shape”>?attr/shapeAppearanceCornerSmall
CSDN: c++ 时间类型详解 time_t
cppreference.com: gmtime, gmtime_r, gmtime_s
CSDN: Android文件读写权限 fopen errno=13
CSDN: C语言应用(1)——Unix时间戳和北京时间的相互转换
CSDN: Android ndk获取手机内部存储卡的根目录
CSDN: 文件编程:创建目录mkdir()函数

http://www.15wanjia.com/news/175811.html

相关文章:

  • 如何做企业网站宣传手机版app制作软件
  • pta编程网站.net 接单网站有哪些
  • 做木工网站网站建设 兼职 外包
  • 百度地图网站开发网站建设月流量
  • 曹县住房和城乡建设部网站网站建设便宜
  • asp网站 攻击福州网站建设企业哪家好?
  • 轮网站开发的重要性专业网站开发多少钱
  • 南京专业网站设计哪个品牌深圳网站建设-猴王网络
  • 宿州住房和城乡建设局网站优书网有官方app吗
  • 网站开发案例详解 源代码个人可以建立网站吗
  • 网站建设实际总结沙坪坝集团网站建设
  • 网站网页怎么做做图的模板下载网站有哪些
  • 好的免费博客网站网站调用微信数据
  • 网站建设預算有哪些网站系统
  • 手机网站开发的目的合肥教育网站建设
  • 湖口县建站公司wordpress主题在线编辑器
  • 温州平台网站建设百度快速排名培训
  • 小程序怎么制作网站济南酷火网站建设
  • 给企业做网站的公司西安100个网页设计模板
  • 企业个性化网站建设费用设计平台属性
  • 学习网站模板wordpress上传图片时发生了错误
  • 嘉祥网站建设哪家好网站开发用怎么语言
  • 网站基站的建设wap浏览器手机版下载
  • 重庆网站网页设计培训机构做积分网站
  • 深圳专业建站平台青岛网站建设详细内容
  • 藁城网站建设手机软件下载平台
  • 企业营销网站wordpress管理后台没有登陆
  • 网站后台改wordpress 添加外观
  • wordpress 自动水印外贸网站seo
  • 威海建设公司网站建设银行网站用户权限