Delphi读取Android设备联系人

这篇文章是武稀松的原创,是在XE6下编译通过的,我尝试D10up1下重新编译,发现并无大问题。

那就搬过来分享下吧。

上代码。


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;

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

uses
  FMX.Helpers.Android,
  Androidapi.JNI.JavaTypes, Androidapi.JNI.GraphicsContentViewText,
  FMX.Platform.Android, Androidapi.JNIBridge, Androidapi.JNI.Provider,
  Androidapi.Helpers;
{$R *.fmx}

procedure QueryContact(AName: string; AList: TStrings);
var
  cursorContactsPhone: JCursor;
  selection          : string;
  projection         : TJavaObjectArray;
  FieldIndex         : Integer;
begin
  if AList <> nil then
    AList.Clear;
  projection := nil;
  if AName.Length > 0 then begin
    projection          := TJavaObjectArray.Create(1);
    projection.Items[0] := TJContacts_PeopleColumns.JavaClass.DISPLAY_NAME;
    selection           := JStringToString
      (TJContacts_PeopleColumns.JavaClass.DISPLAY_NAME) + ' LIKE "%' +
      AName + '%"';
  end;

  // select projection from 联系人数据库 where  selection
  cursorContactsPhone := SharedActivity.getContentResolver.query
    (TJCommonDataKinds_Phone.JavaClass.CONTENT_URI,
    projection { 要查询的字段名,nil的全部 } , StringToJString(selection) { Where条件 } ,
    nil { 这里是Where语句的条件参数们,我上面图方便,写死在Where条件中了,没使用参数 } , nil);
  if AList <> nil then
    while (cursorContactsPhone.moveToNext) do begin
      // 获取字段的ColumnIndex
      FieldIndex := cursorContactsPhone.getColumnIndex
        (TJContacts_PeopleColumns.JavaClass.DISPLAY_NAME);
      // 读字段内容
      AList.Add(JStringToString(cursorContactsPhone.getString(FieldIndex)));
    end;
  cursorContactsPhone.close;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  s: TStrings;
begin
  s := TStringList.Create;
  QueryContact('张', s); // 查询姓张的人
  ShowMessage(s.Text);
  s.Free;
end;
end.

别忘了Android下加上读取联系人的权限,亲测D10可用。 原文链接在此:传送门

分享到: