作者:燕潇洒
导读:android保存图片到本地,需要发送广播扫描SD卡,在Android4.4时,Google提高了Intent.ACTION_MEDIA_MOUNTED的权限,所以在4.4以后使用这个ACTION会报错”Permission Denial: not allowed to send broadcast android.intent.action.MEDIA_MOUNTED from pid=2269, uid=20016”。因为因为Android4.4中限制了系统应用才有权限使用广播通知系统扫描SD卡
解决方案:
一.把上面的Intent.ACTION_MEDIA_MOUNTED,换成Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,Uri可以是文件夹路径,也可以文件路径.
//扫描文件
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path)));
//扫描文件夹
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); intent.setData(Uri.parse(Environment.getExternalStorageDirectory().getPath()));
context.sendBroadcast(intent);
path为图片路径!
二.使用系统的MediaScannerConnection类扫描,可以为文件夹,也可以是文件:
//扫描文件夹
String[] paths = new String[]{Environment.getExternalStorageDirectory().getPath()};
MediaScannerConnection.scanFile(mContext, paths, null, null);
//扫描文件
String[] paths = new String[]{path};
MediaScannerConnection.scanFile(context, paths, null, null);
小例子:
/**
* 保存到sd卡
*/
public File saveToSDCard() {
String filePath = Environment.getExternalStorageDirectory().getPath();
System.out.println(filePath + "保存路径");
String path = filePath + "/" + String.valueOf(System.currentTimeMillis()) + ".png";
File file = new File(path);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
} catch (Exception e) {
e.printStackTrace();
}
mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
//发送Sd卡的就绪广播,要不然在手机图库中不存在
//第一种
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.parse(Environment.getExternalStorageDirectory().getPath()));
context.sendBroadcast(intent);
//第二种
String[] paths = new String[]{path};
MediaScannerConnection.scanFile(context, paths, null, null);
Log.e("TAG", "图片已保存");
}