apk上层做了个类似dns解析的小功能,主要分为两步:
- 1.判断当前网络是否通畅
涉及下面两个类
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
boolean isNetworkAvailable(Context context) { ConnectivityManager connectivity = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivity != null) { NetworkInfo info = connectivity.getActiveNetworkInfo(); if (info != null && info.isConnected()) { if (info.getState() == NetworkInfo.State.CONNECTED) { return true; } } } return false; }
- 2.解析域名
涉及下面类
import java.net.InetAddress;
InetAddress address = InetAddress.getByName("www.baidu.com"); //下面的hostaddress 既是类似180.97.33.108这样的点分形式 String HostAddress = address.getHostAddress();
下面是InetAddress.getByName的api文档,使用时需要注意输入和捕获异常,此外android也规定网络连接等耗时的操作需要另起一个线程,不能在主线程运行。
public static InetAddress getByName (String host) Added in API level 1 Returns the address of a host according to the given host string name host. The host string may be either a machine name or a dotted string IP address. If the latter, the hostName field is determined upon demand. host can be null which means that an address of the loopback interface is returned. Parameters host the hostName to be resolved to an address or null. Returns the InetAddress instance representing the host. Throws UnknownHostException if the address lookup fails.