发布网友 发布时间:2022-04-23 13:41
共1个回答
热心网友 时间:2023-09-14 20:03
Android Ethernet 有线网络监听
import android.net.ConnectivityManager;
ConnectivityManager conn = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] networkInfo = conn.getAllNetworkInfo();
if(networkInfo != null){
for(int i=0;i<networkInfo.length;i++){
if(networkInfo[i].getType() == ConnectivityManager.TYPE_ETHERNET){
//有线网络连接成功,更新UI
}
}
}
// 监听有线网络连接状态(插拔网线)
private BroadcastReceiver mEthernetReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ConnectivityManager.ACTION_ETHERNET_STATE_CHANGED)){
String state = intent.getStringExtra(ConnectivityManager.EXTRA_ETH_STATUS);
if(state.equals(ConnectivityManager.EXTRA_ETH_CONNECT)){
//网线连接成功!
}
else if(state.equals(ConnectivityManager.EXTRA_ETH_UNLINK)){
//网线断开!
}
}
}
};
IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
filter.addAction(ConnectivityManager.INET_CONDITION_ACTION);
filter.addAction(ConnectivityManager.ACTION_ETHERNET_STATE_CHANGED);
filter.addAction(ConnectivityManager.ACTION_ETHERNET_DONGLE_IN);
filter.addAction(ConnectivityManager.ACTION_ETHERNET_DONGLE_OUT);
registerReceiver(mEthernetReceiver, filter);
添加权限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />