Android问题(二)not allowed to send broadcast android.intent.action.MEDIA_MOUNTED

本人在音乐播放器中希望能够通过发送广播刷新歌曲列表,这里本想用Intent.ACTION_MEDIA_MOUNTED检索本机的内容。

但是报了下面的错误:

Permission Denial: not allowed to send broadcast android.intent.action.MEDIA_MOUNTED from pid=2269, uid=20016




那是因为Android4.4中限制了系统应用才有权限使用广播通知系统扫描SD卡,Google将MEDIA_MOUNTED的权限提高了。

旧代码:

Intent intent = new Intent(); 
intent.setAction(Intent.ACTION_MEDIA_MOUNTED);
intent.setData(Uri.parse("file://" + Environment.getExternalStorageDirectory()));
sendBroadcast(intent);



在高版本中使用ACTION_MEDIA_SCANNER_SCAN_FILE去通知系统重新扫描文件可以解决这个问题:
改进后的代码:

  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    Intent mediaScanIntent = new Intent(
    Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    mediaScanIntent.setData(Uri.parse("file://" +Environment.getExternalStorageDirectory()));
            sendBroadcast(mediaScanIntent);
  } else {
      Intent intent = new Intent();
        intent.setAction(Intent.ACTION_MEDIA_MOUNTED);
        intent.setData(Uri.parse("file://" + Environment.getExternalStorageDirectory()));
        sendBroadcast(intent);
                }

你可能感兴趣的:(android,音乐,Broadcast)