遇到这个错误通常是因为没有正确设置文件路径。下面给出代码示例,可以根据自己的需要进行修改:
Uri selectedFileUri = data.getData(); String[] projection = { MediaStore.Images.Media.DATA }; Cursor cursor = getContentResolver().query(selectedFileUri, projection, null, null, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(projection[0]); String filePath = cursor.getString(columnIndex); //文件路径 cursor.close();
File file = new File(getExternalCacheDir(), "file_name"); Uri uri = FileProvider.getUriForFile(this, getPackageName() + ".provider", file); // 根据自己的包名和文件名修改 if (uri != null) { Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("application/octet-stream"); intent.putExtra(Intent.EXTRA_STREAM, uri); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); startActivity(Intent.createChooser(intent, "分享到...")); }
需要注意的是,使用FileProvider需要在AndroidManifest.xml文件中进行配置,如下所示:
配置文件file_paths.xml如下所示:
这样就可以避免文件路径错误导致'file not found”错误了。