Delphi v11 安卓权限申请

问题

Delphi 10.4 的安卓权限申请代码,在 Delphi 11 下面编译无法通过。

原因

原因是里面有几个变量类型的定义有所不同。

procedure TDmBLE.RequestPermissionsResult(Sender: TObject;  const APermissions: TArray;  const AGrantResults: TArray);

上述代码是 Delphi 10.4 的,里面有两个类型需要更改:

1. TArray 更改为:TClassicStringDynArray

2. TArray 更改为:TClassicPermissionStatusDynArray

procedure DisplayRationale(Sender: TObject; const APermissions: TArray; const APostRationaleProc: TProc);

同样,上面这个函数里面的 TArray 更改为:TClassicStringDynArray;

适用于 Delphi 11 的安卓权限动态申请的完整代码

我把代码封装到一个单独的 DataModule 里面了。这样方便在不同的项目里重复使用。

unit UDmPermissions;
// 安卓的权限申请代码 Delphi 11
interface

uses
  System.SysUtils, System.Types, System.Classes, System.Permissions, FMX.DialogService, System.UITypes;

type
  TDmPermissions = class(TDataModule)
  private
    { Private declarations }
    FGotPermission: TNotifyEvent;

    procedure RequestPermissionsResult(Sender: TObject; const APermissions: TClassicStringDynArray; const AGrantResults: TClassicPermissionStatusDynArray);
    procedure DisplayRationale(Sender: TObject; const APermissions: TClassicStringDynArray; const APostRationaleProc: TProc);

    procedure DoGotPermissions;
  public
    { Public declarations }

    property OnGotPermissions: TNotifyEvent read FGotPermission write FGotPermission;
  end;

var
  DmPermissions: TDmPermissions;

implementation

{%CLASSGROUP 'FMX.Controls.TControl'}

{$R *.dfm}

{ TDmPermissions }

procedure TDmPermissions.DisplayRationale(Sender: TObject;
  const APermissions: TClassicStringDynArray; const APostRationaleProc: TProc);
begin
  //Rationale: 理由
  TDialogService.ShowMessage('We need to be given permission to discover BLE devices',
    procedure(const AResult: TModalResult)
    begin
      APostRationaleProc;
    end)
end;

procedure TDmPermissions.DoGotPermissions;
begin
  if Assigned(FGotPermission) then FGotPermission(Self);
end;

procedure TDmPermissions.RequestPermissionsResult(Sender: TObject;
  const APermissions: TClassicStringDynArray;
  const AGrantResults: TClassicPermissionStatusDynArray);
begin
  if (Length(AGrantResults) = 1) and (AGrantResults[0] = TPermissionStatus.Granted) then
    Self.DoGotPermissions
  else
    TDialogService.ShowMessage('Cannot start BLE scan as the permission has not been granted');
end;

end.

又及:

上述代码中,DoGotPermissions 方法,用于调用这个模块的地方,当用户在申请权限的界面上通过了权限申请后,要执行的代码,通过这个事件方法调用。

你可能感兴趣的:(android,Delphi)