Android从系统图库拿到文件--重命名--通知图库更新

在Android应用中,重命名文件后需要更新系统图库。由于Android 4.4以后禁止非系统应用发送ACTION_MEDIA_MOUNTED广播,解决方法是使用MediaScannerConnection扫描特定文件。例如,MediaScannerConnection.scanFile()方法可以用来扫描SD卡的DCIM目录下的文件,从而通知图库更新。
摘要由CSDN通过智能技术生成

1、调用系统图库或文件管理器


Intent intentFromGallery = new Intent();
//                                            intentFromGallery.setType("image/*,audio/*,video/*"); // 设置文件类型
											intentFromGallery.setType("*/*");
											intentFromGallery.addCategory(Intent.CATEGORY_OPENABLE);
                                            intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);
											
											
//											intentFromGallery.setAction(android.content.Intent.ACTION_VIEW);
//											File file = new File("/sdcard");
//											intentFromGallery.setDataAndType(Uri.fromFile(file), "image/*,audio/*,video/*");
                                            startActivityForResult(intentFromGallery,     1);

2、获取用户选取的文件的信息(有路径就有了一切)

File tempf = null;
				try {
					Uri uri = data.getData();//content://media/external/images/media/74984
String[] proj = { MediaStore.Images.Media.DATA };   //_data
					Cursor actualimagecursor = this.managedQuery(uri,proj,null,null,null);					
					if(actualimagecursor == null){
						ToastUtils.showToast(getApplicationContext(), "不支持该类型");
						return;
					}
					 int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);   
					  actualimagecursor.moveToFirst();   
					String img_path = actualimagecursor.getString(actual_image_column_index);  //字段索引
					tempf = new File(img_path);
				} catch (Exception e) {
					e.printStackTrace();
				}

3、拿到文件后随便展示,比如放Gridview里,如果是图片。我现在要一个重命名文件的功能


String filePathString=uploadFileBeanListTemp_imgs.get(position).getSdCardPath();
												File oldFile = new File(filePathString);
												String oldName = oldFile.getName();
												String newPath = oldFile.getParent() +File.separator + newName + oldName.substring(oldName.lastIndexOf("."));
//										boolean result = FileUtils.renameByCopy(filePathString, newPath);
										boolean result = oldFile.renameTo(new File(newPath));
												if(result){
													//oldFile.delete();
													Intent intentn = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
													File newFile = new File(newPath);
											            intentn.setData(Uri.fromFile(newFile));
											        sendBroadcast(intentn);
											        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
											        intent.setData(Uri.fromFile(oldFile));
											        sendBroadcast(intent);

有的时候会出现问题:重命名后会出现0KB的文件,删除以后,文件管理器中没有该文件,但是图库中还有该文件,但是图片大小为0


=================&

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值