我有一个代码来确定是否有网络连接:
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected())
{
// There is an internet connection
}
Run Code Online (Sandbox Code Playgroud)
但是,如果有网络连接而没有互联网,这是没用的.我必须ping一个网站并等待响应或超时以确定互联网连接:
URL sourceUrl;
try {
sourceUrl = new URL("http://www.google.com");
URLConnection Connection = sourceUrl.openConnection();
Connection.setConnectTimeout(500);
Connection.connect();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
// no Internet
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
// no Internet
}
Run Code Online (Sandbox Code Playgroud)
但这是一个缓慢的检测.我应该学习一种快速的方法来检测它.
提前致谢.
我在控制器的负载上加载了一个临时广告.加载完成后,广告会自动开始投放.听到广告的声音.加载代码如下:
interstitial = [[GADInterstitial alloc] initWithAdUnitID:admobInterstatialID];
GADRequest *request = [GADRequest request];
[interstitial loadRequest:request];
Run Code Online (Sandbox Code Playgroud)
展示广告代码如下:
if ([interstitial isReady]) {
[interstitial presentFromRootViewController:self];
}
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助!