[英]Unable to write a folder or file on to android device programmatically
我无法读取或写入我的Android设备。 在同一主题上也有类似的问题(我已经实现了代码),但是它们似乎都使我的应用程序崩溃了。
Button btnUpload = (Button) findViewById(R.id.btnUpload);
File created = new File(Environment.getExternalStorageDirectory().getPath()
+ File.separator + "MyNewFolder" + File.separator + "created");
if (created.isDirectory()) {
File[] contents = created.listFiles();
//Should not trigger as directory check is in place
if (contents == null) { //<--not adding this section causes a crash
btnUpload.setEnabled(false);
}
//Check to see if the number of files is 0
else if (contents.length == 0) {
btnUpload.setEnabled(false);
}
//All checks pass. Enable button
else {
btnUpload.setEnabled(true);
}
}
非常感谢Mike和Commonwares。
简介:除了清单文件中的权限,我们还需要在运行时检查权限(如果不存在,请请求权限)。 问题出在API级别23。
根据阅读内容添加了两行代码。 这不是最好的方法,也不是所有最佳的编码方法,而是一种快速而肮脏的解决方案,因此请进行相应的修改。
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
我已将其添加到“主要活动”的开头,以便在其余时间获得许可及其设置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.