将图像下载到图片目录时,它不会显示在库 [Xamarin 窗体] 上



我正在使用以下代码下载图像:

var webClient = new WebClient();
webClient.DownloadDataCompleted += (s, e) =>
{
    var bytes = e.Result; // get the downloaded data
                          //string documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
    string documentsPath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/" + Android.OS.Environment.DirectoryPictures + "/";
    string localFilename = img.Uri.LocalPath.Split('/').Last();
    string localPath = System.IO.Path.Combine(documentsPath, localFilename);
    File.WriteAllBytes(localPath, bytes); // writes to local storage
    Bitmap bmp = BitmapFactory.DecodeFile(localPath);
    using (var os = new FileStream(localPath, FileMode.Truncate))
    {
        bmp.Compress(Bitmap.CompressFormat.Jpeg, 95, os);
    }
};
webClient.DownloadDataAsync(img.Uri);

问题在于图像已在文件上显示,但在图库中没有显示。我在Android上跑步。

如何解决此问题?

您可以通过以下方式手动触发MediaStore更新:

var pathToPublicImage = "/storage/emulated/0/Download/stackoverflow.png";
if (Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat)
{
    MediaScannerConnection.ScanFile(this, new string[] { pathToPublicImage }, null, this);
}
else
{
    using (var file = new Java.IO.File(pathToPublicImage))
    using (var uri = Uri.FromFile(file))
    {
        SendBroadcast(new Intent(Intent.ActionMediaScannerScanFile, uri));
    }
}

MediaScannerConnection.ionscancompletedListener

public void OnScanCompleted(string path, Uri uri)
{
    Log.Debug("SO", "Media Scan Finished, Open Gallery Now");
}

Intent.ActionMediaScannerScanFile开始/终点

[BroadcastReceiver(Exported = true)]
[IntentFilter(new string[] { Intent.ActionMediaScannerStarted, Intent.ActionMediaScannerFinished })]
public class MediaUpdates : BroadcastReceiver
{
    public override void OnReceive(Context context, Intent intent)
    {
        switch (intent.Action)
        {
            case Intent.ActionMediaScannerStarted:
                Log.Debug("SO", "Media Scan Started");
                break;
            case Intent.ActionMediaScannerFinished:
                Log.Debug("SO", "Media Scan Finished, Open Gallery Now");
                break;
        }
    }
}

我建立了一个解决方案。

只使用此方法:

private void UpdateGallery()
{
    Intent mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);
    Java.IO.File file = new Java.IO.File(_path);
    Android.Net.Uri contentUri = Android.Net.Uri.FromFile(file);
    mediaScanIntent.SetData(contentUri);
    Application.Context.SendBroadcast(mediaScanIntent);
} 

最新更新