gpt4 book ai didi

android - 如何在不重新启动的情况下自动将保存的文件添加到目录 - Android应用程序

转载 作者:行者123 更新时间:2023-11-29 21:10:09 25 4
gpt4 key购买 nike

我已经创建了一个 Android 应用程序并使用以下方法保存文件:

File created = new File(dir, time.format("%Y%m%d%H%M%S") + "."+ suffix);

但是,即使设备连接到我的电脑,保存的文件也只会在重新启动设备后出现在指定目录中。如何在不重新启动的情况下强制显示文件?

最佳答案

使用媒体扫描仪。注意 MIME 类型,您可能需要根据您正在创建的文件更改它

MediaScannerConnection.scanFile(this.getApplicationContext(), new String[] { filename }, new String[] { "image/jpeg" }, new OnScanCompletedListener()
{
@Override
public void onScanCompleted(final String path, final Uri uri)
{
// Eureka, your file has been scanned!
}
});

这里有一些广播新文件的方法:

更新:

void alternativeScan(final String filename)
{
final File file = new File(filename);
final Uri fileUri = Uri.fromFile(file);

// New way

if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
{
this.getApplicationContext().sendBroadcast(new Intent("android.hardware.action.NEW_PICTURE", fileUri));
}

// Keep compatibility

this.getApplicationContext().sendBroadcast(new Intent("com.android.camera.NEW_PICTURE", fileUri));

// Usual way

final Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(fileUri);
this.getApplicationContext().sendBroadcast(intent);
}

如果仍然无效,请使用下一个功能检查您的媒体存储状态

public static int getMediaStorageState()
{
final String state = Environment.getExternalStorageState();

if (Environment.MEDIA_MOUNTED.equals(state))
{
return 0; // All Ok, supported Read & Write
}
else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state))
{
return 1; // Media storage has Read Only state
}
else
{
return 2; // Something's wrong. No Read/Write access
}
}

关于android - 如何在不重新启动的情况下自动将保存的文件添加到目录 - Android应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23186511/

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