Reputation: 1341
All I want is to be able to write a log/exception report for my app inside a very specific folder (related to my app) in order to understand failures and exceptions, so this is the code I'm using:
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();
}
For the above to work, I have to add the following permissions: android.permission.WRITE_EXTERNAL_STORAGE but when the user reads it, it says both reading and writing the external storage and understandably, this is scaring away the user. Is there a better way to log my app's behavior and use a less scary permission for that?
Upvotes: 2
Views: 1537
Reputation: 1495
Try this:
File storageDir = new File(Environment.getExternalStorageDirectory(), "your folder name");
storageDir.mkdir();
Put this code to your manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Upvotes: 0
Reputation: 1007266
First, switch from:
File logFile = new File(Environment.getExternalStorageDirectory() + File.separator + "/appname/log.txt");
to:
File logFile = new File(context.getExternalFilesDir(), "log.txt");
Not only does this avoid manual string concatenation when creating your path, and not only does this stop cluttering up the user's external storage with random app-specific directories, but it now means that you can have:
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="18" />
to eliminate WRITE_EXTERNAL_STORAGE
on API Level 19+.
Beyond that, try raising your targetSdkVersion
to 4 or higher. Quoting 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.
Upvotes: 3