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

标签 android logging android-permissions

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

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/

相关文章:

java - 设置 Android 项目的标题

java - 使用 logback 仅存档旧日志

java - 运行时权限应该采用相同的方法。如何正确处理?

android - 为什么RECEIVE_SMS和READ_SMS权限没有不同的提示框要求权限?

c# - 将 Appium 测试结果记录到控制台

android - Android PackageManager 是否会接受声明 systemOrSignature 权限的应用程序?

android - 设置android :constantSize to 'true' in a StateListDrawable?有什么好处

android - android View 模型之间的相互通信

android - 如何将 Android 源代码附加到 Eclipse

go - 在 Golang 中测试 Log 语句输出