我想创建一个使用互联网的应用程序,我试图创建一个功能,检查连接是否可用,如果它不是,去到一个活动,有一个重试按钮和解释。
附件是我的代码到目前为止,但我得到的错误语法错误,插入“}”来完成MethodBody。
现在我已经把这些放在试图让它工作,但到目前为止没有运气…任何帮助都将不胜感激。
public class TheEvoStikLeagueActivity extends Activity {
private final int SPLASH_DISPLAY_LENGHT = 3000;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
private boolean checkInternetConnection() {
ConnectivityManager conMgr = (ConnectivityManager) getSystemService (Context.CONNECTIVITY_SERVICE);
// ARE WE CONNECTED TO THE NET
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected()) {
return true;
/* New Handler to start the Menu-Activity
* and close this Splash-Screen after some seconds.*/
new Handler().postDelayed(new Runnable() {
public void run() {
/* Create an Intent that will start the Menu-Activity. */
Intent mainIntent = new Intent(TheEvoStikLeagueActivity.this, IntroActivity.class);
TheEvoStikLeagueActivity.this.startActivity(mainIntent);
TheEvoStikLeagueActivity.this.finish();
}
}, SPLASH_DISPLAY_LENGHT);
} else {
return false;
Intent connectionIntent = new Intent(TheEvoStikLeagueActivity.this, HomeActivity.class);
TheEvoStikLeagueActivity.this.startActivity(connectionIntent);
TheEvoStikLeagueActivity.this.finish();
}
}
}
不需要太复杂。最简单的框架方式是使用ACCESS_NETWORK_STATE权限并创建一个连接的方法
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnectedOrConnecting();
}
如果您有特定的主机和连接类型(wifi/移动),也可以使用requestRouteToHost。
你还需要:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
在你的android清单中。
更多细节请点击这里
检查以确保它“连接”到网络:
public boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected();
}
检查以确保它“连接”到互联网:
public boolean isInternetAvailable() {
try {
InetAddress address = InetAddress.getByName("www.google.com");
return !address.equals("");
} catch (UnknownHostException e) {
// Log error
}
return false;
}
需要许可:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
https://stackoverflow.com/a/17583324/950427
检查网络可用在android与互联网数据速度。
public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager) Login_Page.this.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
try
{
HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(500); //choose your own timeframe
urlc.setReadTimeout(500); //choose your own timeframe
urlc.connect();
int networkcode2 = urlc.getResponseCode();
return (urlc.getResponseCode() == 200);
} catch (IOException e)
{
return (false); //connectivity exists, but no internet.
}
}
}
return false;
}
此函数返回true或false。
必须获得用户权限
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
所有的官方方法都只说明设备是否对网络开放,
如果你的设备连接到Wifi,但Wifi没有连接到互联网,那么这些方法会失败(发生了很多次),没有内置的网络检测方法会告诉这种情况,所以创建了Async回调类,它将在onConnectionSuccess和onConnectionFail中返回
new CheckNetworkConnection(this, new CheckNetworkConnection.OnConnectionCallback() {
@Override
public void onConnectionSuccess() {
Toast.makeText(context, "onSuccess()", toast.LENGTH_SHORT).show();
}
@Override
public void onConnectionFail(String msg) {
Toast.makeText(context, "onFail()", toast.LENGTH_SHORT).show();
}
}).execute();
异步任务的网络调用
public class CheckNetworkConnection extends AsyncTask < Void, Void, Boolean > {
private OnConnectionCallback onConnectionCallback;
private Context context;
public CheckNetworkConnection(Context con, OnConnectionCallback onConnectionCallback) {
super();
this.onConnectionCallback = onConnectionCallback;
this.context = con;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Boolean doInBackground(Void...params) {
if (context == null)
return false;
boolean isConnected = new NetWorkInfoUtility().isNetWorkAvailableNow(context);
return isConnected;
}
@Override
protected void onPostExecute(Boolean b) {
super.onPostExecute(b);
if (b) {
onConnectionCallback.onConnectionSuccess();
} else {
String msg = "No Internet Connection";
if (context == null)
msg = "Context is null";
onConnectionCallback.onConnectionFail(msg);
}
}
public interface OnConnectionCallback {
void onConnectionSuccess();
void onConnectionFail(String errorMsg);
}
}
将ping到服务器的实际类
class NetWorkInfoUtility {
public boolean isWifiEnable() {
return isWifiEnable;
}
public void setIsWifiEnable(boolean isWifiEnable) {
this.isWifiEnable = isWifiEnable;
}
public boolean isMobileNetworkAvailable() {
return isMobileNetworkAvailable;
}
public void setIsMobileNetworkAvailable(boolean isMobileNetworkAvailable) {
this.isMobileNetworkAvailable = isMobileNetworkAvailable;
}
private boolean isWifiEnable = false;
private boolean isMobileNetworkAvailable = false;
public boolean isNetWorkAvailableNow(Context context) {
boolean isNetworkAvailable = false;
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
setIsWifiEnable(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected());
setIsMobileNetworkAvailable(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected());
if (isWifiEnable() || isMobileNetworkAvailable()) {
/*Sometime wifi is connected but service provider never connected to internet
so cross check one more time*/
if (isOnline())
isNetworkAvailable = true;
}
return isNetworkAvailable;
}
public boolean isOnline() {
/*Just to check Time delay*/
long t = Calendar.getInstance().getTimeInMillis();
Runtime runtime = Runtime.getRuntime();
try {
/*Pinging to Google server*/
Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
int exitValue = ipProcess.waitFor();
return (exitValue == 0);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
long t2 = Calendar.getInstance().getTimeInMillis();
Log.i("NetWork check Time", (t2 - t) + "");
}
return false;
}
}