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

KotlinでAndroidデバイスのIPアドレスをプログラム的に取得する方法

はじめに

この記事では、Kotlinを使用してAndroidデバイスのIPアドレスをプログラムで取得する方法を解説します。Wi-Fi接続中のデバイスのローカルIPアドレスを取得し、画面に表示するまでの一連の手順をステップごとに紹介します。

手順1:新しいプロジェクトを作成する

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

手順2:レイアウトファイルを編集する

res/layout/activity_main.xmlに以下のコードを追加します。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:layout_margin="16dp"
   android:orientation="vertical">
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="50dp"
      android:text="Tutorials Point"
      android:textAlignment="center"
      android:textColor="@android:color/holo_green_dark"
      android:textSize="32sp"
      android:textStyle="bold" />
   <TextView
      android:id="@+id/getIPAddress"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:textAlignment="center"
      android:textColor="@android:color/background_dark"
      android:text="IP address of your Device"
      android:textSize="24sp"
      android:textStyle="bold" />
</RelativeLayout>

このレイアウトでは、画面中央にIPアドレスを表示するためのTextView(ID: getIPAddress)を配置しています。

手順3:MainActivity.ktを編集する

src/MainActivity.ktに以下のコードを追加します。

import android.content.Context
import android.net.wifi.WifiManager
import android.os.Bundle
import android.text.format.Formatter
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
      val textView: TextView = findViewById(R.id.getIPAddress)
      val wifiManager = applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
      val ipAddress: String = Formatter.formatIpAddress(wifiManager.connectionInfo.ipAddress)
      textView.text = "Your Device IP Address: $ipAddress"
   }
}

このコードのポイントは以下の通りです。
・applicationContextからWIFI_SERVICEを取得し、WifiManagerのインスタンスを作成します。
・wifiManager.connectionInfo.ipAddressでint型のIPアドレスを取得します。
・Formatter.formatIpAddress()メソッドで、人間が読める形式(例:192.168.0.5)の文字列に変換し、TextViewに表示します。

なお、Formatter.formatIpAddress()は現在非推奨(Deprecated)となっているため、最新のAndroidバージョンをターゲットとする場合は、NetworkInterfaceクラスやConnectivityManagerを使用した実装への移行が推奨されます。

手順4:マニフェストファイルを編集する

androidManifest.xmlに以下のコードを追加します。Wi-Fiの状態情報にアクセスするため、ACCESS_WIFI_STATEパーミッションの宣言が必要です。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.example.q11">
   <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
   <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端末がコンピュータに接続されていることを前提としています。Android Studioからアプリを実行するには、プロジェクト内のいずれかのアクティビティファイルを開き、ツールバーの実行アイコンKotlinでAndroidデバイスのIPアドレスをプログラム的に取得する方法をクリックします。表示される選択肢から自分のモバイルデバイスを選択すると、端末上でアプリが起動し、デバイスのIPアドレスが表示された画面を確認できます。

KotlinでAndroidデバイスのIPアドレスをプログラム的に取得する方法

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

    はじめにこの記事では、Androidアプリから端末(エミュレータ/実機)のIPアドレスを取得し、画面に表示する方法を、実際のサンプルコードとともにステップ形式で解説します。Wi-Fi接続情報を利用したシンプルな実装例なので、Android開発初心者の方にもわかりやすい内容となっています。手順1:新規プロジェクトの作成まず、Android Studioで新しいプロジェクトを作成します。メニューから「File」→「New Project」を選択し、必要な項目を入力してプロジェクトを作成してください。手順2:レイアウトファイル(activity_main.xml)の編集res/layout/acti

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

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