文章目录
一、Dex 文件准备
二、外部存储空间权限申请
1、清单文件申请权限
2、动态申请权限
三、文件拷贝
1、文件拷贝
2、执行效果
四、 源码资源
一、Dex 文件准备
在 【Android 热修复】热修复原理 ( 修复包 Dex 文件准备 | Dex 优化为 Odex | Dex 文件拷贝 | 源码资源 ) 博客中 , 进行了文件拷贝简单操作 ;
将 SD 卡跟目录中的文件 /storage/emulated/0/update.dex , 拷贝到了 /data/user/0/kim.hsl.hotfix/app_odex/update.dex 目录中 ;
二、外部存储空间权限申请
1、清单文件申请权限
在 AndroidManifest.xml 清单文件中声明 SD 卡读写权限 ;
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="kim.hsl.hotfix"> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.HotFix"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
2、动态申请权限
在 MainActivity 中的 onCreate 方法中动态申请权限 : 参考 【Android 应用开发】Google 官方 EasyPermissions 权限申请库 ( 最简单用法 | 一行代码搞定权限申请 | 推荐用法 ) 博客 ;
EasyPermissions.requestPermissions( this, "权限申请原理对话框 : 描述申请权限的原理", 100, // 下面是要申请的权限 可变参数列表 Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE );
三、文件拷贝
1、文件拷贝
文件拷贝代码 , 从 SD 卡 /storage/emulated/0/update.dex ,
拷贝到应用内部存储 /data/user/0/kim.hsl.hotfix/app_odex/update.dex ;
private void hotFix() { // 拷贝的目的文件目录 // /data/user/0/kim.hsl.hotfix/app_odex/update.dex File targetDir = this.getDir("odex", Context.MODE_PRIVATE); // 拷贝的目的文件名称 String targetName = "update.dex"; // 准备目的文件, 将 Dex 文件从 SDK 卡拷贝到此文件中 String filePath = new File(targetDir, targetName).getAbsolutePath(); File file = new File(filePath); if (file.exists()) { file.delete(); } // 准备输入流, 读取 SD 卡文件 InputStream is = null; // 准备输出流, 输出到目的文件 FileOutputStream os = null; try { // 读取 SD 卡跟目录的 /storage/emulated/0/update.dex 文件 is = new FileInputStream(new File(Environment.getExternalStorageDirectory(), targetName)); // 输出到目标文件 os = new FileOutputStream(filePath); Log.i(TAG, "is : " + is + " , os : " + os + " , filePath : " + filePath + " , " + Environment.getExternalStorageDirectory()); int len = 0; byte[] buffer = new byte[1024]; while ((len = is.read(buffer)) != -1) { os.write(buffer, 0, len); } // 进行后续操作 } catch (IOException e) { e.printStackTrace(); } finally { Log.i(TAG, "is : " + is + " , os : " + os); // 关闭 IO 流 try { os.close(); is.close(); } catch (IOException e) { e.printStackTrace(); } } }
2、执行效果
在 adb shell 命令行中查看 /data/user/0/kim.hsl.hotfix/app_odex/ 目录内容 ;
四、 源码资源
源码资源 :
GitHub 地址 : https://github.com/han1202012/HotFix
CSDN 源码快照 : https://download.csdn.net/download/han1202012/16651312