获取android设备的IP地址

时间:2024-03-08 19:57:43

直接贴代码,功能介绍代码里注释:

package com.hui.wang;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Collections;
import java.net.SocketException;
import org.apache.http.conn.util.InetAddressUtils;
import android.widget.TextView;

/**
 *
 * @author hui.wang
 *
 */
public class FindAdressActivity extends Activity {
 private TextView ipTextView = null;
 private TextView nameTextView = null;
 // 定义一个ConnectivityManager对象
 private ConnectivityManager mConnectivityManager = null;
 // 定义一个NetworkInfo对象
 private NetworkInfo mActiveNetInfo = null;

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  nameTextView = (TextView) findViewById(R.id.text_name);
  ipTextView = (TextView) findViewById(R.id.text_ip);
  // 实例化mConnectivityManager对象
  mConnectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);// 获取系统的连接服务
  // 实例化mActiveNetInfo对象
  mActiveNetInfo = mConnectivityManager.getActiveNetworkInfo();// 获取网络连接的信息
  if (mActiveNetInfo == null)
   myDialog();
  else
   setUpInfo();

 }

 // 获取本地IP函数
 public String getLocalIpAddress() {
  try {
   String ipv4;

   ArrayList<NetworkInterface> mylist = Collections
     .list(NetworkInterface.getNetworkInterfaces());

   for (NetworkInterface ni : mylist) {

    ArrayList<InetAddress> ialist = Collections.list(ni
      .getInetAddresses());
    for (InetAddress address : ialist) {
     if (!address.isLoopbackAddress()
       && InetAddressUtils.isIPv4Address(ipv4 = address
         .getHostAddress())) {
      return ipv4;
     }
    }

   }

  } catch (SocketException ex) {

  }
  return null;
 }

 // 显示IP信息
 public void setUpInfo() {
  // 如果是WIFI网络
  if (mActiveNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
   nameTextView.setText("网络类型:WIFI");

   ipTextView.setText("IP地址:" + getLocalIpAddress());
  }
  // 如果是手机网络
  else if (mActiveNetInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
   nameTextView.setText("网络类型:手机");
   ipTextView.setText("IP地址:" + getLocalIpAddress());
  } else {
   nameTextView.setText("网络类型:未知");
   ipTextView.setText("IP地址:");
  }

 }

 // 显示对话框
 private void myDialog() {
  AlertDialog mDialog = new AlertDialog.Builder(FindAdressActivity.this)
    .setTitle("注意").setMessage("当前网络不可用,请检查网络!")
    .setPositiveButton("确定", new DialogInterface.OnClickListener() {

     @Override
     public void onClick(DialogInterface dialog, int which) {
      // TODO Auto-generated method stub
      // 关闭对话框
      dialog.dismiss();
      // 结束Activity
      FindAdressActivity.this.finish();
     }
    }).create();// 创建这个对话框
  mDialog.show();// 显示这个对话框
 }

  // 获取本地IP函数
 public String getLocalIpAddress()方法里面判断IPV4和IPV6如果IPV4不为空返回IPV4。

因为如果不加判断默认返回时IPV6的地址,也就是一串字符串。那是IPV6的IP表示方式。

}

main.XML文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/text_name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
 <TextView
        android:id="@+id/text_ip"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="" />
    

</LinearLayout>

AndroidManifest.xml添加权限

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.hui.wang"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="12" />

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".FindAdressActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>