Android 判断当前联网的类型 wifi、移动数据流量

时间:2024-03-05 16:29:15

先获取系统管理网络连接的Manager:

ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

再获取当前已经激活的连接:(当期为null时代表当前无连接)

NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();

其中常量ConnectivityManager.TYPE_MOBILE标识着是移动数据流量,

而ConnectivityManager.TYPE_WIFI标志着是wifi。

package com.example.NetworkChangeReceiver2;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MyActivity extends Activity {

    ConnectivityManager connectivityManager;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    }

    public void isWifi(View view) {
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetworkInfo == null) {
            Toast.makeText(this, "没有联网!", 1).show();
            return;
        }
        if(activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            Toast.makeText(this, "连接的网络是wifi!", 1).show();
        } else {
            Toast.makeText(this, "不是wifi!", 1).show();
        }
    }

    public void isMobile(View view) {
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetworkInfo == null) {
            Toast.makeText(this, "没有联网!", 1).show();
            return;
        }
        if(activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
            Toast.makeText(this, "连接的网络是移动数据流量!", 1).show();
        } else {
            Toast.makeText(this, "不是移动数据流量!", 1).show();
        }
    }
}