Android 获取手机IP

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/yuyehui/article/details/89255634

1.概述

作为一个C语言开发的代码搬运工,想写个Android程序相当不容易。花了两天时间,翻了n篇帖子,感觉每个帖子都不完整,比如各个函数之前参数如何传递,如何把结果显示出来,这些都不完整。于是写这篇博客,希望对Android初学者有点用处。开发环境为Android Studio,版本为Android Studio 3.4 Canary 2,关于Android Studio安装和SDK配置,这里不赘述。

2.实现

2.1 .xml文件

新建工程IPGET,修改/res/layout/activity_main.xml文件,在里面增加l两个TextView文本,完整的activity_main.xml文件和截图如下,

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/nametextview"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginBottom="200dp"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <TextView
        android:id="@+id/ipTextView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginBottom="100dp"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent" />
</android.support.constraint.ConstraintLayout>

.xml

2.2 .java文件

修改/java/com.example.ipget/Mainactivity.java文件,完整的Mainactivity.java文件和截图如下

package com.example.ipget;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.net.ConnectivityManager;
import android.support.v7.app.AlertDialog;
import android.content.DialogInterface;
import android.net.NetworkInfo;
import java.net.NetworkInterface;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.util.Enumeration;
import java.net.SocketException;

public class MainActivity extends AppCompatActivity {
    private TextView ipTextView = null;
    private TextView nameTextView = null;
    private ConnectivityManager mConnectivityManager = null;
    private NetworkInfo mActiveNetInfo = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        nameTextView = findViewById(R.id.nametextview);
        ipTextView = findViewById(R.id.ipTextView);
        mConnectivityManager = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);//获取系统的连接服务
        mActiveNetInfo = mConnectivityManager.getActiveNetworkInfo();//获取网络连接的信息
        if(mActiveNetInfo==null)
            myDialog();
        else
            setUpInfo();
    }

    public String getIPAddress() {
        NetworkInfo info = mConnectivityManager.getActiveNetworkInfo();
        if (info != null && info.isConnected()) {
            if ((info.getType() == ConnectivityManager.TYPE_MOBILE) || (info.getType() == ConnectivityManager.TYPE_WIFI) ){//当前使用2G/3G/4G网络
                try {
                    for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                        NetworkInterface intf = en.nextElement();
                        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                            InetAddress inetAddress = enumIpAddr.nextElement();
                            if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                                return inetAddress.getHostAddress();
                            }
                        }
                    }
                }
                catch (SocketException e) {
                    e.printStackTrace();
                }
            }
        }
        else { //当前无网络连接,请在设置中打开网络
            return null;
        }
        return null;
    }

    public void setUpInfo()  {
        if(mActiveNetInfo.getType()==ConnectivityManager.TYPE_WIFI)  {
            nameTextView.setText("网络类型:WIFI");
            ipTextView.setText("IP地址:"+getIPAddress());
        }
        else if(mActiveNetInfo.getType()==ConnectivityManager.TYPE_MOBILE)  {
            nameTextView.setText("网络类型:3G/4G");
            ipTextView.setText("IP地址:"+getIPAddress());
        }
        else  {
            nameTextView.setText("网络类型:未知");
            ipTextView.setText("IP地址:");
        }
    }

    private void myDialog()  {
        AlertDialog mDialog = new AlertDialog.Builder(MainActivity.this)
                .setTitle("注意")
                .setMessage("当前网络不可用,请检查网络!")
                .setPositiveButton("确定", new DialogInterface.OnClickListener()  {
                    @Override
                    public void onClick(DialogInterface dialog, int which)  {
                        dialog.dismiss();
                        MainActivity.this.finish();
                    }
                })
                .create();//创建这个对话框
        mDialog.show();//显示这个对话框
    }
}

.java

2.3 AndroidManifest.xml文件

修改AndroidManifest.xml文件,在里面添加如下2个权限

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

完整的AndroidManifest.xm文件和截图如下

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.ipget">

    <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>

    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
</manifest>

AndroidManifest.xml

3.测试结果

4G网络、wifi网络、无网络三种情况测试如下图:
测试

4.参考

https://www.cnblogs.com/tianyaxue/p/3168619.html
https://blog.csdn.net/u013986975/article/details/71709866

展开阅读全文

没有更多推荐了,返回首页