androidmauimaui-android

MAUI file not visible after saving until reboot on one phone, same code working on different phones


I'm developing an app in .NET 7.0 MAUI I'm mainly testing it on my phone and it works fine. I got notified about a problem with file being saved successfully (no exception thrown) but the file cannot be viewed or accessed (tried both from PC via USB and from the device via built-in file explorer). After rebooting the device file is on it's place and can be accessed. I've tested it on second phone and it also worked fine.

On the device it's not working there was no error or even warning in debug mode for this file saving segment.

My phone: Xiaomi Mi Note 10 Lite, Android 12 - working Second phone: Redmi Note 12, Android 14 - working Target device: NLS-MT37, Android 8.1 - not working

My android manifest settings:

<uses-sdk android:minSdkVersion="21" android:targetSdkVersion="31" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_MEDIA_AUDIO" />
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
<uses-permission android:name="android.permission.READ_MEDIA_VIDEO" />

Code responsible for saving file (simplified):

public async Task SaveData(){
    Log.Information("Data save initiated by user.");
    try{
        using (MemoryStream memoryStream = new MemoryStream())
        using (StreamWriter writer = new StreamWriter(memoryStream, Encoding.Default)){
            writer.WriteLine("header");
            foreach (var line in lines)
            {
                writer.WriteLine($"write line info");
            }
            writer.Flush();
            memoryStream.Seek(0, SeekOrigin.Begin);
            #if ANDROID
            string downloadsDir = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads).AbsolutePath;
            var filePath = Path.Combine(downloadsDir, fileName);
            await File.WriteAllBytesAsync(filePath, memoryStream.ToArray(), cancellationTokenSource.Token);
            await App.Current.MainPage.DisplayAlert("alert title", "alert success info", "ok");
            #endif
        }
    }catch(Exception exc) {
        //log exception and display error message
    }
}

This code is simply bind to button click. For test reason I revoked access privilege to file storage on all devices and got exception on all of them. What am I doing wrong? Is there because of some bug in older android or maybe version used in the target device? I do not own any old android phone to compare with.


Solution

  • It seems older Android was not automatically notified when file was saved. Adopted solution from here. Added this after saving file:

    var activity = Microsoft.Maui.ApplicationModel.Platform.CurrentActivity;
    (activity as MainActivity)?.ScanFile(filePath);
    

    And this method in MainActivity.cs in Android's platform directory:

    public void ScanFile(string path)
    {
        Android.Net.Uri uri = Android.Net.Uri.Parse("file://" + path);
        Android.Content.Intent scanFileIntent = new Android.Content.Intent(Android.Content.Intent.ActionMediaScannerScanFile, uri);
        Android.App.Application.Context.SendBroadcast(scanFileIntent);
    }