android包的体积也是考量一个程序好坏的一个标准,为了减少包的体积,我发现so是可以进行动态加载的,我们不一定要把so放到项目之中,可以放到网上进入app后在进行加载。
我们知道传统的so加载方式,是通过System.loadLibrary()的方法加载,而系统还提供了一个System.load()的方法来加载某个地址下的so,这里的问题是这个so的路径必须是app的私有路径,不是随便文件夹的位置就可以加载so的。为此我们知道我们需要将so下载以后拷贝到app的私有目录中。
public static void loadFromSd(Context context,String SoName,File SdSo){
try {
File SoFile = null;
File dir = context.getDir("",Context.MODE_PRIVATE);
SoFile = new File(dir, SoName);
if(!SoFile.exists()) {
InputStream inputStream = new FileInputStream(SdSo);
streamToFile(SoFile,inputStream,false);
}
if(SoFile.exists()) {
System.load(SoFile.getPath());
}
} catch (Exception e){
BabytreeLog.e(e.toString());
}
public static int streamToFile(File file, InputStream is, boolean isAppend) {
try {
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file, isAppend);
byte[] buf = new byte[BUF_SIZE];
int readSize = 0;
while ((readSize = is.read(buf)) != -1)
fos.write(buf, 0, readSize);
fos.flush();
is.close();
fos.close();
return 1;
} catch (Exception e) {
BabytreeLog.e(e.toString());
}
return 0;
}
}
其实代码很简单但是坑真的不少,还有下载so的逻辑,各种检验,从本地加载的逻辑等等等。