近期接到一个新需求——在设置里添加一个演示视频,思来想去,直接放在设置的apk里不太好,就决定创建一个新模块,其功能就是提供一些资源文件、降低其它应用的代码耦合。回归正题,如何将assets的资源文件复制到sdcard目录,代码不多,如下:
1、复制到sdcard目录
String fileName = "show.mp4"; //assets目录下的资源名及后缀
InputStream inputStream = context.getAssets().open(fileName);
//"/storage/emulated/0/ResProvider/video"(需要复制到那个目录下)
File file = new File(Environment.getExternalStorageDirectory().getAbsoluteFile() + "/ResProvider/video");
if (!file.exists()) { //判断一下是否存在了,避免重复复制了
Log.d(TAG, "file do not exists");
file.mkdirs(); //不存在,创建一个新的文件夹吧
//最终文件路径为:"/storage/emulated/0/ResProvider/video/show.mp4"
FileOutputStream fileOutputStream = new FileOutputStream(file + File.separator + fileName);//File.separator就是"/"
//这里开始拷贝
int len = -1;
byte[] buffer = new byte[1024];
while ((len = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, len);
}
fileOutputStream.close();//用完了,记得关闭
inputStream.close();
}
2、复制完成后,目录还需提供给其它应用
String name = "path_name"; //这个自己定义,尽量特殊一点,不然可能覆盖其它值
Settings.Global.putString(context.getContentResolver(), name, file + File.separator + fileName);
别忘了添加权限
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.1.2"
android:sharedUserId="android.uid.system">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
<application...>
</manifest>
3、其它应用如何获得这个资源路径
String name = "path_name";
Settings.Global.getString(context.getContentResolver(), name);