Android4.4中不能发送SD卡就绪广播
2016-07-01 00:34
316 查看
当在Android上进行图片的扫描功能开发时一般会使用:sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse(“file://”+ Environment.getExternalStorageDirectory()+ picPath)));的广播.
但是在Android4.4及以上版本中,执行上面的代码出现异常:W/ActivityManager( 498): Permission Denial: not allowed to send broadcast android.intent.action.MEDIA_MOUNTED from pid=2269, uid=20016
因为Android4.4中限制了系统应用才有权限使用广播通知系统扫描SD卡,所以会抛题目异常。
解决方法有两种方式:
第一种:
第二种方式:
上面两种方式亲测有效,说白了,在高版本中,使用MediaScannerConnection类或者ACTION_MEDIA_SCANNER_SCAN_FILE广播通知系统扫描文件夹,在低版本中使用ACTION_MEDIA_MOUNTED广播通知系统。
我建议使用上面那种方式,上面那种方式简单明了!!
但是在Android4.4及以上版本中,执行上面的代码出现异常:W/ActivityManager( 498): Permission Denial: not allowed to send broadcast android.intent.action.MEDIA_MOUNTED from pid=2269, uid=20016
因为Android4.4中限制了系统应用才有权限使用广播通知系统扫描SD卡,所以会抛题目异常。
解决方法有两种方式:
第一种:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//如果是4.4及以上版本 Intent mediaScanIntent = new Intent( Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); Uri contentUri = Uri.fromFile(mPhotoFile); //out is your output file mediaScanIntent.setData(contentUri); CameraActivity.this.sendBroadcast(mediaScanIntent); } else { sendBroadcast(new Intent( Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory()))); }
第二种方式:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // 判断SDK版本是不是4.4或者高于4.4 String[] paths = new String[]{Environment.getExternalStorageDirectory().toString()}; MediaScannerConnection.scanFile(mContext, paths, null, null); } else { final Intent intent; if (f.isDirectory()) { intent = new Intent(Intent.ACTION_MEDIA_MOUNTED); intent.setClassName("com.android.providers.media", "com.android.providers.media.MediaScannerReceiver"); intent.setData(Uri.fromFile(Environment.getExternalStorageDirectory())); } else { intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); intent.setData(Uri.fromFile(new File(path))); } mContext.sendBroadcast(intent); }
上面两种方式亲测有效,说白了,在高版本中,使用MediaScannerConnection类或者ACTION_MEDIA_SCANNER_SCAN_FILE广播通知系统扫描文件夹,在低版本中使用ACTION_MEDIA_MOUNTED广播通知系统。
我建议使用上面那种方式,上面那种方式简单明了!!
相关文章推荐
- 基于android的远程视频监控系统
- Android中的Service(使用StartService 方式启动)
- Android模拟器无法启动,报错:Cannot set up guest memory ‘android_arm’ Invalid argument的解决方法
- Android开发中的机型适配和国际化适配的实现;
- Android -- 固定在ScrollView顶部的View,类似于新浪微博的评论列表的顶部
- Xamarin Android提示找不到资源属性定义
- Android Studio获取SHA1
- IDA 调试 Android
- 【Android基础】minSdkVersion maxSdkVersion targetSdkVersion target 的区别
- 迪米特法则在Android实际开发中的运用
- 运行android项目出现error:cannot parse version string:kg01的解决方法
- Android通知栏通知
- 六步骤开发和发布自己的Android Studio类库
- 不是经常用到的回调方法
- Android之线程池
- Android 获取图片资源格式(png、jpeg、gif、bmp、...)
- APK瘦身方案
- 安卓日记——Realm快速上手
- Android LRecyclerView实现下拉刷新,滑动到底部自动加载更多
- AndroidStudio统一自己的签名文件(免手动签名)