当前位置: 代码迷 >> Android >> Android有关问题集锦之三十八:not allowed to send broadcast android.intent.action.MEDIA_MOUNTED
  详细解决方案

Android有关问题集锦之三十八:not allowed to send broadcast android.intent.action.MEDIA_MOUNTED

热度:244   发布时间:2016-04-28 00:57:55.0
Android问题集锦之三十八:not allowed to send broadcast android.intent.action.MEDIA_MOUNTED

当我们保存图片后就会发个通知告诉系统让sdcard重新挂载,这样其他程序就会立即找到这张图片。

            Intent intent = new Intent();            intent.setAction(Intent.ACTION_MEDIA_MOUNTED);            intent.setData(Uri.fromFile(Environment                    .getExternalStorageDirectory()));            sendBroadcast(intent);

但是到了Android4.4就不灵了,Google将MEDIA_MOUNTED的权限提高了,于是就报了一个下面的错误。

W/System.err﹕java.lang.SecurityException: Permission Denial: not allowed to send broadcast android.intent.action.MEDIA_MOUNTED from pid=18338, uid=10087

在stackoverfollow中找到了一个办法,在高版本中使用ACTION_MEDIA_SCANNER_SCAN_FILE去通知系统重新扫描文件。代码如下:

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {                    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())));                }            } catch (FileNotFoundException e) {                Log.d(TAG, "File not found: " + e.getMessage());            } catch (IOException e) {                Log.d(TAG, "Error accessing file: " + e.getMessage());            }
  相关解决方案