我們經常需要向客戶提供開發用的jar包和so文件,那么能不能將二者打包在一起呢,答案是可以。
首先我們需要將資源文件(包括so文件、配置文件以及其他資源等)放入assets文件夾下,然后在代碼中,將他們復制到指定路徑,並手動加載對應的so文件。
我的資源文件樹結構如下:
詳細的代碼如下:
1 public static boolean init(Context mContext) 2 { 3 initAssetsFile(mContext,"armeabi"); 4 System.load(mContext.getFilesDir() + "/armeabi/"+"libjypri.so"); 5 System.load(mContext.getFilesDir() + "/armeabi/"+"libwltdecode.so"); 6 7 initAssetsFile(mContext, "wltlib"); 8 if (0 == IDCReaderSDK.wltInit(mContext.getFilesDir() + "/wltlib")) { 9 Log.e(TAG, "wltInit success"); 10 return true; 11 } else { 12 Log.e(TAG, "wltInit failed"); 13 return false; 14 } 15 } 16 17 private static void initAssetsFile(Context context,String dir) 18 { 19 Log.e(TAG, "initAssetsFile"); 20 21 boolean needCopy = false; 22 23 // 創建data/data目錄 24 File file = context.getFilesDir(); 25 String path = file.toString() + "/"+dir+"/"; 26 27 // 遍歷assets目錄下所有的文件,是否在data/data目錄下都已經存在 28 try { 29 String[] fileNames = context.getAssets().list(dir); 30 for (int i = 0; fileNames != null && i < fileNames.length; i++) { 31 if (!new File(path + fileNames[i]).exists()) { 32 needCopy = true; 33 break; 34 } 35 } 36 37 } catch (IOException e) { 38 e.printStackTrace(); 39 } 40 41 if (needCopy) { 42 copyFilesFassets(context, dir, path); 43 } 44 } 45 46 //將舊目錄中的文件全部復制到新目錄 47 private static void copyFilesFassets(Context context, String oldPath, String newPath) { 48 49 Log.e("copyFilesFassets", oldPath+" -> "+newPath); 50 try { 51 52 // 獲取assets目錄下的所有文件及目錄名 53 String fileNames[] = context.getAssets().list(oldPath); 54 55 // 如果是目錄名,則將重復調用方法遞歸地將所有文件 56 if (fileNames.length > 0) { 57 File file = new File(newPath); 58 file.mkdirs(); 59 for (String fileName : fileNames) { 60 copyFilesFassets(context, oldPath + "/" + fileName, newPath + "/" + fileName); 61 } 62 } 63 // 如果是文件,則循環從輸入流讀取字節寫入 64 else { 65 InputStream is = context.getAssets().open(oldPath); 66 FileOutputStream fos = new FileOutputStream(new File(newPath)); 67 byte[] buffer = new byte[1024]; 68 int byteCount = 0; 69 while ((byteCount = is.read(buffer)) != -1) { 70 fos.write(buffer, 0, byteCount); 71 } 72 fos.flush(); 73 is.close(); 74 fos.close(); 75 } 76 } catch (Exception e) { 77 // TODO Auto-generated catch block 78 e.printStackTrace(); 79 } 80 }