Showing posts with label adb. Show all posts
Showing posts with label adb. Show all posts

Tuesday, March 19, 2024

안드로이드 개발자 필수 가이드: ADB와 ADB Shell 완벽 정복

ADB(Android Debug Bridge)는 개발용 PC와 안드로이드 기기를 연결하여 통신할 수 있게 해주는 다목적 명령줄 도구입니다. ADB를 통해 앱 설치 및 디버깅, 파일 전송, 기기 로그 확인 등 개발에 필수적인 다양한 작업을 효율적으로 수행할 수 있습니다. 그중에서도 특히 강력한 기능은 ADB Shell로, 기기의 기반이 되는 리눅스 명령줄 환경에 직접 접근하여 파일 시스템 관리, 프로세스 제어, 시스템 설정 변경 등 더욱 심도 있는 작업을 가능하게 합니다.

안드로이드 개발자에게 ADB와 ADB Shell의 능숙한 활용은 선택이 아닌 필수입니다. 개발, 테스트, 디버깅 전 과정의 효율을 극대화하는 핵심 도구이기 때문입니다. 이 글에서는 ADB 설치 과정부터 기본 및 고급 명령어 활용법까지 총정리하여 여러분이 ADB의 모든 잠재력을 활용할 수 있도록 돕겠습니다.

ADB 사용 준비: 설치 및 기기 설정

ADB를 사용하려면 먼저 PC와 안드로이드 기기 양쪽에서 준비가 필요합니다. 다음 단계를 따라 설정을 완료하세요.

1단계: Android 기기에서 USB 디버깅 활성화

가장 먼저 해야 할 중요한 단계입니다. ADB가 기기와 통신하려면 'USB 디버깅' 옵션이 활성화되어 있어야 합니다.

  1. 기기의 설정 > 휴대전화 정보로 이동합니다.
  2. 빌드 번호 항목을 "개발자가 되셨습니다."라는 메시지가 나타날 때까지 7번 연속으로 누릅니다.
  3. 설정 메뉴로 돌아가면 개발자 옵션이라는 새로운 항목이 보입니다. (기기에 따라 '시스템' 메뉴 안에 있을 수 있습니다.)
  4. 개발자 옵션에 들어가 USB 디버깅을 활성화합니다.

2단계: PC에 ADB 설치하기

ADB는 Android SDK Platform-Tools 패키지에 포함되어 있습니다. Android Studio 전체를 설치할 필요는 없습니다.

  1. 공식 Android SDK Platform-Tools 다운로드 페이지로 이동합니다.
  2. 사용 중인 운영체제(Windows, macOS, Linux)에 맞는 패키지를 다운로드합니다.
  3. 다운로드한 ZIP 파일의 압축을 기억하기 쉬운 위치(예: Windows의 경우 C:\platform-tools)에 해제합니다.
  4. 어떤 터미널에서든 ADB 명령어를 바로 사용할 수 있도록, 압축 해제한 폴더의 경로를 시스템 환경 변수 'PATH'에 추가합니다.

3단계: 설치 및 연결 확인

모든 준비가 끝나면 ADB가 제대로 작동하는지 확인합니다.

  1. USB 케이블로 안드로이드 기기와 PC를 연결합니다. 기기 화면에 'USB 디버깅을 허용하시겠습니까?'라는 창이 뜨면 허용을 선택합니다.
  2. PC에서 명령 프롬프트(Windows) 또는 터미널(macOS/Linux)을 엽니다.
  3. adb devices 명령어를 입력하고 Enter 키를 누릅니다.
  4. 연결된 기기의 시리얼 번호 옆에 'device'라고 표시되면 성공적으로 연결된 것입니다. 'unauthorized'라고 표시된다면 기기 화면의 디버깅 허용 창을 다시 확인해주세요.

개발자라면 꼭 알아야 할 필수 ADB 명령어

ADB 설정이 완료되었다면 이제 강력한 명령어들을 사용할 차례입니다. 일상적인 개발 작업에서 가장 자주 사용되는 핵심 명령어들을 소개합니다.

연결된 기기 목록 보기
기기가 제대로 연결되었는지 확인할 때 가장 먼저 사용하는 명령어입니다. adb devices

애플리케이션 설치
APK 파일을 기기에 설치합니다. adb install <APK_파일_경로>

애플리케이션 삭제
패키지 이름(예: com.example.myapp)을 이용해 기기에서 앱을 삭제합니다. adb uninstall <패키지_이름>

기기로 파일 전송
PC의 파일을 기기로 복사합니다. adb push <로컬_경로> <기기_경로>

기기에서 파일 가져오기
기기의 파일을 PC로 복사합니다. adb pull <기기_경로> <로컬_경로>

기기 쉘 접속
기기 내부의 리눅스 명령줄 환경(쉘)으로 접속합니다. adb shell

기기 로그 확인
디버깅의 핵심인 기기 로그(Logcat)를 실시간으로 출력합니다. adb logcat

기기 재부팅
연결된 기기를 다시 시작합니다. adb reboot bootloader(부트로더 모드)나 adb reboot recovery(리커버리 모드)로도 재부팅할 수 있습니다. adb reboot

ADB Shell 기본 명령어

adb shell <명령어> 형식으로 PC에서 바로 쉘 명령을 실행하거나, adb shell로 대화형 쉘에 진입하여 명령어를 사용할 수 있습니다. 다음은 유용한 기본 쉘 명령어입니다.

파일 및 디렉토리 목록 보기
리눅스의 ls 명령어와 동일하게 기기의 파일 시스템을 탐색합니다. adb shell ls /sdcard/

실행 중인 프로세스 목록 보기
현재 기기에서 실행 중인 모든 프로세스를 표시합니다. adb shell ps

시스템 서비스 정보 덤프
시스템 서비스에 대한 방대한 정보를 출력합니다. adb shell dumpsys activity처럼 특정 서비스를 지정하여 원하는 정보를 얻을 수 있습니다. adb shell dumpsys

앱 액티비티 실행
액티비티 매니저(am)를 사용하여 특정 앱의 컴포넌트를 실행합니다. adb shell am start -n <패키지명>/<액티비티명>

시스템 속성 확인
안드로이드 버전, 화면 밀도 등 기기의 시스템 속성을 표시합니다. adb shell getprop

시스템 속성 설정
기기의 시스템 속성을 변경합니다. 대부분의 경우 루팅(root) 권한이 필요합니다. adb shell setprop <키> <값>

텍스트 입력 시뮬레이션
현재 포커스된 입력창에 원하는 텍스트를 입력합니다. adb shell input text <입력할_텍스트>

ADB를 활용한 디버깅

ADB는 앱의 버그를 찾고 해결하는 데 가장 강력한 도구입니다. 디버깅 작업 흐름에 유용한 핵심적인 방법들을 알아봅시다.

실시간 로그 모니터링
adb logcat은 디버깅의 가장 친한 친구입니다. adb logcat YourAppTag:D *:S 와 같이 태그로 필터링하여 내 앱에서 발생하는 로그만 깔끔하게 확인할 수 있습니다.

종합 버그 리포트 생성
adb bugreport는 기기 로그, 스택 트레이스 등 문제 분석에 필요한 모든 정보를 담은 종합적인 보고서를 생성해줍니다. 복잡한 비정상 종료(Crash) 현상을 분석할 때 매우 유용합니다.

Java 디버거 연결 확인
adb jdwp는 디버깅이 가능한 모든 Java 프로세스의 JDWP(Java Debug Wire Protocol) ID를 보여줍니다. Android Studio와 같은 디버거를 직접 연결할 때 사용됩니다.

앱 강제 종료
adb shell am force-stop <패키지명> 명령어로 앱을 즉시 종료시킬 수 있습니다. 앱이 완전히 새로 시작될 때의 동작을 테스트하는 데 유용합니다.

ADB Shell을 이용한 성능 디버깅

ADB Shell은 메모리 누수나 과도한 CPU 사용량 같은 성능 병목 현상을 진단하는 데 효과적인 유틸리티를 제공합니다.

앱 메모리 사용량 확인
adb shell dumpsys meminfo <패키지명> 명령어를 사용하면 특정 앱의 메모리 사용 현황을 상세하게 파악하여 메모리 누수를 추적할 수 있습니다.

CPU 사용량 모니터링
adb shell top은 CPU를 많이 사용하는 프로세스 순으로 실시간 목록을 보여줍니다. 이를 통해 어떤 작업이 성능을 저하하는지 쉽게 식별할 수 있습니다.

시스템 호출 추적
adb shell strace -p <프로세스_ID>는 특정 프로세스가 어떤 시스템 자원을 요청하는지(시스템 콜) 추적하는 고급 기법입니다. 앱의 매우 낮은 수준의 동작을 분석할 때 사용됩니다.

ADB와 ADB Shell의 고급 활용법

기본기를 익혔다면, 이제 개발 워크플로우를 한 차원 높여줄 고급 활용법들을 살펴볼 시간입니다.

포트 포워딩
PC의 특정 포트로 들어오는 요청을 기기의 특정 포트로 전달합니다. 기기 내 웹뷰나 네트워크 서비스를 PC의 브라우저에서 직접 디버깅할 때 매우 유용합니다. adb forward <PC_포트> <기기_포트>

앱 권한으로 명령어 실행
run-as를 사용하면 디버깅 가능한 앱의 권한으로 쉘 명령어를 실행할 수 있습니다. 루팅 없이도 앱의 내부 데이터 폴더(/data/data/<패키지명>)에 접근할 수 있게 해줍니다. adb shell run-as <패키지명> <명령어>

기기 화면 녹화
기기 화면을 동영상으로 녹화합니다. 버그 재현 과정을 공유하거나, 앱의 동작 및 애니메이션을 분석하는 데 효과적입니다. adb shell screenrecord /sdcard/demo.mp4

앱 안정성 스트레스 테스트
Monkey는 무작위 터치, 제스처 등 예측 불가능한 사용자 이벤트를 대량으로 발생시켜 앱을 테스트하는 도구입니다. 이를 통해 앱의 안정성을 검증하고 예상치 못한 오류를 발견할 수 있습니다. adb shell monkey -p <패키지명> -v 1000

기기 데이터 백업 및 복원
기기의 데이터와 앱을 통째로 PC에 백업 파일로 저장합니다. 나중에 adb restore 명령어로 복원할 수 있습니다. adb backup -apk -all -f backup.ab

이 글을 통해 ADB와 ADB Shell의 다양한 기능과 활용법을 알아보았습니다. 이 도구들을 능숙하게 사용한다면 안드로이드 앱 개발, 테스트, 디버깅의 모든 과정을 훨씬 효율적으로 만들어 줄 것입니다. 이 글이 여러분의 개발 여정에 큰 도움이 되었기를 바랍니다.

Android開発者必見!ADBとADB Shellを徹底解説する完全ガイド

ADB (Android Debug Bridge) は、開発用のPCとAndroidデバイスを接続し、通信を可能にする多目的コマンドラインツールです。ADBを使えば、アプリのインストールやデバッグ、ファイルの転送、デバイスのログ取得など、開発に不可欠な様々な操作を効率的に実行できます。その中でも特に強力なのがADB Shellです。これはデバイスの基盤となっているLinuxのコマンドライン環境へ直接アクセスする機能で、ファイルシステムの操作、プロセスの管理、システム設定の変更といった、より低レベルな作業を可能にします。

Androidアプリ開発者にとって、ADBとADB Shellを使いこなすことは、もはや推奨スキルではなく必須スキルと言えるでしょう。本記事では、これらのツールの導入方法から、日常的に使う基本コマンド、さらにはデバッグや高度な活用法までを網羅的に解説し、あなたの開発効率を飛躍的に向上させるお手伝いをします。

ADBのセットアップ:インストールとデバイスの準備

ADBを使い始めるには、PCとAndroidデバイスの両方で準備が必要です。以下の手順に従ってセットアップを完了させましょう。

ステップ1:AndroidデバイスでUSBデバッグを有効にする

これは最も重要な最初のステップです。ADBがデバイスと通信するには、「USBデバッグ」が有効になっている必要があります。

  1. デバイスの「設定」から「デバイス情報」(または「端末情報」)を開きます。
  2. 「ビルド番号」を7回連続でタップします。「これでデベロッパーになりました!」というメッセージが表示されます。
  3. 設定メニューに戻ると、「開発者向けオプション」という新しい項目が表示されています(「システム」内にある場合もあります)。
  4. 「開発者向けオプション」を開き、「USBデバッグ」のスイッチをオンにします。

ステップ2:PCにADBをインストールする

ADBはAndroid SDK Platform-Toolsパッケージに含まれています。Android Studio全体をインストールする必要はありません。

  1. 公式のAndroid SDK Platform-Toolsダウンロードページにアクセスします。
  2. お使いのOS(Windows, macOS, Linux)用のパッケージをダウンロードします。
  3. ダウンロードしたZIPファイルを、わかりやすい場所(例:Windowsなら C:\platform-tools)に展開します。
  4. どのターミナルからでもコマンドを実行できるよう、展開したフォルダへのパスをシステムの環境変数「PATH」に追加します。

ステップ3:インストールと接続の確認

すべての準備が整ったら、ADBが正しく動作するか確認します。

  1. AndroidデバイスをUSBケーブルでPCに接続します。デバイスの画面に「USBデバッグを許可しますか?」というダイアログが表示されたら、許可してください。
  2. PCでコマンドプロンプト(Windows)またはターミナル(macOS/Linux)を開きます。
  3. adb devices と入力してEnterキーを押します。
  4. デバイスのシリアル番号の横に「device」と表示されれば、正常に接続されています。「unauthorized」と表示される場合は、デバイスの画面でデバッグ許可のダイアログを確認してください。

開発者なら覚えておきたい必須ADBコマンド

ADBのセットアップが完了したら、いよいよ強力なコマンド群を使ってみましょう。ここでは日常的に使用する基本的なコマンドを紹介します。

接続デバイスの一覧表示
デバイスが正しく認識されているかを確認するための最初のコマンドです。 adb devices

アプリケーションのインストール
APKファイルをデバイスにインストールします。 adb install <APKファイルのパス>

アプリケーションのアンインストール
パッケージ名(例: com.example.myapp)を指定して、アプリをデバイスから削除します。 adb uninstall <パッケージ名>

デバイスへのファイル転送
PC上のファイルやディレクトリをデバイスにコピーします。 adb push <ローカルパス> <リモートパス>

デバイスからのファイル取得
デバイス上のファイルやディレクトリをPCにコピーします。 adb pull <リモートパス> <ローカルパス>

デバイスシェルへのアクセス
デバイス上で対話的なLinuxコマンドシェルを起動します。 adb shell

デバイスログの表示
デバイスのログ(Logcat)をリアルタイムで表示します。デバッグには不可欠です。 adb logcat

デバイスの再起動
接続されているデバイスを再起動します。adb reboot bootloaderでブートローダー、adb reboot recoveryでリカバリーモードで再起動することも可能です。 adb reboot

ADB Shellの基本コマンド

adb shell <コマンド> の形式でPCのターミナルから直接シェルコマンドを実行したり、adb shellで対話モードに入ってからコマンドを実行したりできます。ここでは基本的なシェルコマンドを紹介します。

ファイルとディレクトリの一覧表示
Linuxのlsコマンドと同様に、デバイスのファイルシステムを探索します。 adb shell ls /sdcard/

実行中プロセスの一覧表示
デバイスで現在実行されているすべてのプロセスを表示します。 adb shell ps

システムサービス情報のダンプ
システムサービスに関する膨大な情報を表示します。adb shell dumpsys activityのようにサービスを指定すると、特定の情報を得られます。 adb shell dumpsys

アプリのアクティビティ起動
アクティビティマネージャ(am)を使い、特定のアプリコンポーネントを起動します。 adb shell am start -n <パッケージ名>/<アクティビティ名>

システムプロパティの取得
Androidのバージョンや画面密度など、デバイスのシステムプロパティを表示します。 adb shell getprop

システムプロパティの設定
システムプロパティを変更します。多くの場合、root権限が必要です。 adb shell setprop <キー> <値>

テキスト入力のシミュレート
現在フォーカスが当たっているテキストフィールドに、指定した文字列を入力します。 adb shell input text <入力したい文字列>

ADBを活用したデバッグ手法

ADBは、アプリの問題を特定し修正するための最も重要なツールです。デバッグ作業で役立つ主要なコマンドを見ていきましょう。

リアルタイムでのログ監視
logcatはデバッグの最高の相棒です。adb logcat YourAppTag:D *:Sのようにタグでフィルタリングすれば、自分のアプリのログだけを追跡できます。 adb logcat

バグレポートの完全生成
デバイスのログ、スタックトレース、その他の診断情報を網羅した包括的なレポートを生成します。複雑なクラッシュの分析に最適です。 adb bugreport

Javaデバッガ接続の確認
デバッグ可能なすべてのプロセスのJDWP (Java Debug Wire Protocol) IDを一覧表示します。Android Studioなどのデバッガをアタッチする際に役立ちます。 adb jdwp

アプリケーションの強制停止
アプリのプロセスを即座に終了させます。アプリがコールドスタートからどのように動作するかをテストするのに便利です。 adb shell am force-stop <パッケージ名>

ADB Shellによるパフォーマンスデバッグ

ADB Shellは、メモリリークや高いCPU使用率といったパフォーマンスのボトルネックを診断するための強力なユーティリティを提供します。

アプリの状態とパフォーマンス確認
dumpsysmeminfoのような特定のサービスと組み合わせて使うことで、アプリの詳細なメモリ使用量を明らかにできます。 adb shell dumpsys meminfo <パッケージ名>

CPU使用率の監視
topコマンドは、CPU使用率の高い順にプロセスをリアルタイムで表示し、CPU負荷の高い処理を特定するのに役立ちます。 adb shell top

システムコールのトレース
straceユーティリティは、プロセスによって行われたシステムコールを傍受し、記録します。これはアプリの低レベルな振る舞いを理解するための高度なテクニックです。 adb shell strace -p <プロセスID>

ADBとADB Shellの高度な活用法

基本をマスターしたら、これらの高度なコマンドを探求して、ワークフローをさらに効率化しましょう。

ポートフォワーディング
PCの特定のポートへのソケット接続を、デバイスのポートに転送します。デバイス上のWebViewやネットワークサービスをPCのブラウザからデバッグする際に便利です。 adb forward <PC側ポート> <デバイス側ポート>

アプリ権限でのコマンド実行
run-asコマンドを使うと、デバッグ可能なアプリと同じ権限でシェルコマンドを実行できます。これにより、root化せずともアプリのプライベートなデータディレクトリ(/data/data/<パッケージ名>)にアクセスできます。 adb shell run-as <パッケージ名> <コマンド>

デバイス画面の録画
デバイスの画面操作を動画として録画します。デモの作成、バグの再現、アニメーションの分析に最適です。 adb shell screenrecord /sdcard/demo.mp4

アプリのストレステスト
Monkeyツールは、ランダムなクリック、タッチ、ジェスチャーといった擬似的なユーザーイベントを大量に発生させます。アプリの安定性をテストし、稀にしか発生しないクラッシュを発見するための優れた方法です。 adb shell monkey -p <パッケージ名> -v 1000

デバイスデータのバックアップと復元
デバイスのデータやアプリを丸ごとPC上のファイルにバックアップします。後でadb restoreコマンドで復元できます。 adb backup -apk -all -f backup.ab

本記事では、ADBとADB Shellの基本的な機能から応用的なコマンドまでを解説しました。これらのツールを日々のワークフローに組み込むことで、Androidアプリの開発、テスト、デバッグの効率を飛躍的に向上させることができるでしょう。ぜひここで紹介したコマンドを実際に試し、その強力な機能を実感してください。

Mastering ADB and ADB Shell: The Ultimate Guide for Android Developers

The Android Debug Bridge (ADB) is a versatile command-line tool that acts as the crucial link between your development machine and an Android device. It empowers you to perform a wide range of actions, from installing and debugging apps to transferring files and accessing detailed device logs. A key component of ADB is the ADB Shell, which grants you direct access to the underlying Linux command-line environment on the device. This allows for powerful, low-level operations like managing file systems, controlling processes, and modifying system settings.

For any Android developer, mastering ADB and ADB Shell is not just a recommendation—it's a necessity. These tools are indispensable for efficient development, rigorous testing, and effective debugging. This comprehensive guide will walk you through everything from installation to advanced commands, helping you harness their full potential.

Getting Started: Installing ADB and Preparing Your Device

Before you can use ADB, you need to set up both your computer and your Android device. Follow these steps to get everything ready.

Step 1: Enable USB Debugging on Your Android Device

This is a critical first step. ADB requires "USB debugging" to be enabled in the Developer options on your device.

  1. On your device, go to Settings > About phone.
  2. Tap on the Build number seven times until you see a message that says, "You are now a developer!"
  3. Go back to the main Settings menu, and you should now see Developer options (it might be under System).
  4. Open Developer options and enable USB debugging.

Step 2: Install ADB on Your Computer

ADB is part of the Android SDK Platform-Tools package. You don't need the full Android Studio to get it.

  1. Navigate to the official Android SDK Platform-Tools download page.
  2. Download the package for your operating system (Windows, macOS, or Linux).
  3. Extract the contents of the downloaded ZIP file to a memorable location on your computer (e.g., C:\platform-tools on Windows).
  4. For convenient access from any terminal window, add the path to the extracted folder to your system's PATH environment variable.

Step 3: Verify the Installation and Connection

Once everything is set up, you can verify that ADB is working correctly.

  1. Connect your Android device to your computer via a USB cable. You may see a prompt on your device asking to "Allow USB debugging." Accept it.
  2. Open a command prompt (on Windows) or a terminal (on macOS/Linux).
  3. Type the command adb devices and press Enter.
  4. If your device is connected and recognized, you will see its serial number listed with "device" next to it. If it shows "unauthorized," check your device for the authorization prompt.

Essential ADB Commands Every Developer Should Know

Once ADB is set up, you can start using its powerful commands. Here are some of the most fundamental ones you'll use daily.

List Connected Devices
The first command you should always run to ensure your device is connected properly. adb devices

Install an Application
Installs an Android application (APK file) onto your device. adb install <path_to_apk_file>

Uninstall an Application
Removes an application from your device using its package name (e.g., com.example.myapp). adb uninstall <package_name>

Transfer Files to Device
Pushes a file or directory from your computer to the device. adb push <local_path> <remote_path>

Transfer Files from Device
Pulls a file or directory from the device to your computer. adb pull <remote_path> <local_path>

Access the Device Shell
Opens an interactive Linux command-line shell on the device. adb shell

View Device Logs
Displays the real-time log output from the device (Logcat), which is invaluable for debugging. adb logcat

Reboot the Device
Reboots the connected Android device. You can also reboot into the bootloader (adb reboot bootloader) or recovery (adb reboot recovery). adb reboot

Basic ADB Shell Commands

You can execute shell commands directly from your computer's terminal using the adb shell <command> format, or you can enter an interactive shell with just adb shell. Here are some essential shell commands.

List Files and Directories
Explore the device's file system, similar to the ls command on Linux. adb shell ls /sdcard/

List Running Processes
Shows all the processes currently running on the device. adb shell ps

Dump System Service Information
Provides a massive amount of information about system services. You can specify a service to get targeted data (e.g., adb shell dumpsys activity). adb shell dumpsys

Start an App Activity
Launches a specific app component using the activity manager (am). adb shell am start -n <package_name>/<activity_name>

Get System Properties
Displays the device's system properties, such as the Android version or screen density. adb shell getprop

Set System Properties
Allows you to modify a system property. This often requires root access. adb shell setprop <key> <value>

Simulate Text Input
Inputs a string of text into the currently focused text field on the device. adb shell input text <text_string>

Debugging with ADB

ADB is your primary tool for identifying and fixing issues in your Android apps. Here are key commands for your debugging workflow.

Monitor Logs in Real-Time
The logcat command is your best friend for debugging. You can filter by tag to see logs only from your app: adb logcat YourAppTag:D *:S. adb logcat

Generate a Full Bug Report
Creates a comprehensive report containing device logs, stack traces, and other diagnostic information, which is perfect for analyzing complex crashes. adb bugreport

Check Java Debugger Connections
Lists the Java Debug Wire Protocol (JDWP) IDs of all processes that can be debugged. This is useful for attaching a debugger like the one in Android Studio. adb jdwp

Force-Stop an Application
Immediately terminates an application's process. Useful for testing how your app behaves on a cold start. adb shell am force-stop <package_name>

Performance Debugging with ADB Shell

ADB Shell provides powerful utilities for diagnosing performance bottlenecks like memory leaks and high CPU usage.

Check App Status and Performance
Using dumpsys with a specific service like meminfo can reveal detailed memory usage for your app. adb shell dumpsys meminfo <package_name>

Monitor CPU Usage
The top command shows a real-time list of processes sorted by their CPU usage, helping you identify CPU-intensive operations. adb shell top

Trace System Calls
The strace utility intercepts and records the system calls made by a process. This is an advanced technique for understanding low-level app behavior. adb shell strace -p <process_id>

Advanced Usage of ADB and ADB Shell

Once you've mastered the basics, you can explore these advanced commands to further streamline your workflow.

Port Forwarding
Forwards a socket connection from a specific port on your computer to a port on the device. This is useful for debugging webviews or other network services on the device from your PC's browser. adb forward <pc_port> <device_port>

Execute Commands as Your App
The run-as command lets you execute shell commands with the same permissions as your debuggable application, allowing you to access its private data directory (/data/data/<package_name>) without root. adb shell run-as <package_name> <command>

Record the Device Screen
Records a video of the device's screen, which is perfect for creating demos, reproducing bugs, or analyzing animations. adb shell screenrecord /sdcard/demo.mp4

Stress Test Your App
The Monkey is a tool that generates a stream of pseudo-random user events (clicks, touches, gestures). It's an excellent way to stress-test your app for stability and uncover rare crashes. adb shell monkey -p <package_name> -v 1000

Backup and Restore Device Data
Creates a full backup of your device's data and apps to a file on your computer. You can later restore it with adb restore. adb backup -apk -all -f backup.ab

This article has covered the essential functions and commands of ADB and ADB Shell. By integrating these tools into your daily workflow, you can significantly enhance your efficiency in developing, testing, and debugging Android applications. We encourage you to experiment with these commands and explore their many options to become a more effective Android developer.

Wednesday, September 20, 2023

Androidカスタマイズの扉を開く:ADBとFastbootの核心に迫る

Androidスマートフォンやタブレットは、私たちの日常生活に深く根付いた強力なコンピューティングデバイスです。多くのユーザーは、メーカーが提供する標準的な機能とインターフェースに満足していますが、その表面下には、デバイスの真のポテンシャルを解放するための隠された扉が存在します。その扉を開く鍵となるのが、ADB (Android Debug Bridge)Fastboot です。これらは単なる開発者向けの専門ツールではありません。システムの奥深くにアクセスし、カスタマイズ、トラブルシューティング、そしてパフォーマンスの最適化を可能にする、パワーユーザーにとって不可欠な架け橋なのです。

この記事では、ADBとFastbootの基本的な概念から、そのインストール方法、多岐にわたるコマンドの具体的な使用例、そして実践的な応用シナリオまで、網羅的かつ詳細に解説していきます。アプリの強制終了やパフォーマンスの低下といった日常的な問題の解決から、カスタムROMの導入やカーネルの書き換えといった高度なカスタマイズまで、あなたのAndroid体験を根底から変える知識がここにあります。さあ、デバイスの制約を乗り越え、あなただけの究極のAndroid環境を構築する旅を始めましょう。

目次

第1章:基盤となる概念の理解 - ADBとFastbootとは何か?

ADBとFastbootを効果的に使用するためには、まずそれぞれが何であり、どのような役割を担っているのかを正確に理解することが不可欠です。これらは似ているようで、動作するレイヤーと目的が根本的に異なります。

1.1 ADB (Android Debug Bridge) の構造と役割

ADB (Android Debug Bridge) は、その名の通り、コンピュータとAndroidデバイスとの間の「デバッグ用の橋渡し」をするための、非常に多機能なコマンドラインツールです。Android OSが完全に起動している状態、またはリカバリーモードで動作し、デバイスのソフトウェアレベルでの広範な操作を可能にします。

ADBのアーキテクチャ

ADBは3つのコンポーネントから構成されるクライアント-サーバーモデルを採用しています。

  • クライアント (Client): ユーザーが操作するコンピュータ上で動作します。コマンドプロンプトやターミナルでadbコマンドを入力すると、このクライアントが起動します。
  • サーバー (Server): コンピュータ上でバックグラウンドプロセスとして動作します。クライアントからのコマンドを受け取り、それを適切なデバイス(エミュレータまたは実機)へ中継する役割を担います。また、USB経由で接続されたデバイスを常時監視しています。adb start-serverコマンドで手動起動も可能です。
  • デーモン (Daemon, adbd): Androidデバイス側で動作するバックグラウンドプロセスです。サーバーからのコマンドを受け取り、デバイス上でそれを実行します。

この構造により、一つのコンピュータから複数のAndroidデバイスを同時に管理することが可能になります。

ADBの主な用途

  • アプリケーションのインストールとデバッグ: 開発者がAPKファイルを直接デバイスにインストール(adb install)したり、アンインストール(adb uninstall)したり、デバッグ情報をリアルタイムで監視(adb logcat)するために使用します。
  • ファイル転送: コンピュータとデバイス間でファイルやフォルダを双方向に転送(adb push / adb pull)できます。バックアップやデータ移動に非常に便利です。
  • シェルアクセス: デバイスのLinuxベースのコマンドラインシェルにアクセス(adb shell)し、ファイルシステムの操作、パーミッションの変更、プロセスの確認など、高度な操作を行えます。
  • システムの制御: デバイスの再起動(adb reboot)、リカバリーモードへの移行(adb reboot recovery)、スクリーンショットの撮影(adb shell screencap)など、多岐にわたるシステム制御が可能です。

簡単に言えば、ADBは「起動中のAndroid OSと対話するための万能ツール」です。

1.2 Fastboot の本質とブートローダーとの関係

Fastbootは、ADBとは異なり、Android OSが起動する前の段階、すなわちブートローダー (Bootloader) モードで動作するプロトコルおよびツールです。ブートローダーは、デバイスの電源が投入された際に最初に実行される低レベルのソフトウェアであり、OSを起動させる役割を担っています。Fastbootはこのブートローダーと直接通信し、デバイスの根幹をなすパーティションを直接書き換えることを可能にします。

Fastbootの役割

Fastbootの主な目的は、デバイスのフラッシュメモリ(ストレージ)に存在する様々なパーティションを操作することです。Androidデバイスのストレージは、以下のような複数のパーティションに区切られています。

  • boot: OSの心臓部であるカーネルとRAMディスクが含まれています。
  • system: Android OSの本体、システムアプリ、ライブラリなどが格納されています。
  • recovery: システムのアップデートや修復を行うためのリカバリー環境が格納されています。
  • userdata: ユーザーデータ、インストールしたアプリ、設定などが保存されます。
  • vendor, radioなど: ハードウェア固有のドライバやベースバンドファームウェアなどが含まれます。

Fastbootは、これらのパーティションに対して新しいイメージファイル(.img)を書き込む(フラッシュする)ことができます。

Fastbootの主な用途

  • カスタムリカバリの導入: TWRP (Team Win Recovery Project) のような高機能なカスタムリカバリをrecoveryパーティションにフラッシュします。これにより、システムの完全なバックアップやカスタムROMのインストールが可能になります。
  • カスタムROMやファクトリーイメージの書き込み: デバイスを工場出荷状態に戻すための公式ファクトリーイメージや、LineageOSのようなサードパーティ製のカスタムROMをsystembootパーティションにフラッシュします。
  • ブートローダーのアンロック/ロック: Fastbootコマンドを使用するための前提条件として、ブートローダーをアンロックする必要があります。この操作自体もFastbootを介して行います。

Fastbootは「デバイスの設計図を直接書き換えるための外科手術用メス」と考えることができます。非常に強力ですが、誤った操作はデバイスを起動不能(文鎮化)にするリスクも伴います。

1.3 ADBとFastbootの決定的な違い

両者の違いを明確に理解することが、適切な場面で適切なツールを使い分ける鍵となります。

項目 ADB (Android Debug Bridge) Fastboot
動作モード Android OSが起動している状態、またはリカバリーモード ブートローダーモード(Fastbootモード)
主な目的 OSとの対話、デバッグ、ファイル転送、アプリ管理 パーティションの書き換え(フラッシュ)、システムの根本的な変更
前提条件 デバイス側で「USBデバッグ」が有効になっていること デバイスがブートローダーモードで起動しており、多くの場合「ブートローダーがアンロック」されていること
リスク 比較的低い。誤ったコマンドでもOSの再起動で回復することが多い。 高い。重要なパーティションを誤って書き換えるとデバイスが起動しなくなる可能性がある。
比喩 「OSと会話する通訳者」 「システムの設計図を書き換える外科医」

この違いを念頭に置き、次の章ではこれらのツールを実際に使用するための環境構築に進みます。

第2章:環境構築 - ADBとFastbootの導入と準備

強力なツールも、正しくセットアップされていなければ使うことはできません。この章では、Androidデバイスとコンピュータの両方で必要な準備を、OSごとに詳しく解説します。

2.1 Androidデバイス側の準備:開発者向けオプションの有効化

ADBを使用するには、まずお使いのAndroidデバイスで隠された設定メニューである「開発者向けオプション」を有効にする必要があります。

  1. 「設定」アプリを開く: デバイスのアプリ一覧から「設定」を探してタップします。
  2. 「デバイス情報」または「タブレット情報」へ移動: メニューの最下部にあることが多いです。
  3. 「ビルド番号」を探す: 「ソフトウェア情報」などのサブメニュー内にある場合があります。
  4. 「ビルド番号」を連続でタップする: 「ビルド番号」の項目を7回連続で素早くタップします。タップするたびに「デベロッパーになるまであとXステップです」というメッセージが表示されます。
  5. 開発者向けオプションの有効化: 7回タップすると、PINやパスワードの入力を求められた後、「これでデベロッパーになりました!」というメッセージが表示されます。
  6. 「開発者向けオプション」メニューへのアクセス: 「設定」メニューのメイン画面に戻ると、「システム」の中など、新たに追加された「開発者向けオプション」という項目が見つかります。

次に、開発者向けオプションの中で、ADBとFastbootに必要な設定を有効にします。

  • USBデバッグを有効にする: 「開発者向けオプション」メニューに入り、「USBデバッグ」という項目のスイッチをオンにします。警告メッセージが表示されますが、内容を理解した上で「OK」をタップします。これにより、USB接続を介したADB通信が許可されます。
  • (Fastboot用) OEMロック解除を有効にする: 同じく「開発者向けオプション」メニュー内にある「OEMロック解除」のスイッチをオンにします。これもPINやパスワードの入力と警告の確認が必要です。この設定は、Fastbootでブートローダーをアンロックするために必須です。この項目がないデバイスは、基本的にブートローダーのアンロックがメーカーによって許可されていません。

2.2 コンピュータ側の準備:プラットフォームツールのインストール

ADBとFastbootは、Googleが公式に提供している「SDK Platform-Tools」パッケージに含まれています。OSごとにインストール方法が異なります。

Windowsでのインストール

  1. Platform-Toolsのダウンロード: Android SDK Platform-Toolsの公式ページにアクセスし、「Download SDK Platform-Tools for Windows」のリンクをクリックしてZIPファイルをダウンロードします。
  2. ファイルの展開: ダウンロードしたZIPファイルを、わかりやすい場所(例: C:\platform-tools)に展開(解凍)します。フォルダ名に日本語やスペースが含まれない、シンプルなパスが推奨されます。
  3. 環境変数(PATH)の設定: これが最も重要なステップです。PATHを設定することで、コマンドプロンプトのどの場所からでもadbfastbootコマンドを実行できるようになります。
    1. スタートボタンを右クリックし、「システム」を選択します。
    2. 「システムの詳細設定」または「関連設定」内の「システムの詳細情報」をクリックします。
    3. 「システムのプロパティ」ウィンドウで「環境変数」ボタンをクリックします。
    4. 「システム環境変数」のリストから「Path」を選択し、「編集」をクリックします。
    5. 「新規」をクリックし、先ほど展開したフォルダのパス(例: C:\platform-tools)を入力して「OK」をクリックします。
    6. すべてのウィンドウを「OK」で閉じて設定を保存します。
  4. USBドライバのインストール: 多くのデバイスはWindowsに接続すると自動で認識されますが、特にFastbootモードで認識されない場合は、メーカー固有のUSBドライバが必要です。Google Pixelデバイスの場合は「Google USB Driver」を、その他のメーカー(Samsung, Sonyなど)の場合は各社のサポートページからドライバをダウンロードしてインストールしてください。

macOSでのインストール

macOSでは、手動でインストールする方法と、パッケージマネージャーであるHomebrewを使用する方法があります。

方法1: 手動インストール

  1. Platform-Toolsのダウンロード: 公式ページから「Download SDK Platform-Tools for Mac」を選択してZIPファイルをダウンロードします。
  2. ファイルの展開: ダウンロードしたZIPファイルをダブルクリックして展開します。例えば ~/platform-tools に配置します。
  3. PATHの設定:
    1. ターミナルアプリを開きます。
    2. お使いのシェルに合わせて設定ファイルを編集します(最近のmacOSはzshが標準です)。nano ~/.zshrc と入力します。
    3. ファイルの末尾に次の行を追加します。パスは実際に展開した場所に合わせてください。
      export PATH=$PATH:~/platform-tools
    4. Control + Xを押し、YEnterと続けてファイルを保存します。
    5. ターミナルで source ~/.zshrc を実行するか、ターミナルを再起動して変更を適用します。

方法2: Homebrewを使用(推奨)

Homebrewがインストールされている場合、非常に簡単にインストールできます。

  1. ターミナルを開きます。
  2. 次のコマンドを実行するだけです:
    brew install --cask android-platform-tools
  3. Homebrewが自動的にPATHを設定してくれるため、手動での設定は不要です。

Linux (Debian/Ubuntu系) でのインストール

Linuxでもパッケージマネージャーを使うのが最も簡単です。

  1. ターミナルを開きます。
  2. 次のコマンドでパッケージリストを更新し、ツールをインストールします:
    sudo apt update
    sudo apt install android-sdk-platform-tools
  3. udevルールの設定 (重要): Linuxでは、一般ユーザーがUSBデバイスに直接アクセスするためにパーミッションの設定が必要になる場合があります。
    1. ターミナルで lsusb を実行し、接続したAndroidデバイスのIDを確認します(例: Bus 001 Device 005: ID 18d1:4ee7 Google Inc.)。18d1がベンダーIDです。
    2. udevルールファイルを作成します: sudo nano /etc/udev/rules.d/51-android.rules
    3. ファイルに以下の内容を記述します。idVendorの部分は自分のデバイスのものに置き換えてください。
      SUBSYSTEM=="usb", ATTR{idVendor}=="18d1", MODE="0666", GROUP="plugdev"
    4. ファイルを保存し、パーミッションを適用します: sudo udevadm control --reload-rules
    5. デバイスを再接続すると、正しく認識されるはずです。

2.3 接続の確認:最初のコミュニケーション

すべての設定が完了したら、実際にデバイスとコンピュータが通信できるか確認します。

  1. コマンドプロンプト/ターミナルを開く: WindowsならコマンドプロンプトやPowerShell、macOS/Linuxならターミナルを開きます。
  2. バージョン確認: インストールとPATH設定が正常に行われたかを確認するために、次のコマンドを実行します。バージョン情報が表示されれば成功です。
    adb version
  3. デバイスをUSBで接続: USBデバッグを有効にしたAndroidデバイスを、品質の良いUSBケーブルでコンピュータに接続します。
  4. USBデバッグの許可: デバイスの画面に「USBデバッグを許可しますか?」というポップアップが表示されます。コンピュータのRSAキーフィンガープリントが表示されるので、内容を確認し、「このパソコンからのUSBデバッグを常に許可する」にチェックを入れて「許可」または「OK」をタップします。これはセキュリティのための重要なステップです。
  5. ADB接続の確認: ターミナルで次のコマンドを実行します。
    adb devices

    次のように表示されれば、ADB接続は成功です。
    List of devices attached
    XXXXXXXXXXXXXX device
    (XXXXXXXXXXXXXXはデバイスのシリアルナンバーです)

    もし unauthorized と表示された場合は、デバイス側の許可ポップアップが正しく処理されていません。もう一度確認してください。offlineと表示される場合は、ケーブルやポート、ドライバの問題が考えられます。

  6. Fastboot接続の確認:
    1. まず、ADBコマンドでデバイスをブートローダーモードに再起動します。
      adb reboot bootloader
    2. デバイスが再起動し、ドロイド君が描かれた黒い画面(メーカーによって異なります)が表示されます。これがブートローダーモードです。
    3. 次に、ターミナルでFastbootの接続を確認します。
      fastboot devices
    4. ADBと同様に、シリアルナンバーと fastboot という文字が表示されれば成功です。
      XXXXXXXXXXXXXX fastboot
    5. 確認が終わったら、通常のAndroid OSに再起動します。
      fastboot reboot

これらの確認作業がすべて成功すれば、環境構築は完了です。次の章から、いよいよ具体的なコマンドの世界に飛び込みます。

第3章:コマンド詳解 - ADBでデバイスを自在に操る

この章では、ADBの多岐にわたるコマンドを機能別に分類し、具体的な使用例とともに詳しく解説します。これらのコマンドを習得することで、日常的なタスクの自動化から高度なトラブルシューティングまで、幅広い操作が可能になります。

3.1 基本的な接続とデバイス管理

これらのコマンドは、ADBの基本中の基本であり、デバイスとの接続状態を確認したり、サーバーを管理したりするために使用します。

  • 接続デバイスの確認:
    adb devices

    接続されているデバイスのシリアルナンバーと状態(device, offline, unauthorized)を表示します。-lオプションを付けると、モデル名などの詳細情報も表示されます。
    adb devices -l

  • ADBサーバーの制御:

    接続が不安定な場合や、ADBが応答しない場合に役立ちます。

    adb kill-server   # ADBサーバーを停止
    adb start-server  # ADBサーバーを起動

    通常、adb kill-serverの後に何らかのadbコマンドを実行すると、サーバーは自動的に再起動します。

  • デバイスの再起動:

    様々なモードでデバイスを再起動できます。

    adb reboot              # 通常の再起動
    adb reboot recovery     # リカバリーモードで再起動
    adb reboot bootloader   # ブートローダー(Fastboot)モードで再起動
  • デバイス情報の取得:
    adb get-serialno    # シリアルナンバーを取得
    adb get-state       # デバイスの状態(device, recovery, bootloader)を取得

3.2 アプリケーション(パッケージ)管理

Androidでは、アプリはパッケージ(APKファイル)として管理されています。ADBを使えば、GUIを介さずにアプリのインストールやアンインストール、データ管理が可能です。

  • アプリのインストール:
    adb install <path/to/app.apk>

    コンピュータ上にあるAPKファイルをデバイスにインストールします。便利なオプションも多数あります。

    • -r: アプリが既に存在する場合に、データを保持したまま上書きインストールします。
    • -d: ダウングレード(古いバージョンのインストール)を許可します。
    • -g: インストール時に、マニフェストで定義されている全てのランタイムパーミッションを許可します。(Android 6.0以降)

    例: adb install -r -g my-app-v2.apk

  • 複数APKのインストール(Split APKs):
    adb install-multiple <app.apk> <split1.apk> <split2.apk>

    ベースAPKと分割された設定APKなどをまとめてインストールします。

  • アプリのアンインストール:
    adb uninstall <package.name>

    パッケージ名を指定してアプリをアンインストールします。-kオプションを付けると、アプリ本体は削除されますが、データとキャッシュは保持されます。
    adb uninstall -k com.example.app

  • パッケージ名を確認する方法:
    adb shell pm list packages

    デバイスにインストールされている全てのパッケージ名の一覧を表示します。非常に長大なリストになるため、grep(macOS/Linux)やfindstr(Windows)と組み合わせて特定のアプリを探すと便利です。

    例 (Linux/macOS): adb shell pm list packages | grep "google"

  • アプリデータの消去:
    adb shell pm clear <package.name>

    特定のアプリのデータを消去し、インストール直後の状態に戻します。設定アプリから「ストレージを消去」を実行するのと同じ効果です。

3.3 ファイルシステムの操作

デバイスとコンピュータ間でファイルをやり取りするためのコマンドです。

  • デバイスからコンピュータへファイルをコピー:
    adb pull <device/path/to/file> <local/path/to/destination>

    例: スクリーンショットフォルダ全体をカレントディレクトリにコピーする
    adb pull /sdcard/Pictures/Screenshots/ .

  • コンピュータからデバイスへファイルをコピー:
    adb push <local/path/to/file> <device/path/to/destination>

    例: ダウンロードした音楽ファイルをデバイスのMusicフォルダにコピーする
    adb push my_song.mp3 /sdcard/Music/

3.4 ADB Shell:デバイス内部へのアクセス

adb shellは、デバイス上で直接Linuxコマンドを実行するための強力な機能です。これにより、GUIでは不可能な高度な操作が実現できます。

adb shell

このコマンドを実行すると、プロンプトがデバイス側のものに変わります。ここから先は、デバイス上でコマンドを実行していることになります。exitで元のプロンプトに戻れます。また、adb shell "command"のように、ワンライナーでコマンドを実行することも可能です。

便利なシェルコマンドの例

  • 画面の解像度と密度を確認/変更:
    # 確認
    adb shell wm size
    adb shell wm density
    
    # 変更 (注意: 予期せぬ表示崩れが起きる可能性あり)
    adb shell wm size 1080x1920
    adb shell wm density 420
    
    # 元に戻す
    adb shell wm size reset
    adb shell wm density reset
  • スクリーンショットを撮る:
    adb shell screencap /sdcard/screenshot.png
    adb pull /sdcard/screenshot.png

    デバイスのSDカードにスクリーンショットを保存し、それをPCにコピーする一連の流れです。

  • 画面を録画する:
    adb shell screenrecord /sdcard/myvideo.mp4

    録画を開始します。停止するにはCtrl + Cを押します。録画したファイルはadb pullでPCにコピーできます。--time-limit--sizeなどのオプションもあります。

  • キーイベントを送信:
    adb shell input keyevent <keycode>

    物理ボタンの押下をシミュレートします。主なキーコードは以下の通りです。

    • 3: HOME
    • 4: BACK
    • 26: POWER
    • 24: VOLUME_UP
    • 25: VOLUME_DOWN
    • 82: MENU

    例: 電源ボタンを押して画面をオン/オフする
    adb shell input keyevent 26

  • テキストを入力:
    adb shell input text "Hello Android"

    現在フォーカスが当たっているテキストフィールドに文字列を直接入力します。スペースは%sで表現します。
    adb shell input text "Hello%sAndroid"

3.5 デバッグと情報収集

ADBの本来の目的であるデバッグに関連するコマンドは、トラブルシューティングに絶大な効果を発揮します。

  • Logcat: システムログの表示:
    adb logcat

    デバイスで発生している全てのシステムイベントやアプリのログをリアルタイムで表示します。情報量が膨大なので、フィルタリングが重要です。

    • タグでフィルタ: adb logcat -s "MyTag" (MyTagというタグの付いたログのみ表示)
    • 優先度でフィルタ: ログには優先度(V: Verbose, D: Debug, I: Info, W: Warn, E: Error, F: Fatal, S: Silent)があります。
      adb logcat *:E (Error以上のログを全て表示)
    • 特定のアプリのログのみ表示:
      # まずアプリのプロセスID(PID)を調べる
      adb shell pidof com.example.app
      # PIDを指定してlogcatを実行
      adb logcat --pid=<PID>
    • ログをファイルに出力: adb logcat -d > log.txt
  • バグレポートの生成:
    adb bugreport ./bugreport-data

    デバイスの状態、ログ、各種情報を含む詳細なバグレポート(ZIPファイル)を生成します。アプリ開発者に問題を報告する際に非常に役立ちます。

  • システムサービス情報のダンプ:
    adb shell dumpsys <service>

    Androidの様々なシステムサービスの状態をダンプ(詳細表示)します。非常に多くの情報が含まれており、特定の情報を探すにはgrepなどとの組み合わせが必須です。

    例:

    # バッテリー状態の詳細情報を表示
    adb shell dumpsys battery
    
    # 現在のアクティビティスタックを表示
    adb shell dumpsys activity activities
    
    # ネットワークポリシー情報を表示
    adb shell dumpsys netpolicy

これらのADBコマンドを組み合わせることで、デバイスの挙動を深く理解し、様々な問題を解決する糸口を見つけることができます。

第4章:システムの核心に触れる - Fastbootコマンドの威力

Fastbootは、デバイスのソフトウェアの基盤を直接操作するためのコマンドです。ADBよりも低レベルで動作するため、より強力で、同時にリスクも高まります。この章のコマンドを実行する前には、必ずデータのバックアップを取り、これから行う操作の意味を完全に理解してください。

4.1 最も重要なステップ:ブートローダーのアンロック

ほとんどのFastbootコマンド、特にパーティションを書き換えるflashコマンドを使用するには、まずブートローダーをアンロックする必要があります。

警告: ブートローダーのアンロック操作は、デバイス上の全てのユーザーデータ(写真、アプリ、設定など)を完全に消去し、工場出荷状態に戻します。また、多くのメーカーでは保証が無効になります。

  1. 前提条件の確認:
    • 第2章で解説した通り、デバイスの「開発者向けオプション」で「OEMロック解除」が有効になっていることを確認します。
    • 重要なデータのバックアップが完了していることを確認します。
  2. ブートローダーモードへの移行:
    adb reboot bootloader
  3. アンロックコマンドの実行:

    コマンドはデバイスの世代によって異なります。

    比較的新しいデバイス (Pixel 2以降など):

    fastboot flashing unlock

    古いデバイス:

    fastboot oem unlock
  4. デバイス上での確認:

    コマンド実行後、デバイスの画面にアンロックを最終確認するメッセージが表示されます。音量ボタンで「Yes」や「Unlock the bootloader」を選択し、電源ボタンで決定します。この操作を完了すると、デバイスのデータが消去され、再起動します。

アンロックが完了すると、デバイス起動時に「The bootloader is unlocked...」という警告メッセージが表示されるようになります。これは正常な状態です。

ブートローダーを再ロックする

デバイスを売却する際など、セキュリティ上の理由からブートローダーを再ロックしたい場合があります。注意: 再ロックする前に、必ずデバイスが完全にストック(公式)の状態に戻っていることを確認してください。カスタムROMなどがインストールされた状態で再ロックすると、デバイスが起動しなくなる(ハードブリック)危険性があります。

# 新しいデバイス
fastboot flashing lock

# 古いデバイス
fastboot oem lock

この操作も同様に、デバイス上で最終確認が必要です。

4.2 パーティションへの書き込み:fastboot flash

fastboot flashは、Fastbootの核となるコマンドです。指定したパーティションに、指定したイメージファイル(.img)を書き込みます。

fastboot flash <partition_name> <filename.img>

主なパーティションとフラッシュの例

  • リカバリ (recovery):

    TWRPのようなカスタムリカバリを導入する際に使用します。これにより、NandroidバックアップやカスタムROMのインストールが可能になります。

    fastboot flash recovery twrp-3.7.0_12-0-oriole.img
  • ブート (boot):

    カーネルとRAMディスクを含むブートイメージを書き込みます。Magiskでパッチを当てたブートイメージをフラッシュしてroot化したり、カスタムカーネルを導入したりする際に使用します。

    fastboot flash boot magisk_patched-26400_abcdef.img
  • システム (system):

    Android OS本体を書き込みます。カスタムROMのイメージや、工場出荷時のファクトリーイメージをフラッシュする際に使用されます。(最近のデバイスでは、systemイメージが巨大なため、直接フラッシュすることは稀で、リカバリ経由でZIPファイルをインストールすることが多いです)

    fastboot flash system system.img

他にもvendor, vbmeta, radioなど、デバイスのファクトリーイメージには多くのパーティションイメージが含まれており、それらを一括で書き込むためのスクリプト(flash-all.batflash-all.sh)が同梱されていることが一般的です。

4.3 A/Bパーティションスキームの理解

近年のAndroidデバイスの多くは、シームレスアップデートを実現するためにA/Bパーティションスキームを採用しています。これは、bootsystemといった重要なパーティションがAとBの2つのスロット(例: boot_a, boot_b)を持っていることを意味します。

ユーザーがスロットAでデバイスを使用している間に、OTAアップデートは非アクティブなスロットBにバックグラウンドで適用されます。次回の再起動時に、デバイスはスロットBから起動し、ユーザーはダウンタイムなしでアップデートを完了できます。もしスロットBでの起動に失敗した場合は、自動的にスロットAにフォールバックする安全性も備えています。

A/BデバイスでのFastboot操作

このスキームにより、Fastbootのコマンドも少し変わります。

  • 現在のアクティブなスロットを確認:
    fastboot getvar current-slot

    出力は a または b になります。

  • 特定のスロットにフラッシュ:

    パーティション名の末尾に _a または _b を付けます。

    fastboot flash boot_a magisk_patched.img
    fastboot flash boot_b magisk_patched.img

    通常、両方のスロットに同じイメージをフラッシュすることが推奨されます。

  • アクティブなスロットを切り替え:
    fastboot --set-active=a
    fastboot --set-active=b
  • リカバリパーティションの不在:

    A/Bデバイスには、独立したrecoveryパーティションが存在しません。リカバリ機能はbootパーティションに統合されています。そのため、TWRPなどを導入する場合、fastboot flash recoveryではなく、fastboot flash boot を使用するか、後述のfastboot bootコマンドで一時的に起動します。

4.4 その他の重要なFastbootコマンド

  • 一時的なイメージの起動: fastboot boot
    fastboot boot <filename.img>

    このコマンドは、イメージをデバイスに恒久的にフラッシュするのではなく、そのイメージを使って一度だけデバイスを起動します。特にカスタムリカバリを試す際に非常に便利です。TWRPのイメージをこのコマンドで起動し、動作に問題がないことを確認してから、TWRP自体を使って恒久的にインストールすることができます。

    例: fastboot boot twrp.img

  • パーティションの消去: fastboot erase / format
    fastboot erase <partition_name>

    指定したパーティションのデータを消去します。ファクトリーリセットを行う際によく使われます。

    # ユーザーデータを全て消去 (工場出荷状態に戻す)
    fastboot erase userdata
    
    # キャッシュを消去
    fastboot erase cache

    formatコマンドも同様の目的で使用されますが、ファイルシステムを指定できる場合があります。通常はeraseで十分です。

  • デバイス情報の取得: fastboot getvar
    fastboot getvar <variable>

    ブートローダーが保持している様々な情報を取得できます。allを指定すると、全ての情報を一度に表示します。

    例: fastboot getvar all

    出力には、製品名、シリアルナンバー、ブートローダーのバージョン、パーティション情報、現在のスロットなど、非常に多くの有用な情報が含まれています。

第5章:問題解決 - 一般的なトラブルシューティング

ADBとFastbootは強力なツールですが、環境設定や操作の過程で様々な問題に遭遇することがあります。この章では、よくあるエラーメッセージとその原因、そして解決策を解説します。

5.1 接続に関する問題

エラー: `adb: command not found` (Linux/macOS) または `'adb' is not recognized as an internal or external command...` (Windows)

  • 原因: このエラーは、システムがadbコマンドの実行ファイルを見つけられないことを意味します。最も一般的な原因は、Platform-Toolsのフォルダへのパスが環境変数PATHに正しく設定されていないことです。
  • 解決策:
    1. 第2章の環境変数設定の手順を再度確認してください。パスのスペルミスがないか、フォルダの場所が正しいかを確認します。
    2. Windowsでは、環境変数を設定した後に開いていたコマンドプロンプトは、一度閉じてから新しく開く必要があります。
    3. 一時的な解決策として、コマンドプロンプト/ターミナルでPlatform-Toolsのフォルダに直接移動(cd C:\platform-toolsなど)してから、./adb(Linux/macOS)やadb(Windows)コマンドを実行することもできます。

`adb devices`で `unauthorized` と表示される

  • 原因: コンピュータがデバイスに接続しようとしましたが、デバイス側でUSBデバッグが許可されていません。
  • 解決策:
    1. デバイスの画面に「USBデバッグを許可しますか?」というポップアップが表示されていないか確認し、表示されていれば許可します。
    2. ポップアップが表示されない場合、一度USBケーブルを抜き差ししてみてください。
    3. 「開発者向けオプション」メニュー内にある「USBデバッグ許可の取り消し」を実行し、再度ケーブルを接続してポップアップを再表示させます。
    4. adb kill-serveradb start-serverを実行してADBサーバーを再起動してみます。

`adb devices`で `offline` と表示される、または何も表示されない

  • 原因: 物理的な接続に問題があるか、ドライバが正しく動作していない可能性があります。
  • 解決策:
    1. USBケーブルとポートを確認: 最も多い原因です。データ転送に対応した品質の良いUSBケーブルを使用してください(充電専用ケーブルでは動作しません)。コンピュータの別のUSBポート(特にUSB 2.0ポート)に接続してみることも有効です。USBハブを介している場合は、直接接続を試してください。
    2. ドライバの確認 (Windows): デバイスマネージャーを開き、デバイスが「ADB Interface」や「Android Device」として正しく認識されているか確認します。黄色の感嘆符が付いている場合は、ドライバに問題があります。
    3. USBデバッグの再有効化: デバイスの「開発者向けオプション」で、USBデバッグを一度オフにしてから再度オンにしてみます。

5.2 Fastboot実行時のエラー

`fastboot devices`で何も表示されない

  • 原因: デバイスがFastbootモードで正しく認識されていません。
  • 解決策:
    1. デバイスが確実にブートローダー/Fastbootモードで起動しているか確認します。
    2. ADBと同様に、USBケーブルとポートの問題を確認します。
    3. ドライバの問題 (Windows): Fastbootモード用のドライバは、ADBモード用のドライバとは別物です。デバイスをFastbootモードで接続した状態でデバイスマネージャーを開き、「Android Device」カテゴリの下に「Android Bootloader Interface」のようなデバイスが表示されているか確認します。もし認識されていない場合は、Google USB Driverやメーカー提供のドライバを再度インストールする必要があります。

エラー: `FAILED (remote: 'flashing is not allowed')` または `FAILED (remote: 'oem unlock is not allowed')`

  • 原因: ブートローダーがロックされた状態で、フラッシュやアンロックを試みようとしたか、あるいはデバイス側でOEMロック解除が許可されていません。
  • 解決策:
    1. Android OSを起動し、「開発者向けオプション」内の「OEMロック解除」がオンになっていることを確認します。グレーアウトしていて操作できない場合、そのデバイスはメーカーによってアンロックが許可されていません。
    2. fastboot flashコマンドを実行する前に、ブートローダーがアンロックされていることを確認してください。

エラー: `FAILED (remote: 'partition not found')`

  • 原因: 存在しないパーティション名を指定してフラッシュしようとしました。
  • 解決策: パーティション名のスペルが正しいか確認してください。A/Bパーティションデバイスの場合、recoveryパーティションは存在しないかもしれません。fastboot getvar allを実行して、デバイスに存在するパーティションの一覧を確認するのが確実です。

5.3 Windowsにおけるドライバー問題

Windowsユーザーにとって、ドライバの問題は最も頻繁に遭遇する障壁です。デバイスマネージャーでの手動インストール方法を覚えておくと非常に役立ちます。

  1. デバイスをADBモードまたはFastbootモードでPCに接続します。
  2. デバイスマネージャーを開き、認識されていないデバイス(通常は黄色の感嘆符付き)を右クリックして「ドライバーの更新」を選択します。
  3. 「コンピューターを参照してドライバーを検索」を選択します。
  4. 「コンピューター上の利用可能なドライバーの一覧から選択します」をクリックします。
  5. 「すべてのデバイスを表示」を選択して「次へ」をクリックします。
  6. 「ディスク使用」ボタンをクリックし、「参照」からダウンロード・展開したGoogle USB Driverフォルダ内のandroid_winusb.infファイルを選択します。
  7. モデルの一覧から「ADB Interface」(ADBモードの場合)または「Bootloader Interface」(Fastbootモードの場合)を選択してインストールします。警告が表示されても続行してください。

この手順により、多くのドライバ関連の問題を強制的に解決することができます。

第6章:実践的応用例と今後の展望

これまでに学んだ知識を統合し、ADBとFastbootが実際にどのように活用されるのかを具体的なシナリオを通じて見ていきましょう。これらの応用例は、Androidカスタマイズの世界への入り口となります。

6.1 OTAアップデートのサイドロード

メーカーからのOTA (Over-The-Air) アップデートは、通常、段階的に配信されるため、自分のデバイスに届くまで数週間かかることがあります。ADBのsideload機能を使えば、公式のアップデートZIPファイルを手動で適用し、誰よりも早く最新バージョンを手にすることができます。

手順

  1. OTA ZIPファイルの入手: メーカーの公式サイトや、XDA-Developersのようなコミュニティフォーラムから、お使いのデバイスモデルと現在のビルド番号に対応したOTAアップデートのZIPファイルを入手します。
  2. リカバリーモードへの移行:
    adb reboot recovery
  3. ADBからのアップデート適用を選択: デバイスがストックリカバリで起動したら、音量ボタンで「Apply update from ADB」を選択し、電源ボタンで決定します。
  4. サイドロードの実行: デバイスの画面に指示が表示されたら、PCのターミナルで以下のコマンドを実行します。
    adb sideload <path/to/ota-file.zip>
  5. 処理の完了を待つ: ファイルの検証とインストールが始まります。デバイスとターミナルの両方で進捗が確認できます。完了したら、リカバリメニューから「Reboot system now」を選択してデバイスを再起動します。

この方法は、アップデートを待てない場合だけでなく、何らかの理由でOTAが失敗するデバイスを修復する際にも有効です。

6.2 カスタムリカバリ(TWRP)の導入

TWRP (Team Win Recovery Project) は、Androidデバイスで最も人気のあるカスタムリカバリです。システムの完全なバックアップ(Nandroidバックアップ)、カスタムROMのインストール、root化など、高度なカスタマイズの基盤となります。

手順(非A/Bデバイスの例)

  1. ブートローダーのアンロック: 第4章で解説した手順で、ブートローダーをアンロックします。
  2. TWRPイメージの入手: TWRP公式サイトから、お使いのデバイス用の最新の.imgファイルをダウンロードします。
  3. ブートローダーモードへの移行:
    adb reboot bootloader
  4. TWRPの一時起動(推奨): まずはfastboot bootでTWRPが正常に動作するかテストします。
    fastboot boot twrp-image.img
  5. TWRPの恒久的なインストール: デバイスがTWRPで起動し、タッチ操作などが問題ないことを確認できたら、TWRPをrecoveryパーティションにフラッシュします。
    fastboot flash recovery twrp-image.img

    または、一時起動したTWRPの「Install」メニューからTWRPイメージファイル自身をRecovery Ramdiskとしてインストールすることもできます。

  6. リカバリへの再起動: フラッシュ後、fastboot reboot recoveryなどでTWRPが起動することを確認します。

6.3 Magiskによるシステム改変

Magiskは、現在の主流となっているroot化ツールであり、システムパーティションを直接変更しない「システムレス」な改変を可能にします。これにより、セーフティネット(SafetyNet)を回避し、銀行アプリなどが動作しやすくなるという利点があります。

手順

  1. ストックブートイメージの入手: お使いのデバイスの現在のファームウェアに対応するストック(公式)のboot.imgを入手します。ファクトリーイメージから抽出するのが一般的です。
  2. Magiskアプリのインストール: Magiskの公式GitHubリリースページから最新のMagiskアプリのAPKをダウンロードし、デバイスにインストールします。
  3. ブートイメージへのパッチ適用:
    1. 入手したストックboot.imgをデバイスの内部ストレージにコピーします。
    2. Magiskアプリを開き、「インストール」ボタンをタップします。
    3. 「メソッド」として「ファイルを選択してパッチを当てる」を選び、先ほどコピーしたboot.imgを選択します。
    4. Magiskがパッチ処理を行い、Downloadフォルダ内にmagisk_patched-....imgという名前の新しいイメージファイルを生成します。
  4. パッチ適用済みイメージのフラッシュ:
    1. 生成されたmagisk_patched-....imgファイルをPCにコピーします(adb pullを使用)。
    2. デバイスをブートローダーモードで再起動します(adb reboot bootloader)。
    3. パッチ適用済みのブートイメージをフラッシュします。
      fastboot flash boot magisk_patched-....img
  5. 再起動と確認: fastboot rebootでデバイスを再起動します。Magiskアプリを開き、インストール状態がバージョン番号で表示されていればroot化は成功です。

6.4 結び:責任あるカスタマイズのために

ADBとFastbootは、Androidデバイスの可能性を無限に広げるための強力な鍵です。この記事で紹介したコマンドや手順は、その広大な世界のほんの入り口に過ぎません。しかし、この力には大きな責任が伴います。

  • 常にバックアップを: 重要な操作の前には、必ずデータのバックアップを取る習慣をつけましょう。
  • 正確な情報を: お使いのデバイスモデルに特化した情報を、XDA-Developersのような信頼できるコミュニティで必ず確認してください。誤ったファイルや手順は、デバイスを文鎮化させる可能性があります。
  • リスクを理解する: ブートローダーのアンロックやシステムの改変は、セキュリティを低下させ、メーカーの保証を無効にする行為です。そのリスクを理解した上で、自己責任で行ってください。

これらの注意点を守り、探求心を忘れなければ、ADBとFastbootはあなたのAndroidライフをより豊かで自由なものにする、最高の相棒となるでしょう。システムの仕組みを学び、問題を自力で解決し、最終的には世界中の開発者が作り上げたカスタムROMやMODを導入して、真に「あなただけの」デバイスを創造することが可能になるのです。

Android's Command Line Interface: A Deep Dive into ADB and Fastboot

Chapter 1: The Foundations of Android Communication

At the heart of Android's open-source nature lies a powerful set of tools that grants developers, power users, and enthusiasts unparalleled access to the inner workings of the operating system. These tools, Android Debug Bridge (ADB) and Fastboot, serve as the primary command-line interfaces for communicating with an Android device from a computer. While often mentioned in the same breath, they operate in fundamentally different environments and serve distinct, yet complementary, purposes. Understanding their roles, architecture, and the necessary security precautions is the first critical step toward mastering your Android device.

What Are ADB and Fastboot?

Android Debug Bridge (ADB) is a versatile and robust command-line tool that facilitates communication with a running Android device. This "bridge" allows you to send a wide array of commands to the device, whether it's a physical phone, tablet, watch, or even an emulator. Its primary purpose, as the name suggests, is for application development and debugging. Developers use it to install and test applications, view real-time system logs, and inspect device state. However, its utility extends far beyond development. For power users, ADB is the key to managing files, installing apps without the Play Store (sideloading), creating full backups, and performing advanced system tweaks that are impossible through the standard user interface.

Fastboot, on the other hand, is a protocol and tool for communicating with an Android device when it is in a special pre-boot state known as the bootloader. The bootloader is a small piece of code that runs before the main Android operating system starts. Its job is to initialize the hardware and then load the Android kernel and system. Because Fastboot operates at this fundamental level, it is used for more drastic, system-altering tasks. These include unlocking the bootloader (a prerequisite for most deep modifications), flashing factory images to restore the device to its original state, and installing custom recoveries or operating systems (ROMs).

In essence, think of the relationship like this: ADB is your tool for interacting with a fully conscious and running Android system, while Fastboot is the tool you use for performing surgery on the system's core components before it even wakes up.

The Three Pillars: Understanding ADB's Architecture

ADB's functionality is not based on a single program but a client-server system composed of three distinct components that work in unison:

  1. The Client: This is the component that runs on your computer (e.g., Windows, macOS, or Linux). When you type a command like adb devices into your terminal, you are interacting with the ADB client. The client's job is to translate your command and send it to the ADB server.
  2. The Server: This is a background process that also runs on your computer. The server acts as a manager and intermediary. It handles communication between the client and the ADB daemon on the Android device. It scans for connected devices, manages connections, and routes commands from the client to the appropriate device's daemon. You can interact with the server directly using commands like adb start-server and adb kill-server.
  3. The Daemon (adbd): This is a background process that runs on the Android device itself. The daemon is the component that listens for and executes the commands received from the ADB server via USB or Wi-Fi. It is the daemon that carries out the actual work on the device, such as installing an APK or copying a file.

When you execute an ADB command, the client checks if an ADB server process is running. If not, it starts one. The server then binds to a local TCP port (usually 5037) and scans for connected devices. Upon finding a device with USB Debugging enabled, it establishes a connection with the 'adbd' daemon on that device. From that point on, all commands are relayed through this established bridge.

Operational States: When to Use ADB vs. Fastboot

The most common point of confusion for newcomers is determining which tool to use. The answer lies entirely in the current state of your Android device.

  • Use ADB when...
    • The device is fully booted into the main Android operating system.
    • The device is booted into a custom recovery environment (like TWRP), as most modern recoveries have an ADB daemon built-in.
    • You need to interact with apps, files, or system settings on a running device.
    • You want to capture logs, take screenshots, or record the screen.
  • Use Fastboot when...
    • The device is powered on into its bootloader/fastboot mode. This is typically accessed by holding a specific key combination (e.g., Power + Volume Down) while booting the device, or by using the command adb reboot bootloader.
    • You need to flash factory images (e.g., `system.img`, `boot.img`).
    • You need to unlock or re-lock the bootloader.
    • The device is unable to boot into the main OS or recovery, making the bootloader the only accessible interface.

A device in fastboot mode will not respond to ADB commands, and a device booted into Android will not respond to Fastboot commands. They are mutually exclusive operating states.

Critical Security Prerequisites: USB Debugging and OEM Unlocking

Before you can use either of these powerful tools, you must explicitly grant permission on your Android device. These settings are intentionally hidden away in a "Developer options" menu to prevent average users from accidentally compromising their devices.

1. Enabling Developer Options:

  • Go to Settings > About phone.
  • Scroll down to the Build number.
  • Tap on the "Build number" entry seven times consecutively. You will see a toast notification counting down the remaining taps.
  • After the seventh tap, you will be prompted for your device's PIN, pattern, or password. Upon successful entry, a message will confirm, "You are now a developer!"
  • A new "Developer options" menu will now be available under Settings > System (the exact location can vary by manufacturer).

2. Enabling USB Debugging (for ADB):

  • Navigate to the newly unlocked Settings > System > Developer options.
  • Scroll down and find the toggle for USB debugging.
  • Enable it. A warning dialog will appear, explaining the security risks. You must accept this to proceed. This is what allows the 'adbd' daemon to run and accept connections.

3. Enabling OEM Unlocking (for Fastboot):

  • Within the same Developer options menu, find the toggle for OEM unlocking.
  • Enabling this option is a prerequisite for using the fastboot flashing unlock command. It essentially tells the bootloader that you authorize it to be unlocked.
  • Be warned: Enabling this and subsequently unlocking the bootloader will perform a factory reset, erasing all data on your device for security reasons. This is a non-negotiable security feature.

These settings act as the gatekeepers to your device's core. Without them, ADB and Fastboot commands will be ignored, ensuring the integrity and security of the device against unauthorized access.

Chapter 2: Setting Up Your Development Environment

Before you can issue a single command, you must properly install and configure ADB and Fastboot on your computer. This process involves downloading the official tools from Google, placing them in an accessible location, and configuring your system's "PATH" so that the commands can be run from any directory in your terminal. Additionally, for Windows users, installing the correct USB drivers is a critical step that is often a source of frustration.

The Official Source: Downloading the SDK Platform-Tools

In the past, ADB and Fastboot were only available as part of the massive Android SDK. Thankfully, Google now provides them as a lightweight, standalone package called SDK Platform-Tools. This is the only source you should use, as it guarantees you have the latest, most stable, and secure versions of the tools. Using outdated versions from unofficial sources can lead to compatibility issues and unpredictable errors.

  1. Navigate to the official SDK Platform-Tools download page on the Android developer website.
  2. You will see download links for Windows, macOS, and Linux.
  3. Download the appropriate ZIP file for your operating system.

Installation and Configuration on Windows

Windows requires two main steps: extracting the tools and configuring the system Environment Variables, followed by driver installation.

Step 1: Extract the Tools and Configure the PATH

  1. Once the ZIP file is downloaded, extract its contents. A good, permanent location is recommended, such as C:\platform-tools. Avoid placing it in temporary folders like 'Downloads' or on the Desktop.
  2. The extracted folder contains adb.exe, fastboot.exe, and other necessary files. Now, you need to tell Windows where to find these executables.
  3. Press the Windows key, type env, and select "Edit the system environment variables".
  4. In the System Properties window that opens, click the "Environment Variables..." button.
  5. In the bottom section, under "System variables", find and select the variable named Path, then click "Edit...".
  6. Click "New" and paste the full path to the folder where you extracted the tools (e.g., C:\platform-tools).
  7. Click "OK" on all open windows to save the changes. To apply the new PATH, you must close and reopen any existing Command Prompt or PowerShell windows.

Step 2: Install USB Drivers

This is the most crucial step on Windows. Without the correct drivers, your computer will not recognize your device in either ADB or Fastboot mode.

  • OEM Drivers: The most reliable option is to install the specific USB driver provided by your device's manufacturer (e.g., Samsung, OnePlus, Sony). A web search for "[Your Manufacturer] USB drivers" will usually lead you to the correct download.
  • Google USB Driver: For Google Pixel/Nexus devices, the Google USB Driver is required. It can be installed via the Android Studio SDK Manager or downloaded separately.
  • Verification: After connecting your device with USB Debugging enabled, open the Device Manager in Windows. You should see your device listed under "Android Device" or a similar category, typically as "Android Composite ADB Interface". If you see a yellow exclamation mark, the driver is not installed correctly.

Installation and Configuration on macOS

The process on macOS is more straightforward as it typically does not require manual driver installation.

Method 1: Manual Installation

  1. Download the platform-tools ZIP for Mac.
  2. Extract the contents. A common location is ~/Library/Android/sdk/platform-tools or simply a folder like ~/platform-tools.
  3. Open the Terminal application. You need to add the location to your shell's PATH. Modern macOS versions use Zsh, so you'll edit the .zshrc file. Older versions use Bash (.bash_profile).
  4. Type the command nano ~/.zshrc to open the editor.
  5. Add the following line to the file, replacing /path/to/your/platform-tools with the actual path where you extracted the folder:
    export PATH=$PATH:/path/to/your/platform-tools
  6. Press Ctrl+X to exit, then Y to save, and Enter to confirm the filename.
  7. Close and reopen the Terminal window, or run source ~/.zshrc to apply the changes immediately.

Method 2: Using Homebrew (Recommended)

The Homebrew package manager simplifies installation and updates.

  1. If you don't have Homebrew, install it by following the instructions on the official site (brew.sh).
  2. Open Terminal and run the following command:
    brew install --cask android-platform-tools
  3. Homebrew automatically handles the installation and PATH configuration.

Installation and Configuration on Linux

Linux offers flexibility with both manual and package manager installations. However, an extra step is required to grant your user account permission to access USB devices.

Method 1: Manual Installation

The process is nearly identical to macOS. You download and extract the tools, then add the folder's path to your shell's configuration file (commonly ~/.bashrc or ~/.zshrc) using the same export PATH=... syntax.

Method 2: Using a Package Manager (Recommended)

Most popular Linux distributions have platform-tools in their official repositories.

  • On Debian/Ubuntu-based systems:
    sudo apt update && sudo apt install adb
  • On Fedora/CentOS-based systems:
    sudo dnf install android-tools

Crucial Step: Configuring 'udev' Rules

On Linux, by default, regular users don't have permission to directly access USB hardware. This will cause ADB to show your device with "????????????" permissions. To fix this, you must create a `udev` rule.

  1. Create a new rules file: sudo nano /etc/udev/rules.d/51-android.rules
  2. Add a line for your device. A generic rule that covers most devices is:
    SUBSYSTEM=="usb", ATTR{idVendor}=="18d1", ATTR{idProduct}=="*", MODE="0666", GROUP="plugdev"
    (Note: You might need to find your device's specific `idVendor` using the `lsusb` command.)
  3. Save and exit the file.
  4. Apply the new permissions:
    sudo chmod a+r /etc/udev/rules.d/51-android.rules
    sudo udevadm control --reload-rules
    sudo udevadm trigger
  5. You may need to restart the ADB server (`adb kill-server`) and reconnect your device.

Verifying the Installation

Once you've completed the steps for your OS, verification is simple.

  1. Open a new terminal/command prompt window.
  2. Type adb version and press Enter. You should see the installed version information for the Android Debug Bridge. If you get a "command not found" error, your PATH was not set correctly.
  3. Enable USB Debugging on your Android device and connect it to your computer.
  4. On your device, you should see a prompt asking "Allow USB debugging?". Check the "Always allow from this computer" box and tap "Allow". This authorizes your computer's RSA key.
  5. In your terminal, type adb devices. You should see an output similar to this, indicating a successful connection:
    List of devices attached
    9A281FFBA001EH    device
                    

With the environment now correctly configured, you are ready to explore the vast capabilities of ADB and Fastboot.

Chapter 3: The Android Debug Bridge (ADB) Command Arsenal

ADB is far more than a simple file transfer utility. It is a comprehensive suite of tools for managing, controlling, and debugging an Android device. This chapter breaks down the most essential ADB commands, categorized by their function, with detailed explanations and practical examples.

Device Connection & Management

These commands form the foundation of any ADB interaction, allowing you to control the ADB server and manage device connections.

  • adb devices [-l]
    This is the most fundamental command. It queries the ADB server for a list of all connected devices.
    Example:
    $ adb devices
    List of devices attached
    emulator-5554   device
    ZY223JQ2G2      device
    The -l flag provides a more detailed output, including the device product and model name, which is useful when multiple devices are connected.
    $ adb devices -l
    List of devices attached
    ZY223JQ2G2      device product:grus model:Mi_9_SE device:grus transport_id:1
  • adb start-server / adb kill-server
    These commands give you manual control over the ADB server process on your computer. adb kill-server is particularly useful for troubleshooting when ADB becomes unresponsive or fails to detect a device. Running any other ADB command will automatically restart the server if it's not already running.
  • adb reconnect
    If a device becomes unresponsive or shows as "offline", this command attempts to re-establish the connection without physically unplugging and replugging the USB cable.
  • adb connect [ip_address]:[port]
    This command allows you to connect to a device over Wi-Fi, freeing you from the constraints of a USB cable. To use it, you must first enable Wireless Debugging in Developer Options or connect via USB once and run adb tcpip 5555. Then, you find your device's IP address and connect.
    Example: adb connect 192.168.1.100:5555

Application (Package) Management

ADB provides powerful tools for managing Android applications (APKs), referred to internally as packages.

  • adb install [options] [path_to_apk]
    Installs an application onto the device. This is known as "sideloading".
    Example: adb install my-app.apk
    Common options:
    • -r: Reinstall an existing app, keeping its data.
    • -d: Allow version code downgrade.
    • -g: Grant all permissions defined in the app's manifest upon installation.
  • adb uninstall [options] [package_name]
    Uninstalls an application. You need the application's package name (e.g., com.google.android.youtube), not the app's friendly name.
    Example: adb uninstall com.example.myapp
    The -k option is useful for removing the app but keeping its data and cache directories.
  • adb shell pm list packages [options]
    Lists all installed package names on the device. This is essential for finding the correct name to use with adb uninstall.
    Example: adb shell pm list packages -f -3 | findstr "google" (on Windows) or ... | grep "google" (on Mac/Linux) will list the path and package name for all third-party apps with "google" in the name.
  • adb shell pm clear [package_name]
    Clears all data associated with an application, effectively resetting it to its initial state without uninstalling it.
    Example: adb shell pm clear com.android.chrome

File System Operations

These commands allow you to move files between your computer and the Android device.

  • adb push [local_path] [remote_path]
    Copies a file or directory from your computer to the device.
    Example: adb push C:\Users\User\Desktop\photo.jpg /sdcard/Pictures/
  • adb pull [remote_path] [local_path]
    Copies a file or directory from the device to your computer.
    Example: adb pull /sdcard/DCIM/Camera/IMG_20230101.jpg . (The period at the end denotes the current directory on the computer).
  • adb sync [directory]
    A more advanced command that synchronizes files. It copies only the files from the host to the device that are newer or do not exist on the device. This is primarily used by developers to push updated system builds.

Unlocking the Power of the Shell

The adb shell command is your gateway to the underlying Linux command-line environment on the Android device.

  • adb shell
    Opens an interactive remote shell on the device. From here, you can run standard Linux commands like ls, cd, rm, cat, etc., to navigate and manage the device's file system directly.
  • adb shell [command]
    Executes a single shell command without opening an interactive session. This is ideal for scripting.
    Example: adb shell ls /sdcard/Download
  • adb root
    Restarts the ADB daemon ('adbd') on the device with root permissions. This only works on development builds or rooted devices. If successful, subsequent adb shell sessions will have root access, allowing you to modify protected system files.

Advanced Debugging and Logging

These commands are indispensable for developers and for troubleshooting complex issues.

  • adb logcat
    Provides a real-time stream of system and application log messages. The output is extremely verbose, so filtering is essential.
    Example: adb logcat *:E will show only error-level messages.
    Example: adb logcat -s "ActivityManager" will show logs only from the "ActivityManager" tag.
  • adb bugreport [path]
    Generates a comprehensive ZIP file containing the device's state, including logcat, system dumps, and other diagnostic information. This is the standard way to report bugs to developers.
  • adb shell dumpsys [service]
    A powerful tool that dumps the status of a specific system service.
    Example: adb shell dumpsys battery provides detailed information about the battery's health, temperature, and charging status.
    Example: adb shell dumpsys activity top shows detailed information about the currently running top activity.

System and Device Control

ADB allows for direct control over the device's state and user interface.

  • adb reboot [bootloader|recovery]
    Reboots the device. Without arguments, it performs a normal reboot.
    • adb reboot bootloader: Reboots the device into its bootloader (for Fastboot).
    • adb reboot recovery: Reboots the device into its recovery environment.
  • adb shell screencap [path]
    Takes a screenshot and saves it to the specified path on the device.
    Example: adb shell screencap /sdcard/screenshot.png
  • adb shell screenrecord [path]
    Records the device's screen as an MP4 file. You can stop the recording by pressing Ctrl+C in the terminal.
    Example: adb shell screenrecord /sdcard/myvideo.mp4
  • adb shell input [source] [command]
    Simulates user input events. This is extremely useful for automation and testing.
    • adb shell input text "hello world": Types the string "hello world".
    • adb shell input keyevent 26: Simulates pressing the power button.
    • adb shell input tap 500 1400: Simulates a tap at X=500, Y=1400 coordinates.
    • adb shell input swipe 100 1500 100 500: Simulates a swipe up gesture.

Advanced Networking with ADB

ADB can create network tunnels between the host computer and the device, which is invaluable for debugging network-aware applications.

  • adb forward [local] [remote]
    Forwards socket connections. For example, you could forward a TCP port on your computer to a port on the device.
    Example: adb forward tcp:8080 tcp:9090. Now, any connection made to localhost:8080 on your computer will be forwarded to port 9090 on the Android device. This is great for debugging a local server running on the device from your computer's browser.
  • adb reverse [remote] [local]
    Does the opposite of forward. It allows an application on the device to connect to a port on the host computer.
    Example: adb reverse tcp:8000 tcp:3000. Now, if an app on the Android device tries to connect to localhost:8000, the connection will be routed to port 3000 on your computer. This is essential for an app that needs to communicate with a development server running on your PC.

Chapter 4: Navigating the Bootloader with Fastboot

While ADB manages a live Android system, Fastboot is the tool for low-level modification in the pre-boot environment. It allows you to directly write to the device's flash memory, altering its core components. This power comes with significant risk; an incorrect Fastboot command can render a device unusable (a "brick"). Therefore, a clear understanding of its functions and the device's partition structure is paramount.

What is the Bootloader?

The bootloader is the first software that runs when you power on your device. It is a vendor-specific program responsible for initializing the processor and memory and then loading the Android OS. Most manufacturers ship devices with a locked bootloader. This is a security measure to prevent unauthorized modification of the system software. Using Fastboot to its full potential requires an unlocked bootloader, a process that voids the warranty and wipes all user data.

Understanding Android Partitions: A Brief Overview

An Android device's internal storage is divided into several partitions, much like a computer's hard drive. Fastboot interacts directly with these partitions. While the exact layout varies, some common partitions include:

  • boot: Contains the kernel and ramdisk. This is the core of the OS that is loaded into memory.
  • system: Contains the main Android operating system, including system apps and libraries.
  • recovery: Contains a separate, minimal operating system used for applying updates and performing factory resets. This is the partition replaced by custom recoveries like TWRP.
  • userdata: This is where all your personal data is stored—apps, photos, settings, etc. Unlocking the bootloader erases this partition.
  • vendor: Contains device-specific files and drivers (proprietary blobs) provided by the hardware manufacturer.
  • radio: Contains the baseband/modem firmware, which controls cellular connectivity.

The Key to Freedom: Unlocking the Bootloader

This is the first and most critical step for any serious modification. The process erases all data on the device.

  1. Enable "OEM unlocking" in Developer Options on the device.
  2. Reboot the device into the bootloader using adb reboot bootloader.
  3. Once in Fastboot mode, run the unlock command. The command has evolved over time:
    • Modern devices (Android 8+): fastboot flashing unlock
    • Older devices: fastboot oem unlock
  4. The device will display a confirmation screen. You must use the volume keys to select "Yes" and the power key to confirm.
  5. The device will then wipe itself and reboot with an unlocked bootloader. You will typically see a warning message on every boot indicating the bootloader is unlocked.

To re-lock the bootloader, you can use fastboot flashing lock. Warning: Only re-lock your bootloader if the device is running 100% stock, unmodified factory software. Locking it with a modified system can result in a hard brick.

Core Fastboot Commands

  • fastboot devices
    Similar to adb devices, this command lists all devices currently connected in Fastboot mode. If nothing is shown, check your drivers and cable.
  • fastboot reboot
    Reboots the device back into the main Android operating system.
  • fastboot reboot-bootloader
    Reboots the device back into the bootloader. Useful if you need to re-run a command.
  • fastboot flash [partition_name] [filename.img]
    This is the most powerful and dangerous Fastboot command. It writes an image file from your computer directly to the specified partition on the device.
    Example: fastboot flash recovery twrp-3.7.0.img flashes the TWRP recovery image to the recovery partition.
    Example: fastboot flash boot boot.img flashes a new kernel/boot image.
    Extreme caution is advised. Flashing an image meant for a different device model or to the wrong partition will almost certainly brick the device.
  • fastboot boot [filename.img]
    A much safer alternative to flashing. This command temporarily boots the device using the provided image file without permanently writing it to a partition. This is excellent for testing a new custom recovery or kernel. If it fails to work, a simple reboot will return the device to its previous state.
    Example: fastboot boot twrp-3.7.0.img
  • fastboot getvar [variable]
    Retrieves information from the bootloader.
    Example: fastboot getvar product will return the device's product name.
    Example: fastboot getvar all will dump all available variables, which can provide a wealth of information about the device's hardware, security state, and partition layout.

Advanced Fastboot and A/B Partitions

Modern Android devices use a partition scheme called A/B (Seamless) Updates. This means there are two copies of most system partitions (e.g., system_a, system_b, boot_a, boot_b). When you receive an over-the-air (OTA) update, it is installed to the inactive slot in the background. The next time you reboot, the device switches to the updated slot. This makes updates safer and faster. This scheme introduces new Fastboot commands:

  • fastboot getvar current-slot
    Tells you which slot (a or b) is currently active.
  • fastboot --set-active=[slot] or fastboot set_active [slot]
    Manually switches the active slot. For example, fastboot --set-active=b will make the 'b' slot active on the next boot. This is an advanced operation and should be used with caution.
  • When flashing on an A/B device, you often don't need to specify the slot. For example, running fastboot flash boot boot.img will automatically flash to the *inactive* slot. You then use fastboot set_active to switch to that slot. Some factory image flashing scripts handle this logic for you. Always follow the specific instructions for your device.

Chapter 5: Advanced Workflows and Practical Scenarios

Understanding individual commands is one thing; combining them into effective workflows is another. This chapter illustrates how ADB and Fastboot work together to accomplish common power-user tasks, moving from the theoretical to the practical.

Workflow 1: Installing a Custom Recovery (e.g., TWRP)

A custom recovery like TWRP (Team Win Recovery Project) replaces the stock recovery and unlocks powerful capabilities like creating full system backups (Nandroid backups), flashing custom ROMs, and rooting the device. This is often the first major modification users perform.

  1. Preparation: Download the correct TWRP .img file for your specific device model. An incorrect version can cause issues. Also, ensure you have backed up all important data, as the first step will wipe your device.
  2. Unlock the Bootloader: Follow the steps in Chapter 4.
    • Enable "OEM Unlocking" in Developer Options.
    • Connect the device and run: adb reboot bootloader
    • Run: fastboot flashing unlock
    • Confirm the unlock on the device screen. The device will be wiped and will reboot. You will need to go through the initial Android setup again and re-enable USB Debugging.
  3. Flash the Custom Recovery:
    • Once the device is set up again, reboot it back into the bootloader: adb reboot bootloader
    • Flash the TWRP image file to the recovery partition. Make sure your terminal is in the same directory as the downloaded .img file, or provide the full path.
      fastboot flash recovery twrp-device-name.img
  4. Boot into the New Recovery: This step is critical. Do not reboot into the system directly. The stock OS can sometimes overwrite the custom recovery on the first boot.
    • Use the volume keys on the device to navigate to "Recovery Mode" in the bootloader menu and press the power button to select it. Alternatively, you can use the command: fastboot reboot recovery
    • The device will now boot into your newly installed TWRP recovery. You have successfully completed the workflow.

Workflow 2: Sideloading an OTA Update Package

Sometimes you want to install an official Over-The-Air (OTA) update manually without waiting for it to be pushed to your device. This can be done using ADB's sideload feature in the stock recovery.

  1. Preparation: Download the official OTA update .zip file for your device from a trusted source (usually the manufacturer's website or reputable forums).
  2. Boot into Recovery:
    • Connect your device to your computer.
    • Run the command: adb reboot recovery
  3. Enter Sideload Mode:
    • In the stock recovery menu, you'll see a screen with an Android logo. Use the volume keys to highlight the option "Apply update from ADB" and press the power key to select it.
    • The device will now be in ADB sideload mode, waiting for a file.
  4. Sideload the Package:
    • On your computer, open a terminal in the directory where you saved the OTA .zip file.
    • Run the sideload command:
      adb sideload ota-update-filename.zip
    • The terminal will show the progress of the file transfer. Once the transfer is complete, the device will automatically start verifying and installing the update. Do not unplug the device during this process.
  5. Reboot: Once the installation is complete, the recovery menu will reappear. Select the "Reboot system now" option. Your device will restart with the new update installed.

Workflow 3: Advanced Application Backup (with Caveats)

While Google provides cloud backups, the built-in adb backup command allows for a local, more comprehensive backup of applications and their data. Important Note: This feature is now considered deprecated and can be unreliable. Many modern apps explicitly disallow backup, and the restore process can be finicky. This workflow is provided for educational purposes, but for critical data, other solutions should be considered.

  1. Initiate the Backup:
    • Run the backup command from your computer. You can use several flags to customize what is backed up.
      adb backup -apk -shared -all -f C:\Backup\myandroid.ab
      • -apk: Includes the APK files themselves in the backup.
      • -shared: Includes the contents of the device's shared storage (SD card).
      • -all: Includes all installed applications (except those that disallow backup).
      • -f [path]: Specifies the location and filename for the backup file (.ab extension).
  2. Confirm on Device:
    • After running the command, a full-screen prompt will appear on your device.
    • You will be asked to enter an optional password to encrypt the backup. If you set a password, you MUST remember it, as there is no way to recover it.
    • Tap "Back up my data" to begin the process.
  3. Restoring the Backup:
    • To restore, use the adb restore command, pointing to your backup file.
      adb restore C:\Backup\myandroid.ab
    • A similar prompt will appear on your device. If you set a password, you will need to enter it now. Tap "Restore my data" to proceed.

Chapter 6: Comprehensive Troubleshooting Guide

Despite their power, ADB and Fastboot can be prone to issues, especially during initial setup. This chapter addresses the most common problems and provides clear, actionable solutions to get you back on track.

Error: 'adb' or 'fastboot' is not recognized as an internal or external command

  • Cause: This is the most common beginner error. It means your operating system's terminal cannot find the adb.exe or fastboot.exe executables. The folder containing these files is not in your system's PATH environment variable.
  • Solution:
    1. Verify the Path: Double-check the path you added to your environment variables in Chapter 2. Ensure there are no typos and that it points directly to the `platform-tools` folder itself, not a folder containing it.
    2. Restart Terminal: On all operating systems, changes to the PATH variable are not applied to currently open terminal/command prompt windows. You must close them and open a new session.
    3. Temporary Fix: As a temporary workaround, you can open a terminal directly inside the `platform-tools` folder. On Windows, you can Shift+Right-click in the folder and select "Open PowerShell window here". From there, you will need to prefix commands with .\ (e.g., .\adb devices). This confirms the tools work and that the problem is solely with the PATH.

Error: 'device not found' or 'waiting for device'

  • Cause: This message indicates that the ADB server or Fastboot tool is running, but it cannot see your device. This is almost always a physical connection or driver issue.
  • Solution:
    1. Check USB Debugging: For ADB, ensure "USB debugging" is enabled in Developer Options. For Fastboot, ensure the device is actually in Fastboot mode.
    2. Physical Connection: This is a surprisingly common culprit.
      • Try a different USB cable. Many cheap cables are for charging only and lack the necessary data wires. Use the cable that came with your device.
      • Try a different USB port on your computer, preferably a port directly on the motherboard (at the back of a desktop PC) rather than a front-panel port or a USB hub.
      • Ensure the port on your phone is clean and free of debris.
    3. Drivers (Windows): This is the most likely cause on Windows. Open Device Manager. If you see your device with a yellow exclamation mark, the driver is missing or incorrect. See the dedicated section below.

Error: Device Unauthorized

  • Cause: When you connect a device to a new computer for the first time, a security prompt must be accepted on the device to authorize that computer for debugging. If adb devices shows your device as "unauthorized", it means this prompt was either missed, dismissed, or a problem prevented it from appearing.
  • Solution:
    1. Look for the Prompt: Unlock your device's screen. The authorization prompt should be visible. Check "Always allow from this computer" and tap "Allow".
    2. Revoke Authorizations: If the prompt doesn't appear, go to Developer Options on your device and find the "Revoke USB debugging authorizations" option. Tap it. This will clear all previously trusted computers.
    3. Restart ADB Server: Unplug the USB cable. On your computer, run adb kill-server. Then, plug the device back in. This fresh start should trigger the authorization prompt again.
    4. Check .android folder: The authorization keys are stored in a folder named .android in your user's home directory (e.g., C:\Users\YourName\.android). Deleting the adbkey and adbkey.pub files in this folder and restarting the server can sometimes resolve stubborn issues.

Dealing with Windows Driver Issues

  • Symptom: In Device Manager, your device appears under "Other devices" with a yellow icon, or it's listed as "ADB Interface" but still doesn't work.
  • Solution:
    1. Install OEM Driver: The best first step is always to install the official driver from your device's manufacturer.
    2. Manual Driver Installation: If that fails, you can manually point Windows to the driver.
      • Download the Google USB Driver package.
      • In Device Manager, right-click the problematic device and select "Update driver".
      • Choose "Browse my computer for drivers".
      • Select "Let me pick from a list of available drivers on my computer".
      • Select "Show All Devices".
      • Click "Have Disk..." and browse to the folder where you extracted the Google USB Driver. Select the android_winusb.inf file.
      • From the list of models, select "Android Composite ADB Interface" and proceed with the installation, ignoring any warnings.
    3. Fastboot Drivers: Be aware that a device can have a working ADB driver but still not be recognized in Fastboot mode. Fastboot sometimes requires a separate driver installation. The manual installation process above is the same for pointing a device in Fastboot mode to the correct driver.

Fixing Linux Permission Errors with 'udev'

  • Symptom: adb devices shows your device serial number as "????????????" and "no permissions".
  • Cause: Your user account does not have the necessary permissions to access the USB device file.
  • Solution: You must create a `udev` rule as detailed in Chapter 2, Section 3.
    1. Create the file: sudo nano /etc/udev/rules.d/51-android.rules
    2. Add the rule: SUBSYSTEM=="usb", ATTR{idVendor}=="18d1", ATTR{idProduct}=="*", MODE="0666", GROUP="plugdev"
    3. Reload rules: sudo udevadm control --reload-rules && sudo udevadm trigger
    4. Restart the ADB server: adb kill-server and reconnect the device.

Understanding Fastboot 'FAILED (remote: ...)' Errors

  • Cause: This generic error means the command was sent successfully, but the bootloader on the device rejected it. The message in the parenthesis is the key to the problem.
  • Common Remote Messages and Solutions:
    • (remote: 'flashing lock is not allowed in Lock State'): You are trying to lock the bootloader, but the device is not in a lockable state (e.g., it's running custom software).
    • (remote: 'unlock operation is not allowed') or (remote: 'oem unlock is not allowed'): You have not enabled "OEM unlocking" in Developer Options.
    • (remote: 'partition write failed'): The bootloader failed to write to the specified partition. This could be due to a corrupt image file or a hardware issue.
    • (remote: 'size too large'): The image file you are trying to flash is larger than the target partition. You have the wrong file for your device.
    • (remote: 'security check fail') or (remote: 'image corrupt or not signed'): The image you are trying to flash failed a security verification. This is common when trying to flash an unofficial or incompatible file on a locked bootloader.