文件输入流在 API 级别 29 上不起作用



我有一个尝试提取 m3u 文件的方法,但它在 api 级别 29 不起作用。我在 Logcat 屏幕上收到以下错误:

2019-10-03 20:46:53.165 32591-417/? E/Google: java.io.IOException: Cleartext HTTP traffic to mysite.tk not permitted

我的方法:

@SuppressLint("StaticFieldLeak")
class _loadFile extends AsyncTask<String, Void, Boolean> {
@Override
protected void onPreExecute() {
super.onPreExecute();
spinner.setVisibility(View.VISIBLE);
}
@Override
protected Boolean doInBackground(String... strings) {
try { //new FileInputStream (new File(name)
is = new FileInputStream(new File(strings[0])); // if u r trying to open file from asstes InputStream is = getassets.open(); InputStream
M3UPlaylist playlist = parser.parseFile(is);
mAdapter.update(playlist.getPlaylistItems());
return true;
} catch (Exception e) {
Log.d("Google", "_loadFile: " + e.toString());
return false;
}
}
@Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
spinner.setVisibility(View.GONE);
}
}

编辑:

我授予了明文权限,但出现了一个新错误。

Google: _loadFile: java.io.FileNotFoundException: /storage/emulated/0/Netuptv/data.m3u: open failed: ENOENT (No such file or directory)

编辑:

我的文件路径。我认为问题就在这里。但我没有解决它的信息。

static final File DEFA = Environment.getExternalStorageDirectory();
public static final File dir = new File(DEFA.getPath() + "/Netuptv");
static final File filepath = new File(dir.getPath() + "/data.m3u");

请检查您是否将此行android:usesCleartextTraffic="true"添加到清单中。

由于文件访问 API 在 Android Q 上已弃用,我强烈建议您阅读CommaneWare的这篇文章,正如本文所述,尽量使用android:requestLegacyExternalStorage="true"来避免文件访问问题

尝试以下操作:

String fileName = "data.m3u";
File storageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES)
+ "/Netuptv");
boolean success = true;
if (!storageDir.exists()) {
success = storageDir.mkdirs();
}
if (success) {
File file = new File(storageDir,fileName);
filepath = file.getAbsolutePath();
}

在 Android 10(API 级别 29(中,文件访问被弃用,它被称为scoped storage

在 Android 11 上测试的快速但不是永久修复:

添加android:requestLegacyExternalStorage="true"

和变化

compileSdkVersion 29targetSdkVersion 29

build.gradle都达到 29

最新更新