Delphi XE10 Android开发笔记整理

### 1. 字符串转换与路径处理
- **JStringToString、StringToJString、StrToJURI**:在XE6中不支持这些函数,需要使用`Androidapi.Helpers`单元。

### 2. Splash Image设置
- **问题**:Delphi XE5、XE6、XE7编译的程序在Android下启动时会有一段时间的黑屏。
- **解决方案**:Delphi XE7增加了Splash Image显示功能。
  - **步骤**:
    1. 右键点击工程,选择Options。
    2. 进入Application分页。
    3. 勾选Include Splash Image。
    4. 选择Splash Image文件。
    5. 设置Splash Tile Mode和Splash Gravity。
  - **Splash Tile Mode**:
    - `disabled`:按图片尺寸大小显示,位置由Splash Gravity设置。
    - `clamp`:图形边框适应屏幕大小。
    - `repeat`:屏幕水平、竖立方向重复填充满Splash Image。
    - `mirror`:与repeat类似,图片是镜像的。
  - **Gravity**:设置比屏幕小的图片在屏幕中的位置,仅当Splash Tile Mode为Disable时有效。

### 3. 带文件发布
- **步骤**:
  1. 菜单 `project -> deployment`。
  2. 点击增加按钮,选择sqlite数据文件(如test.s3db)。
  3. 设置remote path为`assets\internal\`。

### 4. 应用显示中文名
- **步骤**:
  1. 菜单 `project -> Option -> Version Info -> label`。

### 5. FMX.Consts汉化
- **步骤**:修改FMX.Consts单元中的字符串常量,例如将`SMsgDlgWarning`从`'Warning'`改为`'警告'`。

### 6. 临时文件路径(支持安卓、IOS)
- **代码示例**:
  ```delphi
  function GetFileName(const AFileName: string): string;
  begin
  {$IFDEF ANDROID}
    Result := TPath.GetTempPath + '/' + AFileName;
  {$ELSE}
    {$IFDEF IOS}
      Result := TPath.GetHomePath + '/Documents/' + AFileName;
    {$ELSE}
      Result := AFileName;
    {$ENDIF}
  {$ENDIF}
  end;
  ```

### 7. IOUtils文件说明
- **路径类**:
  - `TPath.GetTempPath`:获取临时文件夹路径。
  - `TPath.GetTempFileName`:获取一个临时文件名。
  - `TPath.GetPathRoot`:提取盘符。
  - `TPath.GetDirectoryName`:提取路径。
  - `TPath.GetFileName`:提取文件名。
  - `TPath.GetExtension`:提取扩展名。
  - `TPath.GetFileNameWithoutExtension`:提取无扩展名的文件名。
  - `TPath.ChangeExtension`:更换扩展名。
  - `TPath.DriveExists`:检查路径中的驱动器是否存在。
  - `TPath.GetFullPath`:根据相对路径给出全路径。
  - `TPath.HasExtension`:判断是否有扩展名。
  - `TPath.IsPathRooted`:判断是否是绝对路径。
  - `TPath.Combine`:结合路径。
  - `TPath.GetRandomFileName`:产生一个随机文件名。
  - `TPath.GetGUIDFileName`:用于产生一个唯一的文件名。
  - `TPath.IsValidPathChar`:判断给定的字符是否能用于路径名。
  - `TPath.IsValidFileNameChar`:判断给定的字符是否能用于文件名。
  - `TPath.AltDirectorySeparatorChar`:Windows下是`\`。
  - `TPath.ExtensionSeparatorChar`:Windows下是`.`。
  - `TPath.PathSeparator`:Windows下是`;`。
  - `TPath.VolumeSeparatorChar`:Windows下是`:`。

- **目录类**:
  - `TDirectory.CreateDirectory`:建立新目录。
  - `TDirectory.Exists`:判断文件夹是否存在。
  - `TDirectory.IsEmpty`:判断文件夹是否为空。
  - `TDirectory.Copy`:复制文件夹。
  - `TDirectory.Move`:移动文件夹。
  - `TDirectory.Delete`:删除文件夹。
  - `TDirectory.GetDirectoryRoot`:获取目录的根盘符。
  - `TDirectory.GetCurrentDirectory`:获取当前目录。
  - `TDirectory.SetCurrentDirectory`:设置当前目录。
  - `TDirectory.GetLogicalDrives`:获取驱动器列表。
  - `TDirectory.GetAttributes`:获取文件夹属性。
  - `TDirectory.SetAttributes`:设置文件夹属性。

- **文件类**:
  - `TFile.Exists`:判断指定的文件是否存在。
  - `TFile.Copy`:复制文件。
  - `TFile.Move`:移动文件。
  - `TFile.Delete`:删除文件。
  - `TFile.Replace`:替换文件。

### 8. 传感器与设备信息
- **加速传感器**:
  ```delphi
  MotionSensor1: TMotionSensor;
  MotionSensor1.Sensor(AngleAccelX、AngleAccelY、AngleAccelZ)加速度
  ```

- **方位传感器**:
  ```delphi
  OrientationSensor1: TOrientationSensor;
  OrientationSensor1.Sensor(TiltX,TiltY,TiltZ)
  ```

- **传感器管理器**:
  ```delphi
  TSensorManager传感器管理器(包含上述两种传感器, Samples\Object Pascal\Mobile Samples\Device Sensors and Services\SensorInfo)
  ```

### 9. 标准事件与动作
- **TActionList组件**:可以添加标准事件(New Standard Action)。
  - `TakePhotoFromCameraAction1`:通过手机摄像头获取图片。
  - `TakePhotoFromLibraryAction1`:获取手机已存在图片。
  - `ShowShareSheetAction1`:用其它程序分享图片。

### 10. 麦克风与媒体播放器
- **麦克风**:
  ```delphi
  FMicrophone: TAudioCaptureDevice;
  FMicrophone := TCaptureDeviceManager.Current.DefaultAudioCaptureDevice;
  FMicrophone.FileName 设置路径
  FMicrophone.State = TCaptureDeviceState.Capturing 设备状态
  FMicrophone.StartCapture; //开始录音
  FMicrophone.StopCapture ; // 结束录音
  ```

- **媒体播放器**:
  ```delphi
  MediaPlayer: TMediaPlayer;
  MediaPlayer.FileName 设置路径
  MediaPlayer.Play ; // 开始播放
  MediaPlayer.Stop ; // 结束播放
  ```

### 11. 摄像头与设备信息
- **摄像头**:
  ```delphi
  Camera: TCameraComponent;
  Camera.Active := True ; //打开
  Camera.Active := False ; //停止
  Camera.SampleBufferToBitmap(imgCameraView.Bitmap, True); //保存图片
  TThread.Synchronize(TThread.CurrentThread, GetImage); //线程保存图片
  Camera.Quality 图像质量
  Camera.HasFlash 是否有闪光灯
  Camera.TorchMode := TTorchMode.ModeOn; //打开闪光灯
  Camera.TorchMode := TTorchMode.ModeOff;//关闭闪光灯
  Camera.Kind := FMX.Media.TCameraKind.ckFrontCamera;//前置摄像头
  Camera.Kind := FMX.Media.TCameraKind.ckBackCamera;//后置摄像头
  ```

- **设备信息**:
  ```delphi
  lbDeviceType.Text := Format('Device Type: %s', [JStringToString(TJBuild.JavaClass.MODEL)]);
  lbOSName.Text := Format('OS Name: %s', [GetCodename(JStringToString(TJBuild_VERSION.JavaClass.RELEASE))]);
  lbOSVersion.Text := Format('OS Version: %s', [JStringToString(TJBuild_VERSION.JavaClass.RELEASE)]);
  ```

### 12. 手势识别与地理信息
- **手势识别**:
  ```delphi
  GestureManager1: TGestureManager;
  ```

- **地理信息**:
  ```delphi
  LocationSensor1: TLocationSensor;
  LocationSensor1.Active := swLocationSensorActive.IsChecked; //开始
  NewLocation.Latitude //经度
  NewLocation.Longitude  //纬度
  FGeocoder: TGeocoder;
  ```

### 13. 获取本机信息
- **代码示例**:
  ```delphi
  FMX.Android.DeviceInfo.GetInformation;
  Memo1.Lines.Add('ID:'+FMX.Android.DeviceInfo.ID);
  Memo1.Lines.Add('IMEI:'+FMX.Android.DeviceInfo.IMEI);
  Memo1.Lines.Add('User:'+FMX.Android.DeviceInfo.User);
  Memo1.Lines.Add('Host:'+FMX.Android.DeviceInfo.Host);
  Memo1.Lines.Add('Tags:'+FMX.Android.DeviceInfo.Tags);
  Memo1.Lines.Add('Time:'+FMX.Android.DeviceInfo.Time);
  Memo1.Lines.Add('AType:'+FMX.Android.DeviceInfo.AType);
  Memo1.Lines.Add('Board:'+FMX.Android.DeviceInfo.Board);
  Memo1.Lines.Add('Radio:'+FMX.Android.DeviceInfo.Radio);
  Memo1.Lines.Add('Brand:'+FMX.Android.DeviceInfo.Brand);
  Memo1.Lines.Add('Model:'+FMX.Android.DeviceInfo.Model);
  Memo1.Lines.Add('Serial:'+FMX.Android.DeviceInfo.Serial);
  Memo1.Lines.Add('Device:'+FMX.Android.DeviceInfo.Device);
  Memo1.Lines.Add('CpuABI:'+FMX.Android.DeviceInfo.CpuABI);
  Memo1.Lines.Add('CpuABI2:'+FMX.Android.DeviceInfo.CpuABI2);
  Memo1.Lines.Add('Display:'+FMX.Android.DeviceInfo.Display);
  Memo1.Lines.Add('Product:'+FMX.Android.DeviceInfo.Product);
  Memo1.Lines.Add('Hardware:'+FMX.Android.DeviceInfo.Hardware);
  Memo1.Lines.Add('Bootloader:'+FMX.Android.DeviceInfo.Bootloader);
  Memo1.Lines.Add('FingerPrint:'+FMX.Android.DeviceInfo.FingerPrint);
  Memo1.Lines.Add('Manufacturer:'+FMX.Android.DeviceInfo.Manufacturer);
  ```

### 14. 地图与浏览器
- **地图**:
  ```delphi
  MapView1: TMapView;
  ```

- **浏览器**:
  ```delphi
  WebBrowser1: TWebBrowser;
  WebBrowser1.Navigate('www.baidu.com'); //打开网页
  WebBrowser1.URL := ''; //打开网页
  WebBrowser1.GoForward; //前进
  WebBrowser1.GoBack;//后退
  ```

### 15. 对话框与消息提醒
- **对话框**:
  ```delphi
  ShowMessage、 MessageDlg、 InputQuery
  ```

- **消息提醒**:
  ```delphi
  NotificationC: TNotificationCenter;
  ```

### 16. 程序事件服务
- **代码示例**:
  ```delphi
  var
    FMXApplicationEventService: IFMXApplicationEventService;
  begin
    if TPlatformServices.Current.SupportsPlatformService (IFMXApplicationEventService, IInterface(FMXApplicationEventService)) then
      FMXApplicationEventService.SetApplicationEventHandler(HandleAppEvent)
    else
       flag := false;
  end;
  function TForm1.HandleAppEvent(AAppEvent: TApplicationEvent; AContext: TObject)   : boolean;
  begin
    if flag = false then
      exit;

    case AAppEvent of
      TApplicationEvent.aeEnteredBackground:
        begin
            //当程序后台运行了
        end;
    end;
    Result := true;
  end;
  ```

### 17. 电话信息与拨号
- **获取电话服务信息**:
  ```delphi
  PhoneDialerService: IFMXPhoneDialerService;
  ```

- **拨号**:
  ```delphi
  procedure TPhoneDialerForm.btnMakeCallClick(Sender: TObject);
  var
    PhoneDialerService: IFMXPhoneDialerService;
  begin
    if TPlatformServices.Current.SupportsPlatformService(IFMXPhoneDialerService, IInterface(PhoneDialerService)) then
    begin
      if edtTelephoneNumber.Text <> '' then
        PhoneDialerService.Call(edtTelephoneNumber.Text)
      else
      begin
        ShowMessage('Please type in a telephone number.');
        edtTelephoneNumber.SetFocus;
      end;
    end
    else
      ShowMessage('PhoneDialer service not supported');
  end;
  ```

### 18. Intent与条码扫描
- **Intent**:
  ```delphi
  procedure Call_URI(const AAction : JString; const AURI: string);
  var
    uri: Jnet_Uri;
    Intent: JIntent;
  begin
    uri := StrToJURI(AURI);
    Intent := TJIntent.JavaClass.init(AAction, uri);
    SharedActivityContext.startActivity(Intent);
  end;
  ```

- **条码扫描**:
  ```delphi
  procedure TINVMCForm.btnSCANClick(Sender: TObject);
  var
    uri: Jnet_Uri;
    Intent: JIntent;
    jstr: JString;
  begin
    uri := StrToJURI('com.google.zxing.client.android.SCAN');
    Intent := TJIntent.JavaClass.init(StringToJString('com.google.zxing.client.android.SCAN'));
    SharedActivityContext.startActivity(Intent);
  end;
  ```

### 19. 获取手机信息与振动
- **获取手机信息**:
  ```delphi
  function GetPhoneInfo(): string;
  Var
    TelephonyManager: JTelephonyManager;
    TelephonyServiceNative: JObject;
  begin
    result := '';
    TelephonyServiceNative := SharedActivityContext.getSystemService(TJContext.JavaClass.TELEPHONY_SERVICE);
    if Assigned(TelephonyServiceNative) then
      TelephonyManager := TJTelephonyManager.Wrap((TelephonyServiceNative as ILocalObject).GetObjectID);
    result := JStringToString(TelephonyManager.getLine1Number);
  end;
  ```

- **手机振动**:
  ```delphi
  procedure TForm1.Button2Click(Sender: TObject);
  function GetVibratorArray(const AintArr: array of int64): TJavaArray<int64>;
  var
    Lindex: integer;
  begin
    Result := TJavaArray<int64>.Create(Length(AintArr));
    for Lindex := Low(AintArr) to High(AintArr) do
      Result.Items[Lindex] := AintArr[Lindex];
  end;
  var
    LVibrator: JVibrator;
    LJavaArray: TJavaArray<int64>;
  begin
    LVibrator := TJVibrator.Wrap((SharedActivity.getSystemService(TJActivity.javaClass.VIBRATOR_SERVICE) as ILocalObject).GetObjectID);
    if not LVibrator.hasVibrator then
    begin
      showmessage('手机不支持震动');
      exit;
    end;
    LVibrator.vibrate(200);
    LVibrator.cancel;
    LJavaArray := GetVibratorArray([200, 1000, 3000, 5000]);
    LVibrator.vibrate(LJavaArray, -1);
    LJavaArray := GetVibratorArray([200, 1000, 3000, 5000]);
    LVibrator.vibrate(LJavaArray, 0);
  end;
  ```

### 20. 网络传送文件与蓝牙
- **网络传送文件**:
  ```delphi
  TTetheringManager|设备管理、TTetheringAppProfile|文件发送
  ```

- **蓝牙**:
  ```delphi
  System.Bluetooth单元中主要包含一下几个类
  TBluetoothManager、TBluetoothDeviceList、TBluetoothAdapter、TBluetoothDevice、TBluetoothService、
  TBluetoothServiceList、TBluetoothSocket
  ```

### 21. 其他组件与功能
- **时间选择**:
  ```delphi
  TimeEdit1: TTimeEdit;
  ```

- **横拉组件**:
  ```delphi
  HorzScrollBox1: THorzScrollBox;
  ```

- **多余视图**:
  ```delphi
  MultiView1: TMultiView;
  ```

- **企业移动服务**:
  ```delphi
  EMSProvider: TEMSProvider;
  ```

- **移动客户端数据连接组件**:
  ```delphi
  BBAS Client(组件组TKinveyProvider、TParseProvider);
  ```

- **多页**:
  ```delphi
  TabItem1: TTabItem;
  ```

### 22. 退出键不退出程序
- **代码示例**:
  ```delphi
  procedure TPForm.FormKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
  begin
    if Key = vkHardwareBack then
    begin
      {$IFDEF ANDROID}
      MessageDlg('确认退出吗?', System.UITypes.TMsgDlgType.mtInformation,
      [
        System.UITypes.TMsgDlgBtn.mbYes,
        System.UITypes.TMsgDlgBtn.mbCancel
      ], 0, System.UITypes.TMsgDlgBtn.mbCancel,
      procedure(const AResult: TModalResult)
      begin
        if AResult = mrYES then
           MainActivity.finish;
      end);
      {$ENDIF ANDROID}
      Key := 0;
      exit;
    end;
  end;
  ```

### 23. 屏幕方向设置
- **坚屏**:
  ```delphi
  Application.FormFactor.Orientations := [TFormOrientation.Landscape];
  ```

- **横屏**:
  ```delphi
  Application.FormFactor.Orientations := [TFormOrientation.Portrait];
  ```

### 24. 当前网络状态
- **代码示例**:
  ```delphi
  IsConnected|连接,IsWiFiConnected|Wifi是否连接,IsMobileConnected|移动网络是否连接
  ```

### 25. 剪贴板与键盘
- **剪贴板**:
  ```delphi
  FClipboardService: IFMXClipboardService;
  TPlatformServices.Current.SupportsPlatformService(IFMXClipboardService, IInterface(FClipboardService));
  FClipboardService.SetClipboard(Tvalue(Edit1.Text));  //复制
  FClipboardService.GetClipboard.ToString;  //粘贴
  ```

- **键盘**:
  ```delphi
  FService: IFMXVirtualKeyboardToolbarService;
  if TPlatformServices.Current.SupportsPlatformService(IFMXVirtualKeyboardToolbarService, IInterface(FService)) then
  begin
    FService.SetToolbarEnabled(true);
    FService.SetHideKeyboardButtonVisibility(true);
  end;
  ```

### 26. 添加桌面快捷方式
- **代码示例**:
  ```delphi
  procedure Tform1.Button1Click(Sender: TObject);
  {$IFDEF ANDROID}
  var
    ShortcutIntent: JIntent;
    addIntent: JIntent;
    wIconIdentifier : integer;
    wIconResource : JIntent_ShortcutIconResource;
  {$ENDIF}
  begin
  {$IFDEF ANDROID}
    ShortcutIntent := TJIntent.JavaClass.init(SharedActivityContext, SharedActivityContext.getClass);
    ShortcutIntent.setAction(TJIntent.JavaClass.ACTION_MAIN);
    addIntent := TJIntent.Create;
    addIntent.putExtra(TJIntent.JavaClass.EXTRA_SHORTCUT_INTENT, TJParcelable.Wrap((shortcutIntent as ILocalObject).GetObjectID));
    addIntent.putExtra(TJIntent.JavaClass.EXTRA_SHORTCUT_NAME, StringToJString(Application.Title));
    addIntent.setAction(StringToJString('com.android.launcher.action.INSTALL_SHORTCUT'));
    wIconIdentifier := SharedActivity.getResources.getIdentifier(StringToJString('ic_launcher'), StringToJString('drawable'), StringToJString('com.embarcadero.Project1'));
    wIconResource := TJIntent_ShortcutIconResource.JavaClass.fromContext(SharedActivityContext, wIconIdentifier);
    addIntent.putExtra(TJIntent.JavaClass.EXTRA_SHORTCUT_ICON_RESOURCE, TJParcelable.Wrap((wIconResource as ILocalObject).GetObjectID));
    SharedActivityContext.sendBroadcast(addIntent);
  {$ENDIF}
  end;
  ```

### 27. 截取屏幕图片
- **代码示例**:
  ```delphi
  function MakeScaleScreenshot(Sender: TControl): TBitmap;
  function GetScreenScale: Single;
  var
    ScreenService: IFMXScreenService;
  begin
    Result := 1;
    if TPlatformServices.Current.SupportsPlatformService(IFMXScreenService, IInterface(ScreenService)) then
    begin
      Result := ScreenService.GetScreenScale;
    end;
  end;
  var
    fScreenScale: Single;
  begin
    fScreenScale := GetScreenScale;
    Result := TBitmap.Create(Round(Sender.Width * fScreenScale), Round(Sender.Height * fScreenScale));
    Result.Clear(0);
    if Result.Canvas.BeginScene then
      try
        Sender.PaintTo(Result.Canvas, RectF(0, 0, Result.Width, Result.Height));
      finally
        Result.Canvas.EndScene;
      end;
  end;
  ```

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值