gpt4 book ai didi

android-sdcard - 在 Android 4.4 上删除 SD 卡上的文件

转载 作者:行者123 更新时间:2023-12-02 03:37:45 24 4
gpt4 key购买 nike

众所周知,如果您在 Android 4.4.4 上的 SD 卡文件夹中没有包含应用程序包名称的文件,则该文件无法删除。

有什么办法可以删除这样的文件吗?

最佳答案

讨厌的解决方法存在(见下面的代码)。在 Samsung Galaxy S4 上测试,但此修复程序不适用于所有设备。此外,我不会指望此变通方法会在 future 版本的 Android 中可用。

有一个great article explaining (4.4+) external storage permissions change .

您可以阅读 more about workaround here .解决方法源代码来自 this site .

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;
}
}

关于android-sdcard - 在 Android 4.4 上删除 SD 卡上的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22307053/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com