Delphi 11.3 Android 12 接收共享文件:完整指南及代码示例
Delphi 11.3 Android 12 接收共享文件:完整指南及代码示例
在 Delphi 11.3 上接收 Android 12 共享文件需要进行一系列步骤,包括权限设置、Intent 操作、文件读取和保存等。本文将提供详细的指南和代码示例,帮助您轻松实现此功能。
1. 添加权限
首先,您需要在您的 Android 应用程序清单文件中添加以下权限:
<uses-permission android:name='android.permission.READ_EXTERNAL_STORAGE' />
<uses-permission android:name='android.permission.WRITE_EXTERNAL_STORAGE' />
2. 创建 Intent 对象
在您的 Delphi 11.3 应用程序中创建一个 TAndroidIntent 对象,并为其指定 ACTION_SEND_MULTIPLE 操作:
Intent := SharedActivity.Intent;
3. 检查数据
检查 Intent 对象中是否包含 EXTRA_STREAM 和 MIME_TYPE 数据:
if Intent.getAction.equals(TJIntent.JavaClass.ACTION_SEND_MULTIPLE) then
begin
if Intent.hasExtra(TJIntent.JavaClass.EXTRA_STREAM) and Intent.hasExtra(TJIntent.JavaClass.EXTRA_MIME_TYPES) then
begin
...
end;
end;
4. 保存文件
将 EXTRA_STREAM 数据保存为文件并将其路径存储在变量中:
Uri := Intent.getParcelableExtra(TJIntent.JavaClass.EXTRA_STREAM);
InputStream := SharedActivity.getContentResolver.openInputStream(Uri);
...
FilePath := TPath.GetDocumentsPath;
FileName := TPath.GetFileName(Uri.toString);
...
5. 获取共享文档文件夹路径
使用 TPath.GetSharedDocumentsPath 函数获取共享文档文件夹的路径:
SharedFolderPath := TPath.GetSharedDocumentsPath;
SharedFilePath := TPath.Combine(SharedFolderPath, FileName);
6. 移动文件
将接收到的文件移动到共享文档文件夹中:
OutputStream := TJFileOutputStream.JavaClass.init(StringToJString(SharedFilePath));
OutputStream.write(Bytes);
OutputStream.close;
代码示例
以下是完整的代码示例,演示了如何接收共享文件:
uses
Androidapi.JNI.GraphicsContentViewText, Androidapi.JNI.Net, Androidapi.JNI.JavaTypes,
System.IOUtils;
procedure TForm1.btnReceiveFileClick(Sender: TObject);
var
Intent: JIntent;
Uri: Jnet_Uri;
InputStream: JInputStream;
OutputStream: JOutputStream;
Bytes: TJavaArray<Byte>;
FilePath, FileName, SharedFolderPath, SharedFilePath: string;
begin
Intent := SharedActivity.Intent;
if Intent <> nil then
begin
if Intent.getAction.equals(TJIntent.JavaClass.ACTION_SEND_MULTIPLE) then
begin
if Intent.hasExtra(TJIntent.JavaClass.EXTRA_STREAM) and Intent.hasExtra(TJIntent.JavaClass.EXTRA_MIME_TYPES) then
begin
Uri := Intent.getParcelableExtra(TJIntent.JavaClass.EXTRA_STREAM);
InputStream := SharedActivity.getContentResolver.openInputStream(Uri);
SetLength(Bytes, InputStream.available);
InputStream.read(Bytes);
FilePath := TPath.GetDocumentsPath;
FileName := TPath.GetFileName(Uri.toString);
SharedFolderPath := TPath.GetSharedDocumentsPath;
SharedFilePath := TPath.Combine(SharedFolderPath, FileName);
OutputStream := TJFileOutputStream.JavaClass.init(StringToJString(SharedFilePath));
OutputStream.write(Bytes);
OutputStream.close;
ShowMessageFmt('File received and saved to %s', [SharedFilePath]);
end;
end;
end;
end;
注意
此示例仅处理接收单个文件的情况。如果您要接收多个文件,请在代码中进行适当更改。
通过遵循以上步骤和代码示例,您可以在 Delphi 11.3 上轻松实现 Android 12 共享文件的接收功能。
原文地址: https://www.cveoy.top/t/topic/n6AC 著作权归作者所有。请勿转载和采集!