java.lang.SecurityException: Permission Denial: not allowed to send broadcast android.intent.action.MEDIA_MOUNTED on KitKat only

前端 未结 2 423
野性不改
野性不改 2020-11-30 04:54

I am using the DownloadManager to download images off our server and I am placing the files in the externalFilesDir.

I am send out a broadc

相关标签:
2条回答
  • 2020-11-30 05:48

    It seems that google is trying to prevent this from KITKAT.
    Looking at core/rest/AndroidManifest.xml you will notice that broadcast android.intent.action.MEDIA_MOUNTED is protected now. Which means it is a broadcast that only the system can send.

    <protected-broadcast android:name="android.intent.action.MEDIA_MOUNTED" />
    

    The following should work for all versions:

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        final Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        final Uri contentUri = Uri.fromFile(outputFile); 
        scanIntent.setData(contentUri);
        sendBroadcast(scanIntent);
    } else {
        final Intent intent = new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory()));
        sendBroadcast(intent);
    }
    

    If the above is not working try the following:

    According to this post you need another way to fix it.
    Like using MediaScannerConnection or ACTION_MEDIA_SCANNER_SCAN_FILE.

    MediaScannerConnection.scanFile(this, new String[] {
    
    file.getAbsolutePath()},
    
    null, new MediaScannerConnection.OnScanCompletedListener() {
    
    public void onScanCompleted(String path, Uri uri)
    
    {
    
    
    }
    
    });
    
    0 讨论(0)
  • 2020-11-30 05:51

    I know it's late but try this, it works in every version:

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri contentUri = Uri.fromFile(out); // out is your output file
        mediaScanIntent.setData(contentUri);
        this.sendBroadcast(mediaScanIntent);
    } else {
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
            Uri.parse("file://" + Environment.getExternalStorageDirectory())));
    }
    
    0 讨论(0)
提交回复
热议问题