본문 바로가기

Programming/Delphi

#04. ADB를 이용해 장치 목록 가져오기

가상에뮬레이터는 각각 자기 자신에게 연결되어 있는 장치가 존재합니다.

해당 장치와 ADB를 이용해 사용자가 원하는 가상에뮬레이터에 명령을 보낼 수

있는거죠.


녹스를 예를 들어 설명하도록 하겠습니다.

녹스의 경우 127.0.0.1:xxxxx 와 같은 패턴으로 장치들이 존재합니다.


먼저 명령프롬프트에 명령을 보낸후 결과값을 가져오는 함수가 장치목록을 가져오는 함수에 포함되기때문에 해당 함수부터 소개하도록 하겠습니다.


procedure GetDosOutput(CommandLine: string; list: TStringList;

Work: string = 'C:\'); var SA: TSecurityAttributes; SI: TStartupInfo; PI: TProcessInformation; StdOutPipeRead, StdOutPipeWrite: THandle; WasOK: Boolean; Buffer: array[0..255] of AnsiChar; BytesRead: Cardinal; WorkDir: string; Handle: Boolean; begin with SA do begin nLength := SizeOf(SA); bInheritHandle := True; lpSecurityDescriptor := nil; end; CreatePipe(StdOutPipeRead, StdOutPipeWrite, @SA, 0); try with SI do begin FillChar(SI, SizeOf(SI), 0); cb := SizeOf(SI); dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES; wShowWindow := SW_HIDE; hStdInput := GetStdHandle(STD_INPUT_HANDLE); hStdOutput := StdOutPipeWrite; hStdError := StdOutPipeWrite; end; WorkDir := Work; Handle := CreateProcess(nil, PChar('cmd.exe /C ' + CommandLine), nil, nil, True, 0, nil, PChar(WorkDir), SI, PI); CloseHandle(StdOutPipeWrite); if Handle then try list.Clear; repeat WasOK := ReadFile(StdOutPipeRead, Buffer, 255, BytesRead,

nil); if BytesRead > 0 then begin Buffer[BytesRead] := #0; list.Text := list.Text + Buffer; end; until not WasOK or (BytesRead = 0); WaitForSingleObject(PI.hProcess, INFINITE); finally CloseHandle(PI.hThread); CloseHandle(PI.hProcess); end; finally CloseHandle(StdOutPipeRead); end; end;


ADB를 이용한 장치목록을 가져오는 함수입니다.

function GetADBDevices(adb_path : String) : TStringList;
var
  list,rList  : TStringList;
  i           : Integer;
  tmpStr      : String;
begin
  try
    list := TStringList.Create;
    rList := TStringList.Create;

    try
      GetDosOutput(adb_Path + ' devices', list);

      for i := 1 to list.Count - 1 do
      begin
        tmpStr := list.Strings[i];
        if tmpStr <> '' then
        begin
          if Pos('device', tmpStr) > 0 then
          begin
            tmpStr := Copy(tmpStr, 0, Pos('device', tmpStr) - 1);
            rList.Add(tmpStr);
          end;
        end;
      end;

      Result := rList;
    finally
      list.Free;
      rList.Free;
    end;
  except
    On E: Exception do ShowMessage(E.Message);
  end;
end;


ADB의 풀경로를 이용하여 모든 ADB장치 목록을 가져옵니다.

** 주의사항: ADB풀경로에 공백이 존재할경우 목록들을 가져올 수 없습니다.