我试图编写一个需要保存到外部存储的程序。现在我似乎无法保存到外部存储器。
我包含了必要的许可
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
我的代码是写入外部存储的简单测试。
final Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String path = Environment.getExternalStorageDirectory() + "/Pictures/" + "test.jpg";
File file = new File(path);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
我已在模拟器和物理设备上运行此代码。在这两种情况下,我都看不到保存到图片文件夹的文件。真的需要帮助。
答案 0 :(得分:1)
自Android M +以来,您不仅需要在Manifest中请求权限,还需要在运行时请求权限
private void requestPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ) {
ActivityCompat
.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
} else {
//your permission was already granted then write to storage
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case 1:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission Granted
// here you write to the storage for the first time
} else {
// Permission Denied
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}