android代码删除sd卡文件,如何从SD卡中删除文件?

对Android4.4+的更改

应用程序是不允许到写 (删除、修改.)到外部储物除向他们包专用目录。

正如Android文档所述:“不得允许应用程序写入辅助外部存储设备,除非在它们的包特定目录中写入被合成的权限所允许的目录。”

不过肮脏的解决办法存在(见下文代码)..在三星GalaxyS4上进行了测试,但这种修复并不适用于所有设备。也是我不会指望此解决方案可在未来安卓版本。

你能读懂更多关于如何解决的问题..解决方案源代码来自本站.public class MediaFileFunctions {

@TargetApi(Build.VERSION_CODES.HONEYCOMB)

public static boolean deleteViaContentProvider(Context context, String fullname)

{

Uri uri=getFileUri(context,fullname);

if (uri==null)

{

return false;

}

try

{

ContentResolver resolver=context.getContentResolver();

// change type to image, otherwise nothing will be deleted

ContentValues contentValues = new ContentValues();

int media_type = 1;

contentValues.put("media_type", media_type);

resolver.update(uri, contentValues, null, null);

return resolver.delete(uri, null, null) > 0;

}

catch (Throwable e)

{

return false;

}

}

@TargetApi(Build.VERSION_CODES.HONEYCOMB)

private static Uri getFileUri(Context context, String fullname)

{

// Note: check outside this class whether the OS version is >= 11

Uri uri = null;

Cursor cursor = null;

ContentResolver contentResolver = null;

try

{

contentResolver=context.getContentResolver();

if (contentResolver == null)

return null;

uri=MediaStore.Files.getContentUri("external");

String[] projection = new String[2];

projection[0] = "_id";

projection[1] = "_data";

String selection = "_data = ? ";    // this avoids SQL injection

String[] selectionParams = new String[1];

selectionParams[0] = fullname;

String sortOrder = "_id";

cursor=contentResolver.query(uri, projection, selection, selectionParams, sortOrder);

if (cursor!=null)

{

try

{

if (cursor.getCount() > 0) // file present!

{

cursor.moveToFirst();

int dataColumn=cursor.getColumnIndex("_data");

String s = cursor.getString(dataColumn);

if (!s.equals(fullname))

return null;

int idColumn = cursor.getColumnIndex("_id");

long id = cursor.getLong(idColumn);

uri= MediaStore.Files.getContentUri("external",id);

}

else // file isn't in the media database!

{

ContentValues contentValues=new ContentValues();

contentValues.put("_data",fullname);

uri = MediaStore.Files.getContentUri("external");

uri = contentResolver.insert(uri,contentValues);

}

}

catch (Throwable e)

{

uri = null;

}

finally

{

cursor.close();

}

}

}

catch (Throwable e)

{

uri=null;

}

return uri;

} }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值