Search code examples
androiddelphijava-native-interface

Delphi Android JMediaScannerConnection


My app writes files into a folder on the internal (or external) SD card but those files are not seen via MTP.

I found a solution in Java to utilize MediaScannerConnection.scanfile().Androidapi.JNI.Media which contains TJMediaScannerConnection but I did not find any help on how to use it.

An example would be appreciated.


Solution

  • You can use the following code:

    use  Androidapi.Helpers, Androidapi.Jni.Media;
    

    ...

      procedure TForm1.UpdateMTP;
      var
        c: Integer;
        JMediaScannerCon: Androidapi.Jni.Media.JMediaScannerConnection;
        JMediaScannerCon_Client: Androidapi.Jni.Media.JMediaScannerConnection_MediaScannerConnectionClient;
      begin
        JMediaScannerCon:=TJMediaScannerConnection.JavaClass.init(SharedActivityContext, JMediaScannerCon_Client);
        JMediaScannerCon.connect;
        c:=0;
        while not JMediaScannerCon.isConnected do begin
          Sleep(100);
          inc(c);
          if (c>20) then break;
        end;
        if (JMediaScannerCon.isConnected) then begin
          JMediaScannerCon.scanFile(StringToJString(sYourPath), nil);
          JMediaScannerCon.disconnect;
        end;
      end);
    

    I use a polling to check if connected, a better way is to use the events of JMediaScannerCon, but I did not try it.