Android检查互联网连接

时间:2017-01-18 05:04:48

标签: android

enter image description here

我正在创建一个应用程序,其中启动活动获取用户的位置,当它获取位置时,它将用户重定向到另一个活动。但是当没有可用的互联网时,它不能将用户重定向到另一个活动< / p>

这是我的主要活动代码的一部分:

protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(networkReceiver, filter);  //here i have registerd the receiver
// create class object
final GPSTracker gps = new GPSTracker(WelcomeActivity.this);
// check if GPS enabled
if (gps.canGetLocation()) {

    latitude = gps.getLatitude();
    longitude = gps.getLongitude();
    if (latitude != 0.0 && longitude != 0.0) {
        if (Utils.isNetworkAvailable(WelcomeActivity.this)) {
            fetchlocation.setText("Fetching your Location...");
            sendGetAddressRequest(latitude, longitude);
        }
        else
            fetchlocation.setText("No Internet Connectivity");
    } else {
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                latitude = gps.getLatitude();
                longitude = gps.getLongitude();
                if (latitude != 0.0 && longitude != 0.0) {
                    if (Utils.isNetworkAvailable(WelcomeActivity.this)) {
                        fetchlocation.setText("Fetching your Location...");
                        sendGetAddressRequest(latitude, longitude);
                    } else
                        fetchlocation.setText("No Internet Connectivity");
                } else {
                    Toast.makeText(WelcomeActivity.this, "Couldn't detect location", Toast.LENGTH_LONG).show();
                }
            }
        }, 5000);
    }


} else {
   // fetchlocation.setText("Enable Location First");
    gps.showSettingsAlert();
}

}

这是在onPause:

@Override
protected void onPause() {
    unregisterReceiver(networkReceiver); // here i have unregistered the receiver
    super.onPause();
}
public boolean isNetworkConnected() {
    ConnectivityManager cm =
            (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;
}

这是我的NetwrokConnectivity代码:

@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getExtras() != null) {
        NetworkInfo ni = (NetworkInfo) intent.getExtras().get(ConnectivityManager.EXTRA_NETWORK_INFO);
        if (ni != null && ni.getState() == NetworkInfo.State.CONNECTED) {
            // we're connected
        }
    }
}

当没有互联网可用时,textview显示文本为Np互联网连接......当我打开互联网时它仍然显示没有互联网连接......我想要的是互联网即将到来或我打开了无线网络或者网络数据,textview必须将文本显示为获取您的位置并将用户重定向到另一个活动

3 个答案:

答案 0 :(得分:0)

for obj in parsed_string["somethings"]:
    print(obj["param1"])

如果此private boolean isNetworkAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } 为真,则表示您具有网络连接,然后执行以下操作:

boolean

您还需要:

if(isNetworkAvailable()){
     // perform your operation here 
}

答案 1 :(得分:0)

从您的活动中调用此方式:

  

getNetworkType(活性)

获取wifi或SIM卡:

public static String getNetworkType(final Context activity) {
        String networkStatus = "";

        final ConnectivityManager connMgr = (ConnectivityManager)activity.getSystemService(Context.CONNECTIVITY_SERVICE);
        // check for wifi
        final android.net.NetworkInfo wifi =connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        // check for mobile data
        final android.net.NetworkInfo mobile =connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

        if (wifi.isConnected() && wifi.isAvailable()) {
            networkStatus = "Wifi";
        } else if (mobile.isAvailable()&& mobile.isConnected()) {
            networkStatus = getDataType(activity);
        } else {
            networkStatus = "noNetwork";
        }
        return networkStatus;
}

getDataType()方法:

更准确的细节(2G,3G或4G)。

public static String getDataType(Context activity) {
    String type = "Mobile Data";
    TelephonyManager tm = (TelephonyManager) activity.getSystemService(Context.TELEPHONY_SERVICE);
    System.out.println("tm.getNetworkType(): "+tm.getNetworkType());
    switch (tm.getNetworkType()) {
        case TelephonyManager.NETWORK_TYPE_HSDPA:
            type = "Mobile Data 3G";
            Log.d("Type", "3g");
            // for 3g HSDPA networktype will be return as
            // per testing(real) in device with 3g enable
            // data
            // and speed will also matters to decide 3g network type
            break;
        case TelephonyManager.NETWORK_TYPE_HSPAP:
            type = "Mobile Data 4G";
            Log.d("Type", "4g");
            // No specification for the 4g but from wiki
            // i found(HSPAP used in 4g)
            break;
        case TelephonyManager.NETWORK_TYPE_CDMA:
            type = "Mobile Data CDMA";
            Log.d("Type", "CDMA");
            // No specification for the CDMA but from wiki
            break;

        case TelephonyManager.NETWORK_TYPE_LTE:
            type = "Mobile Data 4G LTE";
            Log.d("Type", "LTE");
            break;

        case TelephonyManager.NETWORK_TYPE_GPRS:
            type = "Mobile Data GPRS";
            Log.d("Type", "GPRS");
            break;

        case TelephonyManager.NETWORK_TYPE_EDGE:
            type = "Mobile Data EDGE 2G";
            Log.d("Type", "EDGE 2g");
            break;

        case TelephonyManager.NETWORK_TYPE_UNKNOWN:
            type = "Mobile Data UNKNOWN";
            Log.d("Type", "unknown");
            break;

    }
    return type;
}

答案 2 :(得分:0)

您必须检查您是否已连接到互联网,而不仅仅是连接到wifi网络。你可能想试试这个:

try {
        HttpURLConnection urlc = (HttpURLConnection) (new URL("http://google.com").openConnection());
        urlc.setRequestProperty("User-Agent", "Test");
        urlc.setRequestProperty("Connection", "close");
        urlc.setConnectTimeout(1500);
        urlc.connect();

        isConnected = true;

}catch (IOException e) {

        isConnected = false;

}