我搜索了这个并且无法解决问题,请查看其他示例中检查的代码:
public class EntryActivity extends Activity {
public Boolean isNetAvailable(Context con) {
try{
ConnectivityManager connectivityManager = (ConnectivityManager)
con.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifiInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo mobileInfo =connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifiInfo.isConnected() || mobileInfo.isConnected()) {
return true;
}
}
catch(Exception e){
e.printStackTrace();
}
return false;
当我在 onCreate 方法中调用它时,此方法效果很好,如下所示:
if (isNetAvailable(getApplicationContext())) {
Toast.makeText(EntryActivity.this,
"You have Internet Connection, wait a moment to sincronize" +
"Metar's stations", Toast.LENGTH_LONG)
.show();
Intent myIntent = new Intent(this, MainActivity.class);
startActivity(myIntent);
} else {
Toast.makeText(EntryActivity.this,
"You Do not have Internet Connection",
Toast.LENGTH_LONG).show();
EntryActivity.this.startActivity(new Intent(
Settings.ACTION_WIRELESS_SETTINGS));
}
这仅适用于第一次互联网连接检查!问题是,如果Wifi关闭,用户应该离开应用程序或打开Wi-Fi。但是,如果他打开它,我无法访问该更改,我无法前进到我的其他活动。 因此,如果在开始互联网连接状态下降时,我想继续检查用户是否将其打开以提示其他活动。 我该怎么办?
答案 0 :(得分:0)
您不需要每隔一段时间执行一次代码来检查Internet连接更改。相反,您需要在应用中定义广播接收器以侦听网络更改。
看到这个答案 How can I monitor the network connection status in Android?
答案 1 :(得分:0)
在你的android清单中:
<receiver android:name="com.softteco.clivero.receivers.ConnectionReceiver" >
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
创建课程:
public class ConnectionReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
boolean newConnectionState = isConnected(context);
}
private boolean isConnected(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] info = connectivityManager.getAllNetworkInfo();
boolean ifConnected = false;
for (int i = 0; i < info.length; i++) {
NetworkInfo connection = info[i];
if (connection.getState().equals(NetworkInfo.State.CONNECTED)) {
ifConnected = true;
}
}
return ifConnected;
}
}
这是可能的变种之一。希望它会对你有所帮助。
答案 2 :(得分:0)
这可以帮助您监控网络连接Wi-Fi,GPRS,UMTS等
public boolean isNetworkAvailable(Context context)
{
ConnectivityManager manager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
return info!=null;
}
还要确保您在Manifest
文件中添加了必需权限,例如
<uses-permission android:name="android.permission.INTERNET" >
</uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" >
</uses-permission>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" >
</uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" >
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" >
</uses-permission>