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