添加读写外部存储的权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
动态权限检查
使用的这个库:
https://github.com/Karumi/Dexter
还是挺方便的。
添加依赖
implementation 'com.karumi:dexter:5.0.0'
需要申请权限的地方:
Dexter.withActivity(getActivity())
.withPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
@Override
public void onPermissionGranted(PermissionGrantedResponse response) {
showProgressDialog();
EventBus.getDefault().post(exportEvent);
}
@Override
public void onPermissionDenied(PermissionDeniedResponse response) {
Toast.makeText(getContext(), "请打开读写文件权限", Toast.LENGTH_LONG).show();
}
@Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {/* ... */}
}).check();
获取文件路径
public String getFilePath() {
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath(), "download");
dir.mkdirs();
return dir.getAbsolutePath();
}
写文件
public void writeToSDFile(String coinType, List<AddressPair> data, String fileName) throws IOException {
FileOutputStream f = null;
try {
File file = new File(fileName);
f = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(f);
for (int i = 0; i < data.size(); i++) {
AddressPair pp = data.get(i);
pw.println(coinType + "," + pp.address);
}
pw.flush();
pw.close();
} finally {
if (f != null) {
f.close();
}
}
}