Android
 Computer >> コンピューター >  >> プログラミング >> Android

【Android】エミュレータのIPアドレスを取得して表示する方法を解説

はじめに

この記事では、Androidアプリから端末(エミュレータ/実機)のIPアドレスを取得し、画面に表示する方法を、実際のサンプルコードとともにステップ形式で解説します。Wi-Fi接続情報を利用したシンプルな実装例なので、Android開発初心者の方にもわかりやすい内容となっています。

手順1:新規プロジェクトの作成

まず、Android Studioで新しいプロジェクトを作成します。メニューから「File」→「New Project」を選択し、必要な項目を入力してプロジェクトを作成してください。

手順2:レイアウトファイル(activity_main.xml)の編集

res/layout/activity_main.xml に以下のコードを追加します。中央にIPアドレスを表示する TextView を配置し、その下に取得用の Button を置いたシンプルな構成です。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <TextView
        android:textSize="16sp"
        android:textStyle="bold"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView"
        android:layout_centerInParent="true"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btnGetIPAddress"
        android:text="Get IP Address"
        android:layout_below="@id/textView"
        android:layout_marginTop="10dp"
        android:layout_centerInParent="true"/>
</RelativeLayout>

手順3:MainActivity.java の実装

次に、src/MainActivity.java に以下のコードを記述します。ボタンがタップされると WifiManager から接続情報を取得し、Formatter.formatIpAddress() で文字列に変換したうえで TextView に表示する仕組みです。

import androidx.appcompat.app.AppCompatActivity;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.text.format.Formatter;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
    Button button;
    TextView textview;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textview = findViewById(R.id.textView);
        button = findViewById(R.id.btnGetIPAddress);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                GetIPAddress();
            }
        });
    }
    private void GetIPAddress() {
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE); assert wifiManager != null;
        String ip = Formatter.formatIpAddress(wifiManager.getConnectionInfo().getIpAddress());
        textview.setText(String.format("IP Address: %s", ip));
    }
}

補足:Formatter.formatIpAddress() は現在では非推奨(deprecated)のAPIです。IPv6対応などより堅牢な実装が必要な場合は、java.net.NetworkInterface や ConnectivityManager の NetworkCapabilities を使った方法への移行を検討しましょう。

手順4:AndroidManifest.xml への権限追加

最後に、androidManifest.xml に以下のパーミッションを追加します。Wi-Fiの状態を取得するために ACCESS_WIFI_STATE、ネットワーク通信のために INTERNET 権限が必要です。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.com.sample">
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

アプリを実行して動作を確認しよう

それでは、アプリを実行してみましょう。Android Studioでプロジェクト内のアクティビティファイルを開き、ツールバーの「Run」アイコンをクリックします。デプロイ先としてエミュレータまたは接続済みのAndroid端末を選択すると、アプリが起動して初期画面が表示されます。

画面上の「Get IP Address」ボタンをタップすると、TextView に現在のIPアドレスが表示されます。

【Android】エミュレータのIPアドレスを取得して表示する方法を解説

ワンポイント:Androidエミュレータには通常「10.0.2.15」という固定の内部IPアドレスが割り当てられます。また、エミュレータからホストPCへアクセスする場合は「10.0.2.2」を使用します。これらはエミュレータ特有のアドレスなので、ローカルサーバーとの通信テスト時に覚えておくと便利です。

  1. Androidで2つの地理的な地点間の距離を取得する方法

    この記事では、Androidアプリで2つの地理的な地点(緯度・経度)の間の距離を取得し、画面に表示する方法を解説します。Androidフレームワークが提供するLocationクラスのdistanceTo()メソッドを使うと、2地点間の距離を簡単に計算できます。 ステップ1:新しいプロジェクトを作成する Android Studioを起動し、メニューから「File」→「New Project」を選択します。必要な項目をすべて入力して、新しいプロジェクトを作成してください。 ステップ2:activity_main.xmlにコードを追加する res/layout/activity_main.xmlに

  2. Android端末のメインメールアドレスを取得する方法をサンプルコード付きで解説

    本記事では、Android端末に登録されているメインのメールアドレスを取得する方法を、実際のサンプルコードとともにわかりやすく解説します。AccountManagerとGET_ACCOUNTS権限を活用することで、端末に設定されたアカウント情報からメールアドレスを取得できます。 手順1:Android Studioで新規プロジェクトを作成する Android Studioを起動し、「File」→「New Project」を選択して、必要な項目を入力して新しいプロジェクトを作成します。 手順2:res/layout/activity_main.xml にコードを追加する 以下のコードをレイアウト