Android判断网线是否插入的方法

1.通过命令:
cat /sys/class/net/eth0/carrier

2.读取carrier文件信息

public boolean isNetworkConnected() {
    File file = new File("/sys/class/net/eth0/carrier");
    int status = 0;
    try {
        FileInputStream fileInputStream = new FileInputStream(file);
        InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

        String text = bufferedReader.readLine();
        status = Integer.parseInt(text);
        bufferedReader.close();
        inputStreamReader.close();
        fileInputStream.close();
        return status == 1;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return false;
}

3.通过ConnectivityManager:
需要添加权限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

public boolean isNetworkConnected() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    if (cm != null) {
        NetworkInfo info = cm.getActiveNetworkInfo();
        return info != null && info.isConnected();
    }
    return false;
}

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×