Einzelnen Beitrag anzeigen

Benutzerbild von jaenicke
jaenicke

Registriert seit: 10. Jun 2003
Ort: Berlin
9.963 Beiträge
 
Delphi 12 Athens
 
#5

AW: Kein TOpenDialog für Android?

  Alt 14. Mär 2025, 19:48
Das ist ein Beispiel mit einem Button und einem TImage, das ein ausgewähltes Bild anzeigt:
Delphi-Quellcode:
uses
  Androidapi.JNI.GraphicsContentViewText, Androidapi.Helpers, Androidapi.JNI.Net,
  Androidapi.JNI.App, Androidapi.JNI.JavaTypes, Androidapi.JNIBridge, System.Messaging;

procedure OpenAndroidFileDialog;
var
  Intent: JIntent;
begin
  Intent := TJIntent.Create;
  Intent.setType(StringToJString('*/*')); // image/* für Bilder
  Intent.setAction(TJIntent.JavaClass.ACTION_GET_CONTENT);
  TAndroidHelper.Activity.startActivityForResult(Intent, 0);
end;

procedure TForm286.FormCreate(Sender: TObject);
begin
  TMessageManager.DefaultManager.SubscribeToMessage(TMessageResultNotification, HandleActivityMessage);
end;

function OpenFileViaContentResolver(Uri: Jnet_Uri): JInputStream;
begin
  Result := nil;
  if Uri <> nil then
  begin
    Result := TAndroidHelper.Context.getContentResolver.openInputStream(Uri);
    if Result = nil then
      ShowMessage('Konnte die Datei nicht öffnen.');
  end;
end;

function JInputStreamToMemoryStream(InputStream: JInputStream): TMemoryStream;
var
  Buffer: TJavaArray<Byte>;
  BytesRead: Integer;
begin
  Result := TMemoryStream.Create;

  Buffer := TJavaArray<Byte>.Create(1024);
  repeat
    BytesRead := InputStream.read(Buffer, 0, Buffer.Length);
    if BytesRead > 0 then
      Result.Write(Buffer.Data^, BytesRead);
  until BytesRead <= 0;

  Result.Position := 0;
end;

procedure TForm286.ShowImageFromUri(Uri: Jnet_Uri);
var
  InputStream: JInputStream;
  Bitmap: TBitmap;
  BitmapStream: TMemoryStream;
begin
  InputStream := OpenFileViaContentResolver(Uri);

  if InputStream <> nil then
  begin
    BitmapStream := JInputStreamToMemoryStream(InputStream);

    try
      Bitmap := TBitmap.Create;
      try
        Bitmap.LoadFromStream(BitmapStream);
        Image1.Bitmap.Assign(Bitmap);
      finally
        Bitmap.Free;
      end;
    finally
      BitmapStream.Free;
    end;
  end
  else
    ShowMessage('Fehler: Bild konnte nicht geöffnet werden.');
end;

procedure TForm286.HandleActivityMessage(const Sender: TObject; const M: TMessage);
var
  IntentData: JIntent;
begin
  if M is TMessageResultNotification then
  begin
    if TMessageResultNotification(M).ResultCode = TJActivity.JavaClass.RESULT_OK then
    begin
      IntentData := JIntent(TMessageResultNotification(M).Value);
      if Assigned(IntentData) then
        ShowImageFromUri(IntentData.getData);
    end;
  end;
end;

procedure TForm286.Button1Click(Sender: TObject);
begin
  OpenAndroidFileDialog;
end;
Sebastian Jänicke
AppCentral
  Mit Zitat antworten Zitat