我使用以下代码检查电话是否有 Internet 连接:
online = SystemCheckInternetConn.getInstance(this).isOnline(this);
如何不断检查手机是否有连接?
我使用以下代码检查电话是否有 Internet 连接:
online = SystemCheckInternetConn.getInstance(this).isOnline(this);
如何不断检查手机是否有连接?
您需要注册一个广播接收器来收听连接的变化。尝试这样的事情:
registerReceiver(MyNetworkStateReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
private BroadcastReceiver NetworkStateReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
boolean haveConnection = haveNetworkConnection(context);
}
private boolean haveNetworkConnection(Context context) {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
};
然后用这些新发现的知识做点什么:)