我的MainActivity中有以下内容:
public void clickImage(View view) {
//fire intent
Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File fp = getFile();
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(fp));
startActivityForResult(intent, REQUEST_CHECK);
}
private File getFile() {
File folder = new File("sdcard/attendence");
if (!folder.exists()) {
folder.mkdir();
}
imgpath = new File(folder, File.separator +
Calendar.getInstance().getTime() + ".jpg");
return imgpath;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try{
s = imgpath.toString();
Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
}
catch (Exception e){
e.printStackTrace();
}
imgv1.setImageDrawable(Drawable.createFromPath(s));
}
public void sand(View view)
{
db=mdb.getWritableDatabase();
ContentValues cv =new ContentValues();
cv.put("path" ,s);
db.insert("tableimage", null, cv);
Toast.makeText(this, "Done", Toast.LENGTH_SHORT).show();
}
public void show (View view) {
String col[] = {"path"};
db = mdb.getReadableDatabase();
c = db.query("tableimage", col, null, null, null, null, null);
c.moveToLast();
imgs = c.getString(c.getColumnIndex("path"));
imgv2.setImageDrawable(Drawable.createFromPath(imgs));
}
我在清单中包含了读写外部存储空间。当我尝试获取图像时,它会给我许可错误(请参阅标题)。请帮忙。
答案 0 :(得分:2)
您需要在Marshmallow或以上的Android版本中添加运行时权限请求。这是代码:
全局声明文件:
File fp;
在获取文件之前添加运行时请求:
final int MyVersion = Build.VERSION.SDK_INT;
if (MyVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
if (!checkIfAlreadyhavePermission()) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
} else {
vfp = getFile();
}
}
checkIfAlreadyhavePermission()方法:
private boolean checkIfAlreadyhavePermission() {
int result = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
return result == PackageManager.PERMISSION_GRANTED;
}
在onRequestPermissionResult()中定义ALLOW和DENY动作:
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case 1: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
fp = getFile();
} else {
Toast.makeText(MainActivity.this, "Please give your permission.", Toast.LENGTH_LONG).show();
}
break;
}
}
}