ADB를 활용한 안드로이드 자동화 스크립트 개발

필수 도구 설치

안드로이드 기기 자동화는 ADB(Android Debug Bridge) 명령어를 통해 구현됩니다. 먼저 필요한 도구들을 설치해야 합니다.

1. ADB 툴킷 설정

다음 링크에서 운영체제에 맞는 SDK 플랫폼 도구를 다운로드합니다:

SDK 플랫폼 도구 다운로드

압축을 해제한 후, adb.exe가 위치한 디렉토리를 시스템 환경변수 PATH에 추가합니다. 설정 완료 후 명령 프롬프트에서 다음 명령어를 실행하여 정상 설치 여부를 확인할 수 있습니다:

adb version

2. 디바이스 연결 준비

uiautomator2 라이브러리를 설치하여 안드로이드 UI 자동화를 지원합니다:

pip install uiautomator2

에뮬레이터 사용시 별도 설정 없이 바로 연결할 수 있으며, 실제 디바이스의 경우 개발자 옵션에서 USB 디버깅을 활성화해야 합니다. 연결 상태는 다음 명령어로 확인합니다:

adb devices

실제 단말기 사용시 추가 초기화가 필요합니다:

python -m uiautomator2 init

핵심 모듈 설치

pip install opencv-python schedule

핵심 함수 구현

1. 시스템 명령 실행 함수

import subprocess

def execute_cmd(cmd_text):
    process = subprocess.Popen(
        cmd_text.split(), 
        stdout=subprocess.PIPE, 
        stderr=subprocess.PIPE,
        text=True
    )
    output, error = process.communicate()
    return output.strip()

2. 화면 캡처 기능

import os

def capture_screen(filename):
    screenshot_path = f"./screenshots/{filename}.png"
    os.makedirs(os.path.dirname(screenshot_path), exist_ok=True)
    cmd = f"adb exec-out screencap -p > {screenshot_path}"
    execute_cmd(cmd)
    print(f"스크린샷 저장: {filename}")

3. 좌표 클릭 함수

def click_position(x_coord, y_coord):
    cmd = f"adb shell input tap {x_coord} {y_coord}"
    execute_cmd(cmd)

4. 이미지 매칭을 통한 위치 탐색

import cv2

def find_element_position(target_img, screen_img):
    source_image = cv2.imread(screen_img, 0)
    template_image = cv2.imread(target_img, 0)
    
    result = cv2.matchTemplate(source_image, template_image, cv2.TM_CCOEFF_NORMED)
    _, max_val, _, max_loc = cv2.minMaxLoc(result)
    
    h, w = template_image.shape
    center_x = max_loc[0] + w // 2
    center_y = max_loc[1] + h // 2
    
    return center_x, center_y, max_val

5. 대상 이미지 목록 검색

def get_target_images(directory="./targets"):
    image_files = []
    for root, _, files in os.walk(directory):
        for file in files:
            if file.lower().endswith('.png'):
                image_files.append(os.path.join(root, file))
    return image_files

자동화 프로세스 실행

def automation_process():
    target_list = get_target_images()
    current_screen = "current_view"
    
    capture_screen(current_screen)
    screen_path = f"./screenshots/{current_screen}.png"
    
    for target_path in target_list:
        try:
            x, y, confidence = find_element_position(target_path, screen_path)
            if confidence > 0.8:  # 신뢰도 임계값
                click_position(x, y)
                print(f"클릭 완료: {target_path}")
                break
        except Exception as e:
            print(f"요소 탐색 실패: {e}")
            continue

스케줄링 설정

import schedule
import time

def setup_schedule():
    work_start = input("출근 시간 입력 (HH:MM): ")
    work_end = input("퇴근 시간 입력 (HH:MM): ")
    
    schedule.every().day.at(work_start).do(automation_process)
    schedule.every().day.at(work_end).do(automation_process)
    
    print("자동화 스케줄 등록 완료")
    
    while True:
        schedule.run_pending()
        time.sleep(30)

if __name__ == "__main__":
    setup_schedule()

태그: python ADB OpenCV automation schedule

7월 20일 05:10에 게시됨