以太网开关_切换静态以及获取IP地址

代码下载地址:https://pan.baidu.com/s/15-LLGdTA46jgDyqQcx6SUA

 上次写过一遍这一篇的,复制粘贴时studio,有背景色,好烦,弄不干净,就重新写 ,布局文件就不用提交了,需要源码的同伴,可以自己去下载。下载地址如上:

     这篇文章主要解决的问题,

     1:开机自启,每30秒去检测当前的网络状态 ,因为我的需求是以太网,所有其他的网络不在我的工作范围内。

      2:如果当前没有网络的话,去检测有没有插入以太网

     3:如果插入以太网,判断以太网有没有打开

     4:如果以太网打开的话 ,去获取上次的连接记录,是静态还是动态。然后恢复到上次的状态

     5:大家看代码可能会有一位 ,为啥切换状态需要切两次,因为我们的系统有个bug, 以太网需要切两次,这个可以根据自己的

        需求来调整。

====软件编译需要在服务器中编译,所以没办法直接运行====,请须知=================================

  不想下载源码的就直接看代码吧 ,目前测试人员没有测试出bug,所以代码可以直接放心使用

先看清单文件,就不一一解释代码了

  

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ys.demo"
    android:sharedUserId="android.uid.system">

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_SETTINGS" />
    <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
    <uses-permission android:name="android.permission.CONNECTIVITY_INTERNAL" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.BROADCAST_STICKY" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <application
        android:name="com.ys.EthNetApplication"
        android:allowBackup="true"
        android:icon="@mipmap/app_eth"
        android:label="@string/app_name"
        android:supportsRtl="true">
        <activity android:name="com.ys.setstaticip.StartActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

        <activity android:name="com.ys.setstaticip.MainActivity" />

        <service
            android:name="com.ys.service.EthListenServer"
            android:enabled="true"
            android:permission="true"/>

        <receiver
            android:name="com.ys.receiver.AppReceiver"
            android:enabled="true"
            android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.NET.conn.CONNECTIVITY_CHANGE" />
                <action android:name="android.Net.wifi.WIFI_STATE_CHANGED" />
                <action android:name="android.net.wifi.STATE_CHANGE" />
                <action android:name="android.net.ethernet.ETHERNET_STATE_CHANGED" />
                <action android:name="android.net.ethernet.STATE_CHANGE" />
                <action android:name="android.rkbord.luncher.start" />
                <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
                <action android:name="android.hardware.usb.action.USB_DEVICE_DETACHED" />
                <category android:name="android.intent.category.HOME" />
            </intent-filter>
        </receiver>

    </application>

</manifest>

一个实体类,用来封装网络信息

      

package com.ys.entity;

public class EthNetEntity {

    /***
     * true ==动态
     * false==静态
     */
    boolean isEthNetState;
    String staticIpAddress;

    public EthNetEntity() {
    }

    public EthNetEntity(boolean isEthNetState, String staticIpAddress) {
        this.isEthNetState = isEthNetState;
        this.staticIpAddress = staticIpAddress;
    }

    public boolean isEthNetState() {
        return isEthNetState;
    }

    public void setEthNetState(boolean ethNetState) {
        isEthNetState = ethNetState;
    }

    public String getStaticIpAddress() {
        return staticIpAddress;
    }

    public void setStaticIpAddress(String staticIpAddress) {
        this.staticIpAddress = staticIpAddress;
    }

    @Override
    public String toString() {
        return "EthNetEntity{" +
                "isEthNetState=" + isEthNetState +
                ", staticIpAddress='" + staticIpAddress + '\'' +
                '}';
    }
}

下面的这个类是项目的核心类,以太网的所有操作都在这里面了,

   

package com.ys.ethernetwatchdog;

import android.content.Context;
import android.net.EthernetManager;
import android.net.IpConfiguration;
import android.net.IpConfiguration.IpAssignment;
import android.net.IpConfiguration.ProxySettings;
import android.net.LinkAddress;
import android.net.NetworkUtils;
import android.net.StaticIpConfiguration;
import android.os.SystemProperties;
import android.util.Log;

import com.ys.config.AppConfig;
import com.ys.entity.EthNetEntity;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.util.regex.Pattern;

public class EthernetControl {

    private static final String TAG = "EthernetControl";
    public final static String nullIpInfo = "0.0.0.0";
    Context context;
    IpConfiguration mIpConfiguration;
    EthernetManager mEthManager;
    StaticIpConfiguration mStaticIpConfiguration;

    public EthernetControl(Context context) {
        this.context = context;
        mEthManager = (EthernetManager) context.getSystemService("ethernet");
    }

    /**
     * 以太网开关是否打开或关闭
     *
     * @return true 打开 false 关闭
     */
    public boolean isEnable() {
        int isEnable = mEthManager.getEthernetIfaceState();
        return isEnable == EthernetManager.ETHER_IFACE_STATE_UP;
    }

    /**
     * 以太网模式:是否位动态模式
     *
     * @return true 动态模式 false 静态模式
     */
    public boolean isDHCP() {
        return (mEthManager.getConfiguration().ipAssignment == IpAssignment.DHCP) ? true : false;
    }

    /**
     * 使能以太网
     *
     * @param enable true 打开 false 关闭
     */
    public void setEthernetEnabled(boolean enable) {
        mEthManager.setEthernetEnabled(enable);
    }


    /**
     * 设置动态模式
     */
    public void setDHCP() {
        mEthManager.setConfiguration(new IpConfiguration(IpAssignment.DHCP, ProxySettings.NONE, null, null));
    }

    /**
     * 设置静态模式
     */
    public void setStaticIp(String staticIp) {
        if (setStaticIpConfiguration(staticIp)) {
            mEthManager.setConfiguration(mIpConfiguration);
        } else {
            Log.e(TAG, mIpConfiguration.toString());
        }
    }

    /***
     * 获取IPCOnfig保存的相关信息
     */
    public EthNetEntity getEthStateFromIpConfig() {
        EthNetEntity ethNetEntity = new EthNetEntity();
        try{
            IpConfiguration ipConfiguration = mEthManager.getConfiguration();
            Log.e("cdl", "===0000ipConfiguration=="+ipConfiguration.toString());
            if (ipConfiguration == null) {
                Log.e("cdl", "===000000ipConfiguration==null" );
                return null;
            }
            String ipModel = ipConfiguration.getIpAssignment().toString();  //get_model:static or DHCP
            Log.e("cdl", "===11111-ipModel==="+ipModel);
            if(ipModel.contains("STATIC")){
                StaticIpConfiguration statusIpConfiguration = ipConfiguration.getStaticIpConfiguration();
                Log.e("cdl", "===2222-Configuration=="+statusIpConfiguration.toString());
                if (statusIpConfiguration == null) {   Log.e("cdl", "===22222statusIpConfiguration==null" );
                    return null;
                }
              LinkAddress linkAddress = statusIpConfiguration.getLinkIpAddress();
              if (linkAddress == null) {
                  Log.e("cdl", "===linkAddress==null==");
                    return null;
               }
              String  ipaddress = linkAddress.staticIpAdress();
                Log.e("cdl", "====finale ipaddress=== : " + ipaddress);
                ethNetEntity.setEthNetState(false);
                ethNetEntity.setStaticIpAddress(ipaddress);
            }else if (ipModel.contains("DHCP")){
                ethNetEntity.setEthNetState(true);
                ethNetEntity.setStaticIpAddress("");
            }
        }catch (Exception e){
            ethNetEntity.setEthNetState(true);
            ethNetEntity.setStaticIpAddress("");
        }
        return ethNetEntity;
    }

    private boolean setStaticIpConfiguration(String staticIP) {
        mStaticIpConfiguration = mEthManager.getConfiguration().getStaticIpConfiguration();
        if (mStaticIpConfiguration == null || mStaticIpConfiguration.ipAddress == null) {
            mStaticIpConfiguration = new StaticIpConfiguration();
            Inet4Address inetAddr = getIPv4Address(staticIP);
            int prefixLength = maskStr2InetMask("255.255.255.0");
            InetAddress gatewayAddr = getIPv4Address("192.168.1.1");
            InetAddress dnsAddr = getIPv4Address("8.8.8.8");
            if (inetAddr.getAddress().toString().isEmpty() || prefixLength == 0 || gatewayAddr.toString().isEmpty()
                    || dnsAddr.toString().isEmpty()) {
                Log.d(TAG, "ip,mask or dnsAddr is wrong");
                return false;
            }
            String dnsStr2 = "8.8.4.4";
            mStaticIpConfiguration.ipAddress = new LinkAddress(inetAddr, prefixLength);
            mStaticIpConfiguration.gateway = gatewayAddr;
            mStaticIpConfiguration.dnsServers.add(dnsAddr);
            if (!dnsStr2.isEmpty()) {
                mStaticIpConfiguration.dnsServers.add(getIPv4Address(dnsStr2));
            }
        }
        mIpConfiguration = new IpConfiguration(IpAssignment.STATIC, ProxySettings.NONE, mStaticIpConfiguration, null);
        return true;
    }

    private Inet4Address getIPv4Address(String text) {
        try {
            return (Inet4Address) NetworkUtils.numericToInetAddress(text);
        } catch (IllegalArgumentException | ClassCastException e) {
            return null;
        }
    }

    public String getIPAddress() {
        String tempIpInfo;
        String iface = "eth0";
        tempIpInfo = SystemProperties.get("dhcp." + iface + ".ipaddress");
        if ((tempIpInfo != null) && (!tempIpInfo.equals(""))) {
        } else {
            tempIpInfo = nullIpInfo;
        }
        return tempIpInfo;
    }

    public String getMask() {
        String tempIpInfo;
        String iface = "eth0";
        tempIpInfo = SystemProperties.get("dhcp." + iface + ".mask");
        if ((tempIpInfo != null) && (!tempIpInfo.equals(""))) {
        } else {
            tempIpInfo = nullIpInfo;
        }
        return tempIpInfo;
    }

    public String getGateway() {
        String tempIpInfo;
        String iface = "eth0";
        tempIpInfo = SystemProperties.get("dhcp." + iface + ".gateway");
        if ((tempIpInfo != null) && (!tempIpInfo.equals(""))) {
        } else {
            tempIpInfo = nullIpInfo;
        }
        return tempIpInfo;
    }

    public String getDns1() {
        String tempIpInfo;
        String iface = "eth0";
        tempIpInfo = SystemProperties.get("dhcp." + iface + ".dns1");
        if ((tempIpInfo != null) && (!tempIpInfo.equals(""))) {
        } else {
            tempIpInfo = nullIpInfo;
        }
        return tempIpInfo;
    }

    public String getDns2() {
        String tempIpInfo;
        String iface = "eth0";
        tempIpInfo = SystemProperties.get("dhcp." + iface + ".dns2");
        if ((tempIpInfo != null) && (!tempIpInfo.equals(""))) {
        } else {
            tempIpInfo = nullIpInfo;
        }
        return tempIpInfo;
    }

    private int maskStr2InetMask(String maskStr) {
        StringBuffer sb;
        String str;
        int inetmask = 0;
        int count = 0;
        /*
         * check the subMask format
         */
        Pattern pattern = Pattern.compile("(^((\\d|[01]?\\d\\d|2[0-4]\\d|25[0-5])\\.){3}(\\d|[01]?\\d\\d|2[0-4]\\d|25[0-5])$)|^(\\d|[1-2]\\d|3[0-2])$");
        if (pattern.matcher(maskStr).matches() == false) {
            Log.e(TAG, "subMask is error");
            return 0;
        }

        String[] ipSegment = maskStr.split("\\.");
        for (int n = 0; n < ipSegment.length; n++) {
            sb = new StringBuffer(Integer.toBinaryString(Integer.parseInt(ipSegment[n])));
            str = sb.reverse().toString();
            count = 0;
            for (int i = 0; i < str.length(); i++) {
                i = str.indexOf("1", i);
                if (i == -1)
                    break;
                count++;
            }
            inetmask += count;
        }
        return inetmask;
    }

    /**
     * Check the IP address is valid
     * @param value
     * @return
     */
    private boolean isIpAddressValid(String value) {
        int start = 0;
        int end = value.indexOf('.');
        int numBlocks = 0;

        while (start < value.length()) {
            if (-1 == end) {
                end = value.length();
            }
            try {
                int block = Integer.parseInt(value.substring(start, end));
                if ((block > 255) || (block < 0)) {
                    Log.w(TAG, "isValidIpAddress() : invalid 'block', block = "
                            + block);
                    return false;
                }
            } catch (NumberFormatException e) {
                Log.w(TAG, "isValidIpAddress() : e = " + e);
                return false;
            }

            numBlocks++;
            start = end + 1;
            end = value.indexOf('.', start);
        }
        return numBlocks == 4;
    }
}

广播接受类用来监听以太网变化 ,wifi变化以及U盘插拔动作

package com.ys.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import com.ys.config.AppConfig;
import com.ys.service.EthListenServer;
import com.ys.util.MyLog;

public class AppReceiver extends BroadcastReceiver {

    //以太网插拔广播
    public static final String ETH_NET_CHANGE_STATE = "android.net.ethernet.ETHERNET_STATE_CHANGED";
    public static final String WIFI_STATE_CHANGE = "android.net.wifi.STATE_CHANGE";
    public static final String BOOT_COMPLENT = "android.intent.action.BOOT_COMPLETED";
    public static final String LUNCHER_START = "android.rkbord.luncher.start";
    public static final String USB_IN = "android.hardware.usb.action.USB_DEVICE_ATTACHED";
    public static final String USB_OUT = "android.hardware.usb.action.USB_DEVICE_DETACHED";

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equals(BOOT_COMPLENT)) { //开机广播
            MyLog.i("haha", "===============开机广播====" + action);
            context.startService(new Intent(context, EthListenServer.class));
        } else if (action.equals(ETH_NET_CHANGE_STATE)) {
            MyLog.i("haha", "==============接收到以太网广播====" + action);
            Intent intent1 = new Intent();
            intent1.setAction(AppConfig.ETH_STATE_CHANHE);
            context.sendBroadcast(intent1);
        } else if (action.equals(WIFI_STATE_CHANGE)) {
            MyLog.i("haha", "==============接收到WIFI广播====" + action);
        } else if (action.equals(LUNCHER_START)) {
            MyLog.i("haha", "==============接收到 LUNCHER_START广播====");
            context.startService(new Intent(context, EthListenServer.class));
        } else if (action.equals(USB_IN)) {
            MyLog.i("haha", "==============接收到 U盘插入广播====");
            context.startService(new Intent(context, EthListenServer.class));
        } else if (action.equals(USB_OUT)) {
            MyLog.i("haha", "==============接收到 U盘拔出广播====");
            context.startService(new Intent(context, EthListenServer.class));
        }
    }
}

service类用来自动监听网络状态,以及网络异常自动恢复的操作

package com.ys.service;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import com.ys.config.AppConfig;
import com.ys.entity.EthNetEntity;
import com.ys.ethernetwatchdog.EthernetControl;
import com.ys.util.MyLog;
import com.ys.util.NetWorkUtil;
import com.ys.util.SharedPerManager;
import com.ys.util.TimerTaskUtil;

import java.io.File;

public class EthListenServer extends Service {

    private static final String TAG = "EthListenServer";

    @Override
    public void onCreate() {
        super.onCreate();
        MyLog.i(TAG, "============SERVICR======oncreate");
        init();
        jujluFileList();
    }

    private void jujluFileList() {
        String fileListPath = AppConfig.BASE_LOG_PATH;
        File file = new File(fileListPath);
        if (!file.exists()) {
            return;
        }
        try {
            File[] fileList = file.listFiles();
            if (fileList.length > 10) {
                fileList[0].delete();
            }
        } catch (Exception e) {
        }
    }

    //    TimerTaskUtil timerTaskUtil;
    EthernetControl ethernetControl;

    private void init() {
        ethernetControl = new EthernetControl(getBaseContext());
//        timerTaskUtil = new TimerTaskUtil();
//        timerTaskUtil.startTimerDistense(AppConfig.CHECK_ETH_DISTANCE_TIME, new TimerTaskUtil.TimerTaskListener() {
//            @Override
//            public void timeIsOn() {
//                checkEthNetState();
//            }
//        });
        Runnable runnable = new TimerRunable();
        Thread thread = new Thread(runnable);
        thread.start();
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case HANDLER_TIMER_WORK:
                    checkEthNetState();
                    break;
            }
        }
    };

    private static final int HANDLER_TIMER_WORK = 8970;

    public class TimerRunable implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep(AppConfig.CHECK_ETH_DISTANCE_TIME);// 线程暂停30秒,单位毫秒
                    Message message = new Message();
                    message.what = HANDLER_TIMER_WORK;
                    handler.sendMessage(message);// 发送消息
                } catch (Exception e) {
                    MyLog.e(TAG, "==========定时器异常了======");
                    e.printStackTrace();
                }
            }
        }
    }


    /***
     * 去监测当前以太网状态
     */
    private void checkEthNetState() {
        String isOnlineEquip = NetWorkUtil.getNetisLine();
        MyLog.i(TAG, "以太网是否插入设备==" + isOnlineEquip);
        if (isOnlineEquip.contains("0")) {
            MyLog.i(TAG, "以太网没有接入,请检查");
            return;
        }
        boolean isOpen = ethernetControl.isEnable();
        MyLog.i(TAG, "以太网是否打开==" + isOpen);
        if (!isOpen) { //没有打开,直接打开
            MyLog.i(TAG, "以太网没有打开,去打开==");
            ethernetControl.setEthernetEnabled(true);
        }
        boolean isNetLine = NetWorkUtil.isNetworkAvalible(getBaseContext());
        MyLog.i(TAG, "当前网络链接状态==" + isNetLine);
        if (isNetLine) { //有网络
            dealOnlineInfo();
        } else {
            dealDisOnlineInfo();
        }
    }

    /**
     * 当前有网络,处理时间
     * true ==动态
     * false==静态
     */
    private void dealOnlineInfo() {
        EthNetEntity entity = ethernetControl.getEthStateFromIpConfig();
        if (entity == null) {
            return;
        }
        Log.e(TAG, "===获取的ipconfig==" + entity.toString());
        boolean ethState = entity.isEthNetState();
        SharedPerManager.setEthState(ethState);
        if (ethState) { //DHCP
//            SharedPerManager.setStaticIp("");
        } else {  //STATIC
            SharedPerManager.setStaticIp(entity.getStaticIpAddress());
        }
    }

    /***
     * 处理没有网络得信息
     */
    private void dealDisOnlineInfo() {
        boolean isEthNetState = SharedPerManager.getEthState();
        MyLog.e(TAG, "====网络异常,上一次保存的状态是true是动态,false静态====" + isEthNetState);
        if (isEthNetState) {  //DPCH
            //1:先设置成静态IP,在设置为动态IP
            String staticIP = SharedPerManager.getStaticIp();
            ethernetControl.setStaticIp(staticIP);
            MyLog.i(TAG, "=========设置网络为静态==");
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    setDhcpState();
                }
            }, AppConfig.CHECK_ETH_DHP_TIME);
        } else {  //static 。先设置成动态 ,在设置成静态
            setDhcpState();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    MyLog.i(TAG, "=========设置网络为静态==");
                    String staticIP = SharedPerManager.getStaticIp();
                    ethernetControl.setStaticIp(staticIP);
                }
            }, AppConfig.CHECK_ETH_DHP_TIME);
        }
    }

    private void setDhcpState() {
        ethernetControl.setDHCP();
        MyLog.i(TAG, "=========设置网络为动态==");
        Intent intent = new Intent();
        intent.setAction(AppConfig.ETH_STATE_DHCP);
        sendBroadcast(intent);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public int onStartCommand(Intent paramIntent, int paramInt1, int paramInt2) {
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
//        if (timerTaskUtil != null) {
//            timerTaskUtil.cacelTimer();
//        }
        Intent intent = new Intent(this, EthListenServer.class);
        startService(intent);
    }
}

========================一些界面,基本用不上===========================================

package com.ys.setstaticip;

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;

public class BaseActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);// 隐藏标题
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }
}
package com.ys.setstaticip;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.ys.config.AppConfig;
import com.ys.demo.R;
import com.ys.ethernetwatchdog.EthernetControl;
import com.ys.service.EthListenServer;
import com.ys.util.Biantai;
import com.ys.util.MyLog;
import com.ys.util.NetWorkUtil;
import com.ys.util.SharedPerManager;
import com.ys.util.TimerTaskUtil;
import com.ys.view.WaitDialogUtil;

public class MainActivity extends Activity implements View.OnClickListener {
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(AppConfig.ETH_STATE_CHANHE)) {
                if (Biantai.isThreeClick()) {
                    return;
                }
                MyLog.e("haha", "=====主界面收到广播。准备刷新界面=" + action);
                updateViewState();
            } else if (action.equals(AppConfig.ETH_STATE_DHCP)) {
                MyLog.e("haha", "=====主界面收到广播。准备刷新界面=" + action);
                updateViewState();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initReceiver();
    }

    Button button_start;
    Button button_dong;
    Button button_open_close;
    EthernetControl ethernetControl;
    TextView tv_eth_state;    //以太网状态
    TextView tv_ip_address;  //以太网IP地址
    TextView tv_eth_type;   //以太网类型
    TextView tv_is_line;    //是否查网线
    TimerTaskUtil timerTaskUtil;
    WaitDialogUtil waitDialogUtil;

    private void initView() {
        waitDialogUtil = new WaitDialogUtil(MainActivity.this);
        timerTaskUtil = new TimerTaskUtil();
        ethernetControl = new EthernetControl(MainActivity.this);
        button_open_close = (Button) findViewById(R.id.button_open_close);
        button_open_close.setText("开关以太网");
        button_start = (Button) findViewById(R.id.button_start);
        button_start.setText("静态IP");
        button_dong = (Button) findViewById(R.id.button_dong);
        button_dong.setText("动态IP");
        button_open_close.setOnClickListener(this);
        button_start.setOnClickListener(this);
        button_dong.setOnClickListener(this);
        tv_eth_state = (TextView) findViewById(R.id.tv_eth_state);
        tv_ip_address = (TextView) findViewById(R.id.tv_ip_address);
        tv_eth_type = (TextView) findViewById(R.id.tv_eth_type);
        tv_is_line = (TextView) findViewById(R.id.tv_is_line);
        updateViewState();
    }

    @Override
    public void onClick(View v) {
        updateViewState();
        switch (v.getId()) {
            case R.id.button_open_close:
                boolean isOpen = ethernetControl.isEnable();
                ethernetControl.setEthernetEnabled(!isOpen);
                break;
            case R.id.button_start:
                String staticIP = SharedPerManager.getStaticIp();
                ethernetControl.setStaticIp(staticIP);
                showToast("设置以太网静态IP");
                break;
            case R.id.button_dong:
                ethernetControl.setDHCP();
                showToast("设置以太网动态IP");
                break;
        }
    }

    public void updateViewState() {
        waitDialogUtil.show("操作中...");
        timerTaskUtil.startTimer(3000, new TimerTaskUtil.TimerTaskListener() {
            @Override
            public void timeIsOn() {
                waitDialogUtil.dismiss();
                updateStateView();
            }
        });
    }

    public void updateStateView() {
        String lightState = NetWorkUtil.getNetisLine();
        MyLog.i("haha", "=====网线是否插入: " + lightState);
        if (lightState.contains("0")) {        //没有插网线
            tv_is_line.setTextColor(0xffC11629);
            tv_is_line.setText("网线状态 :   没有插网线");
        } else if (lightState.contains("1")) { //插网线
            tv_is_line.setTextColor(0xff3fcd3b);
            tv_is_line.setText("网线状态 :   网线已接入");
        } else {
            tv_is_line.setTextColor(0xffC11629);
            tv_is_line.setText("网线状态 :   检测失败");
        }
        boolean isOpenOrClose = ethernetControl.isEnable();
        if (isOpenOrClose) {
            tv_eth_state.setTextColor(0xff3fcd3b);
            tv_eth_state.setText("以太网状态 :   打开");
        } else {
            tv_eth_state.setTextColor(0xffC11629);
            tv_eth_state.setText("以太网状态 :   关闭");
        }
        String ipAddress = NetWorkUtil.getLocalIpAddress();
        tv_ip_address.setText("IP地址 :   " + ipAddress);

        boolean isEthStatic = ethernetControl.isDHCP();
        String ethType = isEthStatic ? "动态IP" : "静态IP";
        tv_eth_type.setText("当前状态 :   " + ethType);

    }


    @Override
    protected void onResume() {
        super.onResume();
        startService(new Intent(MainActivity.this, EthListenServer.class));
    }

    public void showToast(String toast) {
        Toast.makeText(MainActivity.this, toast, Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (receiver != null) {
            unregisterReceiver(receiver);
        }
        if (timerTaskUtil != null) {
            timerTaskUtil.cacelTimer();
        }
    }

    private void initReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(AppConfig.ETH_STATE_CHANHE);
        filter.addAction(AppConfig.ETH_STATE_DHCP);
        registerReceiver(receiver, filter);
    }

}
package com.ys.setstaticip;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.ys.demo.R;


public class StartActivity extends BaseActivity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start);
        initView();
    }

    Button btn_eth,btn_test;

    private void initView() {
        btn_eth = (Button) findViewById(R.id.btn_eth);
        btn_eth.setText("以太网测试");
        btn_test = (Button) findViewById(R.id.btn_test);
        btn_test.setText("功能待定义");
        btn_eth.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_eth:
                startActivity(new Intent(StartActivity.this, MainActivity.class));
                break;
        }
    }
}

下面的是网络工具类 ,也蛮重要的,用来检测以太网有没有插入 ,以及系统保存的IP地址,

package com.ys.util;

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class NetWorkUtil {

    /***
     * 获取局域网IP
     * @return
     */
    public static String getLocalIpAddress() {
        String ipAddress = "0:0:0:0";
        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()) {
                        ipAddress = inetAddress.getHostAddress().toString();
                        if (!ipAddress.contains("::"))
                            return inetAddress.getHostAddress().toString();
                    } else
                        continue;
                }
            }
        } catch (SocketException ex) {
            MyLog.e("haha", ex.toString());
        }
        return ipAddress;
    }


    /***
     * jujle data/data/com/ys/demo/userInfo.xml
     * @return
     */
    public static boolean isFileExicet() {
        try {
            String filePath = "/data/data/com.ys.demo/shared_prefs/userInfo.xml";
            File file = new File(filePath);
            return file.exists();
        } catch (Exception e) {
        }
        return true;
    }


    /**
     * 获取是否插网线
     * 1:表示有插网线
     * 0:表示没有插网线
     *
     * @return
     */

    @SuppressLint("NewApi")
    public static String getNetisLine() {
        String netLineStatePath = "/sys/class/net/eth0/carrier";
        File file = new File(netLineStatePath);
        if (!file.exists()) {  //sys/devices/misc_power_en.22/usb_eth_en
            toOpenEthFileModel();
            return "0";
        }
        StringBuilder result = new StringBuilder();
        try {
            BufferedReader br = new BufferedReader(new FileReader(file));// 构造一个BufferedReader类来读取文件
            String s = null;
            while ((s = br.readLine()) != null) {// 使用readLine方法,一次读一行
                result.append(System.lineSeparator() + s);
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.toString().trim();
    }

    private static final String TAG = "EthListenServer";
    private static final int OPEN_ETH_STATE = 1;

    private static void toOpenEthFileModel() {
        try {
            String ethConfigPath = "/sys/devices/misc_power_en.22/usb_eth_en";
            String ethInfo = readInfoFromSysFile(ethConfigPath);
            int ethInfoInteger = Integer.parseInt(ethInfo);
            MyLog.e(TAG, "=====网络插口文件丢失,1=ok ,0=error, -1=file not exict====:" + ethInfoInteger);
            if (ethInfoInteger < 0) {
                return;
            }
            if (ethInfoInteger != OPEN_ETH_STATE) {
                MyLog.e(TAG, "=====网卡文件异常,去修复文件");
                writeFile(ethConfigPath, OPEN_ETH_STATE);
            }
        } catch (Exception e) {
            MyLog.e(TAG, "=====网卡文件,修复异常: " + e.toString());
        }
    }

    @SuppressLint("NewApi")
    public static String readInfoFromSysFile(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return "-1";
        }
        StringBuilder result = new StringBuilder();
        try {
            BufferedReader br = new BufferedReader(new FileReader(file));// 构造一个BufferedReader类来读取文件
            String s = null;
            while ((s = br.readLine()) != null) {// 使用readLine方法,一次读一行
                result.append(System.lineSeparator() + s);
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.toString().trim();
    }

    public static void writeFile(String sysFilePath, int paramInt) {
        try {
            File localFile = new File(sysFilePath);
            localFile.setExecutable(true);
            localFile.setReadable(true);
            localFile.setWritable(true);
            if (paramInt == 0) {
                do_exec("busybox echo 0 > " + sysFilePath);
                return;
            }
            if (paramInt == 1) {
                do_exec("busybox echo 1 > " + sysFilePath);
                return;
            }
        } catch (Exception localException) {
            Log.e(TAG, "======写入失败:==" + localException);
            localException.printStackTrace();
        }
    }

    public static void do_exec(String paramString) {
        try {
            Process localProcess = Runtime.getRuntime().exec("su");
            String str = paramString + "\nexit\n";
            localProcess.getOutputStream().write(str.getBytes());
            if (localProcess.waitFor() != 0) {
                Log.e(TAG, "====adb 执行写入失败===" + paramString);
                throw new SecurityException();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断网络情况
     *
     * @param context 上下文
     * @return false 表示没有网络 true 表示有网络
     */
    public static boolean isNetworkAvalible(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager == null) {
            return false;
        } else {
            // 建立网络数组
            NetworkInfo[] net_info = connectivityManager.getAllNetworkInfo();
            if (net_info != null) {
                for (int i = 0; i < net_info.length; i++) {
                    // 判断获得的网络状态是否是处于连接状态
                    if (net_info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

}

防止测试暴力测试的工具类

package com.ys.util;

public class Biantai {
    private static long lastClickTime;

    public static boolean isThreeClick() {
        long l1 = System.currentTimeMillis();
        long l2 = l1 - lastClickTime;
        if ((0L < l2) && (l2 < 3000L)) {
            return true;
        }
        lastClickTime = l1;
        return false;
    }

    public static boolean isTwoClick() {
        long l1 = System.currentTimeMillis();
        long l2 = l1 - lastClickTime;
        if ((0L < l2) && (l2 < 2000L)) {
            return true;
        }
        lastClickTime = l1;
        return false;
    }

    public static boolean isOneClick() {
        long l1 = System.currentTimeMillis();
        long l2 = l1 - lastClickTime;
        if ((0L < l2) && (l2 < 1000L)) {
            return true;
        }
        lastClickTime = l1;
        return false;
    }
}

===========文件管理类======用来保存日志的

   

package com.ys.util;

import com.ys.config.AppConfig;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class FileUtils {

    public static void writeTxtToSdcard(String filePath, String content) {
        MyLog.test(TAG, "=====writeTxtToSdcard== " + content);
        FileWriter fw = null;
        try {
            File logFile = new File(AppConfig.BASE_SD_PATH);  //sdcard/ys
            if (!logFile.exists()) {
                boolean isCreste = logFile.mkdirs();
                MyLog.test(TAG, "========" + AppConfig.BASE_SD_PATH + "  //" + isCreste);
            }
            logFile = new File(AppConfig.BASE_LOG_PATH);  //sdcard/ys/log
            if (!logFile.exists()) {
                boolean isCreste = logFile.mkdirs();
                MyLog.test(TAG, "========" + AppConfig.BASE_LOG_PATH + "  //" + isCreste);
            }
            File file = new File(filePath);
            if (!file.exists()) {
                file.createNewFile();
            }
            fw = new FileWriter(file, true);
            MyLog.test(TAG, "=====writeTxtToSdcard success== ");
        } catch (IOException e) {
            MyLog.test(TAG, "=====writeTxtToSdcard error== " + e.toString());
            e.printStackTrace();
        }
        PrintWriter pw = new PrintWriter(fw);
        pw.println(content);
        pw.flush();
        try {
            fw.flush();
            pw.close();
            fw.close();
        } catch (IOException e) {
            MyLog.test(TAG, "=====writeTxtToSdcard resele== " + e.toString());
            e.printStackTrace();
        }
    }

    private static final String TAG = "EthListenServer";
//
//    public static void createFileifNotExicet() {
//        MyMyLog.test(TAG, "=======create file start=====");
//        try {
//            File logFile = new File(AppConfig.BASE_SD_PATH);  //sdcard/ys
//            if (!logFile.exists()) {
//                boolean isCreste = logFile.mkdirs();
//                MyLog.test(TAG, "========" + AppConfig.BASE_SD_PATH + "  //" + isCreste);
//            }
//            logFile = new File(AppConfig.BASE_LOG_PATH);  //sdcard/ys/log
//            if (!logFile.exists()) {
//                boolean isCreste = logFile.mkdirs();
//                MyLog.test(TAG, "========" + AppConfig.BASE_LOG_PATH + "  //" + isCreste);
//            }
//            logFile = new File(AppConfig.BASE_LOG_FILE);  ////sdcard/ys/log/ethNetListener.txt
//            if (!logFile.exists()) {
//                boolean isCreste = logFile.createNewFile();
//                MyLog.test(TAG, "========" + AppConfig.BASE_LOG_FILE + "  //" + isCreste);
//            }
//        } catch (Exception e) {
//            MyMyLog.test(TAG, "=======create file= error====" + e.toString());
//        }
//    }


}

log类,用来写入log的

package com.ys.util;

import android.util.Log;


public class MyLog {

    public static void i(String tag, String desc) {
        Log.i(tag, desc);
        FileUtils.writeTxtToSdcard(SimpleDateUtil.getSaveFilePath(), SimpleDateUtil.getSuccrentTime() + "/" + desc);
    }

    public static void e(String tag, String desc) {
        Log.e(tag, desc);
        FileUtils.writeTxtToSdcard(SimpleDateUtil.getSaveFilePath(), SimpleDateUtil.getSuccrentTime() + "/" + desc);
    }

    public static void test(String tag, String desc) {
//        Log.e(tag, desc);
    }

}

=============SharedPerference工具类======

package com.ys.util;


import com.ys.EthNetApplication;
import com.ys.config.AppConfig;

public class SharedPerManager {
    /***
     * true ==DPCH
     * false==STATIC
     */
    public static boolean getEthState() {
        boolean ethState = (boolean) EthNetApplication.getIntance().getData("ethState", true);
        return ethState;
    }

    public static void setEthState(boolean ethState) {
        EthNetApplication.getIntance().saveData("ethState", ethState);
    }


    public static String getStaticIp() {
        String staticIP = (String) EthNetApplication.getIntance().getData("staticIp", AppConfig.STATIC_IPADDRESS);
        return staticIP;
    }

    public static void setStaticIp(String staticIp) {
        EthNetApplication.getIntance().saveData("staticIp", staticIp);
    }
}

======================时间解析类,====用来生成文件名=

package com.ys.util;

import android.annotation.SuppressLint;

import com.ys.config.AppConfig;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

@SuppressLint({"SimpleDateFormat"})
public class SimpleDateUtil {

    public static String getSaveFilePath() {
        long l = System.currentTimeMillis();
        String str = new SimpleDateFormat("yyyyMMdd").format(Long.valueOf(l));
        String basePath = AppConfig.BASE_LOG_PATH;
        return basePath + "/" + str + ".txt";
    }

    public static String getSuccrentTime() {
        return new SimpleDateFormat("yyyy/MM/dd/ HH:mm:ss").format(System.currentTimeMillis());
    }
}

=========定时器,工具类,目前用线程替代了timer了,===============

package com.ys.util;

import android.os.Handler;
import android.os.Message;

import java.util.Timer;
import java.util.TimerTask;

public class TimerTaskUtil {

    private static final String TAG = "ScreenViewService";
    TimerTaskListener listener;
    long timeLength;

    Timer timer;
    MyTask task;


    public void startTimer(long timeLength, TimerTaskListener listener) {
        this.listener = listener;
        this.timeLength = timeLength;
        cacelTimer();
        timer = new Timer(true);
        task = new MyTask();
        timer.schedule(task, timeLength);
    }


    public void startTimerDistense(long timeLength, TimerTaskListener listener) {
        this.listener = listener;
        this.timeLength = timeLength;
        cacelTimer();
        timer = new Timer(true);
        task = new MyTask();
        timer.schedule(task, 1000, timeLength);
    }

    public void cacelTimer() {
        if (timer != null) {
            timer.cancel();
        }
        if (task != null) {
            task.cancel();
        }
    }

    class MyTask extends TimerTask {
        @Override
        public void run() {
            handler.sendEmptyMessage(START_TIMER);
        }
    }

    private static final int START_TIMER = 234;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == START_TIMER) {
                listener.timeIsOn();
            }
        }
    };

    public interface TimerTaskListener {
        /***
         * 监听的时间到了
         */
        void timeIsOn();
    }


}

====================等待框。=======================

package com.ys.view;


import android.app.Dialog;
import android.content.Context;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.TextView;

import com.ys.demo.R;

public class WaitDialogUtil {

    Dialog waitDialog;
    Context context;
    public static final String TAG = WaitDialogUtil.class.getName();
    private final TextView mTv;

    public WaitDialogUtil(Context context) {
        this.context = context;
        waitDialog = new Dialog(context, R.style.MyDialog);
        View recdialog = View.inflate(context, R.layout.dialog_wait, null);
        mTv = (TextView) recdialog.findViewById(R.id.tv_dialog_wait);
        waitDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        waitDialog.setContentView(recdialog);
        waitDialog.setCanceledOnTouchOutside(false);
        waitDialog.setCancelable(true);
        waitDialog.getWindow().setGravity(Gravity.CENTER);
    }

    public void show(String text_dialog) {
        dismiss();
        mTv.setText(text_dialog);
        waitDialog.show();
    }

    public void dismiss() {
        if (waitDialog != null && waitDialog.isShowing()) {
            waitDialog.dismiss();
        }
    }

    public boolean isShowing() {
        if (waitDialog != null && waitDialog.isShowing()) {
            return true;
        }
        return false;
    }
}

==========================application类==========

package com.ys;

import android.app.Application;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;

import com.ys.util.FileUtils;

public class EthNetApplication extends Application {

    private static SharedPreferences mSharedPreferences;
    public static String USER_INFO = "userInfo";
    public static EthNetApplication instance;

    public static EthNetApplication getIntance() {
        return instance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        mSharedPreferences = getSharedPreferences(USER_INFO, MODE_PRIVATE);
    }

    public void saveData(String key, Object data) {
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        try {
            Log.i("SharedPreferences", "setting info tag =" + key + "   //date = " + data);
            if (data instanceof Integer) {
                editor.putInt(key, (Integer) data);
            } else if (data instanceof Boolean) {
                editor.putBoolean(key, (Boolean) data);
            } else if (data instanceof String) {
                editor.putString(key, (String) data);
            } else if (data instanceof Float) {
                editor.putFloat(key, (Float) data);
            } else if (data instanceof Long) {
                editor.putLong(key, (Long) data);
            }
        } catch (Exception e) {
            Log.i("SharedPreferences", "setting info error tag =" + key + "   //date = " + e.toString());
        }
        editor.commit();
    }

    public Object getData(String key, Object defaultObject) {
        try {
            Log.i("SharedPreferences", "tag =" + key + "   //date = " + defaultObject.toString());
            if (defaultObject instanceof String) {
                return mSharedPreferences.getString(key, (String) defaultObject);
            } else if (defaultObject instanceof Integer) {
                return mSharedPreferences.getInt(key, (Integer) defaultObject);
            } else if (defaultObject instanceof Boolean) {
                return mSharedPreferences.getBoolean(key, (Boolean) defaultObject);
            } else if (defaultObject instanceof Float) {
                return mSharedPreferences.getFloat(key, (Float) defaultObject);
            } else if (defaultObject instanceof Long) {
                return mSharedPreferences.getLong(key, (Long) defaultObject);
            }
        } catch (Exception e) {
            Log.i("SharedPreferences", "get info error====>>>tag =" + key + "   //date = " + e.toString());
            return null;
        }
        return null;
    }

    public void restartApp() {
        Log.i("SharedPreferences", "=====获取数据异常,重启APP===");
        Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

}

  

猜你喜欢

转载自blog.csdn.net/fkgjdkblxckvbxbgb/article/details/80917852
今日推荐