在Andriod程序中获取外置SD卡根目录

我们知道,Andriod是基于Linux的,所以正常的存贮设备都被挂载到/mnt目录下,我们查找SD卡根目录就是要在下面找到那个卡是外置的SD卡,但遗憾的是,目前没有一种标准的方法来做到这一点(包括Andriod本身)。下面我为大家提供了一个函数来完成这一功能:

function GetExtSDDir: String;
  var
    AList: TStringDynArray;
    S: String;
    I, J, ALastNo, ANo: Integer;
  const
    ExtSDCardNames: array [0 .. 7] of String = ('/mnt/ext_sdcard',
      '/mnt/extsd',
      '/mnt/ext_card',
      '/mnt/external_sd',
      '/mnt/ext_sd',
      '/mnt/external',
      '/mnt/extSdCard',
      '/mnt/externalSdCard'
      );
  begin
  Result := '';
  AList := TDirectory.GetDirectories('/mnt');
  ALastNo := 0;
  for I := 0 to High(AList) do
    begin
    S := AList[I];
    for J := 0 to High(ExtSDCardNames) do
      begin
      if S = ExtSDCardNames[J] then
        begin
        Result := S + '/';
        Exit;
        end
      end;
    if StartWithW(PWideChar(S),'/mnt/sdcard', False) then
      begin
      if TryStrToInt(RightStrW(AList[I], Length(AList[I]) - 11, False), ANo)
      then
        begin
        if ANo > ALastNo then
          begin
          ALastNo := ANo;
          Result := AList[I] + '/';
          end;
        end;
      end;
    end;
  end;

这个函数使用了QString.pas单元的StartWithW和RightStrW两个函数,TDirectory对象需要引入ioutils单元。ExtSDCardNames常量定义了目前已经的SD卡根目录的挂载名称,可能还有更多,如果你发现了,可以随时补充就好。在找不到上述关键词时,会尝试搜索sdcard1/sdcard2这样的目录,并取其中最大的那个值为SD卡的根目录。

分享到: