Android4.4拒绝发送扫描SD卡的广播

作者:燕潇洒

导读: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", "图片已保存");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值