我正在尝试以下代码
String Data = cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.DATA));
File file = new File(Data);
if (file != null && file.exists()) {
// delete it
Toast.makeText(FileEditorDialog.this, "deleted not null",
Toast.LENGTH_LONG).show();
}
boolean deleted = file.delete();
if (deleted) {
Toast.makeText(FileEditorDialog.this,
"Successfully Deleted", Toast.LENGTH_LONG).show();
sendBroadcast(new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
Uri.parse("file://"
+ Environment.getExternalStorageDirectory())));
finish();
}
这个代码在Android果冻豆中有效,但在Android棒棒糖中无效。我们如何删除Android棒棒糖的文件?
尝试Dexter库检查权限-WRITE_EEXTERNAL_STORAGE
确保您在AndroidManifest.xml 中具有权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
这是可选的,但称为Dexter的库更容易处理即时权限。将此依赖项添加到build.gradle(应用程序)
compile 'com.karumi:dexter:2.2.2'
创建应用程序类:
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
Dexter.initialize(getApplicationContext());
}
}
并将其设置在您的AndroidManifest.xml 中
<application
android:name=".MyApplication"
使用这段代码可以请求用户权限。
Dexter.checkPermission(new PermissionListener() {
@Override public void onPermissionGranted(PermissionGrantedResponse response) {
deleteFile();//call the method to delete file
}
@Override public void onPermissionDenied(PermissionDeniedResponse response) {
Toast.makeText(getApplicationContext(), "Permission denied", Toast.LENGTH_LONG).show();
}
@Override public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
token.continuePermissionRequest();
}
}, Manifest.permission.WRITE_EXTERNAL_STORAGE);
你必须在android 6.0中从用户那里获得Runitme权限,仅仅声明它们是不够的。
在我之前对此的回答中,请查看此处的。