gpt4 book ai didi

Android - WRITE_EXTERNAL_STORAGE 权限和写入应用程序日志

转载 作者:搜寻专家 更新时间:2023-11-01 08:44:43 26 4
gpt4 key购买 nike

我想要的只是能够在一个非常特定的文件夹(与我的应用程序相关)中为我的应用程序编写日志/异常报告,以便了解失败和异常,所以这是我正在使用的代码:

File logFile = new File(Environment.getExternalStorageDirectory() + File.separator + "/appname/log.txt");
if (!logFile.exists()) {
try {
if (logFile.getParentFile().mkdir()) {
if (!logFile.createNewFile())
showPopup(context.getString(R.string.app_name), "error creating log file");
}
} catch (IOException e) {
e.printStackTrace();
}
}
try {
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(text);
buf.newLine();
buf.flush();
buf.close();
} catch (IOException e) {
e.printStackTrace();
}

为了使上面的工作正常,我必须添加以下权限:android.permission.WRITE_EXTERNAL_STORAGE 但是当用户读取它时,它说读写外部存储,可以理解,这吓跑了用户。有没有更好的方法来记录我的应用程序的行为并为此使用不那么可怕的权限?

最佳答案

首先,切换自:

File logFile = new File(Environment.getExternalStorageDirectory() + File.separator + "/appname/log.txt");

到:

File logFile = new File(context.getExternalFilesDir(), "log.txt");

这不仅避免了在创建路径时手动连接字符串,而且不仅避免了用户的外部存储被随机的特定于应用程序的目录弄得乱七八糟,而且现在还意味着您可以:

<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="18" />

在 API 级别 19+ 上消除 WRITE_EXTERNAL_STORAGE

除此之外,尝试将您的 targetSdkVersion 提高到 4 或更高。引用 the docs for READ_EXTERNAL_STORAGE :

Note: If both your minSdkVersion and targetSdkVersion values are set to 3 or lower, the system implicitly grants your app this permission. If you don't need this permission, be sure your targetSdkVersion is 4 or higher.

关于Android - WRITE_EXTERNAL_STORAGE 权限和写入应用程序日志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29576912/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com