Android4.4中拒绝发送Intent.ACTION_MEDIA_MOUNTED扫描SD卡的广播 - Geder

来源:互联网 发布:反淘宝联盟ebrun 编辑:程序博客网 时间:2024/06/06 03:51

当在Android4.4上进行图片的扫描功能开发时一般会使用:sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory()+ picPath)));的广播

因为Android4.4中限制了系统应用才有权限使用广播通知系统扫描SD卡,所以会抛题目异常。

解决方法:使用MediaScannerConnection执行具体文件或文件夹进行扫描,核心代码如下:

try{        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {            Intent mediaScanIntent = new Intent(                    Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);            Uri contentUri = Uri.fromFile(Environment.getExternalStorageDirectory()); //指定SD卡路径            mediaScanIntent.setData(contentUri);            sendBroadcast(mediaScanIntent);        } else {            sendBroadcast(new Intent(                    Intent.ACTION_MEDIA_MOUNTED,                    Uri.parse("file://"                            + Environment.getExternalStorageDirectory())));        }}     catch(Exception e) {        e.getMessage();     } }


0 0