作者:dsafdasdfddsa_459 | 来源:互联网 | 2023-02-01 17:24
我有一个Android 7.0测试设备和我的APK目标="targetSdkVersion 22",有:
有:
final File f = new
File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + File.separator + "DressUpBaby" + photonumber + ".png");
f.createNewFile();
在这一点上,我得到警告:
W/System.err: java.io.IOException: Permission denied
如何保存文件?当我在Eclipse上创建它时,这是有效的,但是现在我已经更新并转移到Android Studio,它似乎已经破坏了一些东西.
1> fdelafuente..:
如果您在API级别23或更高级别上运行应用程序,则必须在运行时请求权限.
请求许可:
String[] permissiOns= {Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permissions, WRITE_REQUEST_CODE);
然后处理结果:
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case WRITE_REQUEST_CODE:
if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
//Granted.
}
else{
//Denied.
}
break;
}
}
有关更多信息,请访问运行时请求权限 - Android Doc
2> 小智..:
Android N引入了一种新的权限模型,该模型仅在应用程序真正需要它时才要求权限,而不是像以前那样在安装过程中要求权限。
使用以下代码请求权限
注意-还要在清单文件中添加所需的权限
如果您不是从Main Activity询问权限,请将该引用传递给上下文/活动
以下示例显示了询问写入外部存储的权限的示例,可以同时要求多个权限(不建议Google使用)。
public class MainActivity extends AppCompatActivity {
/**
* Variables for requiesting permissions, API 25+
*/
private int requestCode;
private int grantResults[];
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {if(ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED ){
//if you dont have required permissions ask for it (only required for API 23+)
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},requestCode);
onRequestPermissionsResult(requestCode,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},grantResults);
}
@Override // android recommended class to handle permissions
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.d("permission","granted");
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.uujm
Toast.makeText(MainActivity.this, "Permission denied to read your External storage", Toast.LENGTH_SHORT).show();
//app cannot function without this permission for now so close it...
onDestroy();
}
return;
}
// other 'case' line to check fosr other
// permissions this app might request
}
}