参考链接:
How to vibrate iOS and Android phones using FireMonkey and XE8 (embarcadero.com)
实测以下代码在 D10.4 社区版,OPPO 手机上运行成功。
前提:安卓系统,需要设置工程文件里面的用户权限:
需要 Vibrate 权限,在 Project - Options - UserPermissions 里面,找到 Vibrate ,勾选。
以下是全部测试代码:
unit Unit1;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
FMX.Controls.Presentation, FMX.StdCtrls
{$IFDEF ANDROID}
,Androidapi.JNI.Os,
Androidapi.JNI.GraphicsContentViewText,
Androidapi.Helpers,
Androidapi.JNIBridge
{$ENDIF}
{$IFDEF IOS}
,IOSapi.MediaPlayer, IOSapi.CoreGraphics, FMX.Platform, FMX.Platform.IOS, IOSapi.UIKit, Macapi.ObjCRuntime, Macapi.ObjectiveC, iOSapi.Cocoatypes,
Macapi.CoreFoundation, iOSapi.Foundation, iOSapi.CoreImage, iOSapi.QuartzCore, iOSapi.CoreData
{$ENDIF}
;
{$IFDEF IOS}
Const
libAudioToolbox = '/System/Library/Frameworks/AudioToolbox.framework/AudioToolbox';
kSystemSoundID_vibrate = $FFF;
Procedure AudioServicesPlaySystemSound( inSystemSoundID: integer ); Cdecl; External libAudioToolbox Name _PU + 'AudioServicesPlaySystemSound';
{$ENDIF}
type
TForm1 = class(TForm)
SpeedButton1: TSpeedButton;
procedure SpeedButton1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
procedure TForm1.SpeedButton1Click(Sender: TObject);
{$IFDEF ANDROID}
Var
Vibrator:JVibrator;
{$ENDIF}
begin
{$IFDEF ANDROID}
Vibrator:=TJVibrator.Wrap((SharedActivityContext.getSystemService(TJContext.JavaClass.VIBRATOR_SERVICE) as ILocalObject).GetObjectID);
// Vibrate for 500 milliseconds
Vibrator.vibrate(500);
{$ENDIF}
{$IFDEF IOS}
AudioServicesPlaySystemSound( kSystemSoundID_vibrate );
{$ENDIF}
end;
end.