zoukankan      html  css  js  c++  java
  • Android4.4中不能发送SD卡就绪广播

    当在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卡,所以会抛题目异常。

    解决方法有两种方式:
    第一种:

    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广播通知系统。

    我建议使用上面那种方式,上面那种方式简单明了!!

  • 相关阅读:
    【python小随笔】单例模式设计(易懂版)
    【python小随笔】函数的初始化与私有化
    【python小随笔】List列表的常见函数与切片
    【itsdangerous】的加密解密原理(易懂版)
    【Django入坑之路】Django后台上传图片,以及前端的显示
    【插拔式】分页+bootstrap4(开源)
    luogu P1231 教辅的组成 |网络流最大匹配
    luogu P3376 【模板】网络最大流 |Dinic
    luogu P4177 [CEOI2008]order |最大权闭合子图
    luogu P4562 [JXOI2018]游戏 |组合数学
  • 原文地址:https://www.cnblogs.com/DarrenChan/p/5631687.html
Copyright © 2011-2022 走看看