Android Q的第6个Beta版本已经发出,距离正式版本推出非常临近了. 笔者"有幸"提前尝到Android Q的"酸爽",特此留下此篇以给后面的攻城狮抛砖引玉.
Android Q的更新比较多,但是与我们应用层App开发者影响最大还是 Q与内存卡的恩恩怨怨; 为啥Android Q 突然要搞出这种幺蛾子了? Google 爸爸的众多理由有2个最突出对用户最友好的是:1.减少应用权限的申请2.这样可以让SdCard里面的存储空间更加整洁. 以前各种App动不动就各种在SdCard 里面新建各种文件,搞的内存卡凌乱无比. Environment.getExternalStorageDirectory() 这个用着很爽吧,对不起以后Android Q上不能用了. What ? Google你这是要闹哪样 ? Google 爸爸给出了自己相应的方案-----分区存储
简单来说以笔者的理解就是(如有错误之处还望各位看官不吝斧正) : 一个类似IOS的半吊子的沙盒. 在android Q上面每个app在 内存卡上面有个属于自己的沙盒(独立空间 -- /storage/emulated/0/Android/data/包名 ) 别的App是无法直接访问和获取该沙盒信息的.自己的App在自己的沙盒里面 读取/书写 文件IO操作是不要任何的权限的. app内存卡沙盒的根路径通过该:Context.getExternalFilesDir() 可获.同时该沙盒里面的任何信息在App卸载的时候也会被系统删除(以后安卓手机上再也不用安装那些垃圾清理软件了);那问题来了,如果想保存图片怎么办 ? 毕竟有些美好的事物我想留下来啊 ~ 恩,Google 为我们准备了公共存储空间 MediaStore ;如果一直按照Google的要求来开发,对这个应该不会陌生,只要将沙盒里面的文件保存到MedaStore中去,那么就可以长期的保存下来. 如果Android只有沙盒和公共存储空间的话那和IOS就一样了.但是安卓就是半吊子,安卓还可以间接的访问别的应用的沙盒,具体怎么做了? 恩 通过风骚的系统文件浏览器(恩 没有比这个更垃圾的). 好了下面我们依次来说说这三种类型的存储空间怎么操作.
不想那么快适配Android Q,想等等别人踩过坑了,再过去怎么办 ? 恩 ,我们有如下两种方案解决这个问题.
1.设置 targetSdkVersion < 29
2.如果 targetSdkVersion >=29,请在manifest中 application标签中 添加android:requestLegacyExternalStorage=“true”;默认是false
上面两种方案随便一种,都可以让App 在Android Q的系统上 分区存储 方案失效,进而到达延缓app适配 Android Q的时间.
一. 访问自己的沙盒空间.
private void createFile(){
/** /storage/emulated/0/Android/data/com.androidqtest/files/Documents/test.txt */
String filePath = this.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS)+"/test.txt";
File file =new File(filePath);
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
在自己应用的沙盒里面 增删改查 文件不需要任何权限 ;也可以对File进行任何操作.
二.MediaStore中的资源.
1.读取MediaStore中的视频文件
private void readMediaStoreVideos(){
String [] selectItems = new String[]{
MediaStore.Video.VideoColumns.DATA, //file path
MediaStore.Video.VideoColumns.SIZE, //file size
MediaStore.Video.VideoColumns.DISPLAY_NAME //file name
};
Cursor cursor=this.getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,selectItems,null,null,null);
if(cursor!=null){
while (cursor.moveToNext()){
/** /storage/emulated/0/Movies/test.mp4 **/
String path =cursor.getString(cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA));
// ...
}
}
if(cursor!=null){
cursor.close();
}
}
其中获取的path路径是绝对路径,可以使用File类进行IO操作.
2.向MediaStore中插入视频文件.
public static ContentValues getVideoContentValues(Context paramContext, File paramFile, long paramLong) {
ContentValues localContentValues = new ContentValues();
localContentValues.put("title", paramFile.getName());
localContentValues.put("_display_name", paramFile.getName());
localContentValues.put("mime_type", "video/3gp");
localContentValues.put("datetaken", Long.valueOf(paramLong));
localContentValues.put("date_modified", Long.valueOf(paramLong));
localContentValues.put("date_added", Long.valueOf(paramLong));
localContentValues.put("_data", paramFile.getAbsolutePath());
localContentValues.put("_size", Long.valueOf(paramFile.length()));
return localContentValues;
}
private void insertImageToMediaStoreVideo(){
String filePath = this.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS)+"/videoTest.mp4";
ContentResolver localContentResolver = this.getContentResolver();
ContentValues localContentValues = getVideoContentValues(this,new File(filePath), System.currentTimeMillis());
Uri localUri = localContentResolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, localContentValues);
try {
InputStream is = new FileInputStream(new File(filePath));
OutputStream os = getContentResolver().openOutputStream(localUri);
byte[] buffer = new byte[4096]; // tweaking this number may increase performance
int len;
while ((len = is.read(buffer)) != -1){
os.write(buffer, 0, len);
}
os.flush();
is.close();
os.close();
} catch (Exception e) {
}
/** it works when over android 4.3 **/
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, localUri));
}
以上介绍的对MediaStore中的资源读取和插入的方法是通用的;音频,视频,图片,都可以通过这样做. 相信读者你一定有个疑问?为何插入完成后还要进行IO操作,将资源拷贝到Movies中去? 恩,如果进行MediaStore的插入操作不进行拷贝操作的话,当你广播结束后打开系统相册你会发现,图片或者视频是黑色的一块矩形封面哈~ 原因就是系统在相应的公共资源目录下面找不相应的资源.所以记得MediaStore插入成功后一定要根据成功后返回的Uri进行IO操作.
对于图片也有简单的api可以操作,该api内部会进行拷贝操作,如下:
private void insertImageToMediaStore(){
String filePath = this.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS)+"/test.jpg";
try {
/** copy the picture into MediaStore return path of MediaStore **/
String mediaPath = MediaStore.Images.Media.insertImage(this.getContentResolver(),filePath,"test","one");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
三.其他应用沙盒中数据的获取
比如获取SdCard中根目录的资源. 如下调用该代码打开系统文件浏览器.
public void openSystemFileFilter() {
// ACTION_OPEN_DOCUMENT is the intent to choose a file via the system's file
// browser.
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
// Filter to only show results that can be "opened", such as a
// file (as opposed to a list of contacts or timezones)
intent.addCategory(Intent.CATEGORY_OPENABLE);
/** add it if you want to select multiple files **/
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
// Filter to show only images, using the image MIME data type.
// If one wanted to search for ogg vorbis files, the type would be "audio/ogg".
// To search for all documents available via installed storage providers,
// it would be "*/*".
intent.setType("*/*");
startActivityForResult(intent,66);
}
如下图,系统文件夹比较丑.
选择完成之后,数据会从onActivityResult中回调回来.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(null!=data){
/** if single file **/
Uri uri = data.getData();
/** if multiple files **/
ClipData datas=data.getClipData();
if(datas!=null){
for(int i=0;i<datas.getItemCount();i++){
Uri itemUri = datas.getItemAt(i).getUri();
}
}
/** if you want get fd **/
try {
ParcelFileDescriptor parcelFileDescriptor=MainActivity.this.getContentResolver().openFileDescriptor(uri,"r");
int fd = parcelFileDescriptor.detachFd();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
如果是单个文件的话直接从Intent中getData获取Uri,如果是选择多个的话,通过Intent的getClipData获得多个Uri值.系统文件浏览器比较垃圾一次只能选择一个文件夹中的所有非文件夹的纯文件(不能递归选择,垃圾).还通过Intent传值,嘿嘿 有经验的攻城狮是不是嗅到危险的味道.没错当数值过大的时候(多选,选的文件较多) Intent就会抛出异常 : TransactionTooLargeException ,有人会说既然都能拿到Uri那我转化为url 然后构建File,然后通过File结构,list不行么? 首先内存卡中这时File你可以构建成功 exist也是true,但是你却无法对这些File进行IO操作,这就是Android Q的风骚之处, 那如何进行操作了? 如下通过ContentResolver:
InputStream myInput;
OutputStream myOutput;
ParcelFileDescriptor parcelFileDescriptor =null;
try {
parcelFileDescriptor =FaceGroupApplication.getInstance().getContentResolver().openFileDescriptor(inputUri,"r");
if(parcelFileDescriptor!=null) {
myInput = new FileInputStream(parcelFileDescriptor.getFileDescriptor());
myOutput = new FileOutputStream(output);
byte[] buffer = new byte[10240]; // 10KB
int length = myInput.read(buffer);
while (length > 0) {
myOutput.write(buffer, 0, length);
length = myInput.read(buffer);
}
myOutput.flush();
myInput.close();
myOutput.close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(parcelFileDescriptor!=null){
try {
parcelFileDescriptor.close();
} catch (IOException e) {
e.printStackTrace();
}
parcelFileDescriptor=null;
}
}
ParcelFileDescriptor 具有一次性,用完记得close;然后再次用,需ContentResolver打开使用.当然那种detachFd的可以不用管了.
同样android Q上面会使用IO操作的api都重载了支持FileDescriptor的接口,例如:
parcelFileDescriptor =Context.getContentResolver().openFileDescriptor(inputUri,"r");
fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);
四.小结
1. 沙盒和MediaStore中的资源可以随意进行File的IO操作和访问,一如以前android上的存储策略.
2.其他沙盒里面的资源,通过系统文件浏览器获取访问的Uri,然后ContentResolver解析进行IO;切记不要直接用File结构进行IO操作.
五.问题
通过上面的分析,我们已然知道Sdcard中其他沙盒中的资源无法用其绝对路径进行访问.那很多的第三方 C/C++ 库,需要使用路径该肿么搞? ( 比如 著名的音视频框架 FFmepg 需要视频绝对路径才可以打开视频 初始化 FormatContext ).
解决方案如下:
1.其他沙盒中的资源插入MediaStore或者拷贝到自己的沙盒中,这样绝对路径的访问方式就可以使用了.
2.使用Fd的方式,将fd值传入底层,然后底层直接通过fd的值进行资源内容的访问.(比如 FFmpeg 就是通过自定义AvioContext .进而绕过传入路径的方案,从fd中读取视频内容,下一篇将着重介此方案).
六.关于我
这是我的个人技术公众号(CodeEngine),以后的技术文章会在上面推出,方便看官地跌上打发时间.(欢迎大家扫描下方二维码)