简体   繁体   English

检查3g,4g是否已连接android

[英]Check if 3g,4g is connected android

I am using below code to check if any kind of connectivity is available on mobile or tablet. 我正在使用下面的代码来检查手机或平板电脑上是否有任何类型的连接。 It is working fine with WiFi and GPRS. WiFi和GPRS都可以正常工作。 Unfortunately I have no 3g access, therefore I cannot check if this code is working. 不幸的是,我没有3g访问权限,因此无法检查此代码是否正常工作。 If any of you please can confirm it? 如果有人可以确认吗? And how much it effect battery life? 对电池寿命有多大影响?

 private  boolean chkConnectivity() {
    boolean isConnected = false;

    ConnectivityManager connManager = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    android.net.NetworkInfo mobile = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    if( mobile.isAvailable() && mobile.getDetailedState() == NetworkInfo.DetailedState.CONNECTED ){
        Toast.makeText(ctx, "3g", Toast.LENGTH_SHORT).show();
        return true;
    }
    if (mWifi.isAvailable() && mWifi.getDetailedState() == NetworkInfo.DetailedState.CONNECTED ) {
        Toast.makeText(ctx, "WiFi", Toast.LENGTH_SHORT).show();
        return true;
    }
    try {
        TelephonyManager mgr = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
        int networkType = mgr.getNetworkType();
        if (networkType == TelephonyManager.NETWORK_TYPE_GPRS){
            Class cmClass = Class.forName(connManager.getClass().getName());
            Method method = cmClass.getDeclaredMethod("getMobileDataEnabled");
            method.setAccessible(true);
            isConnected = (Boolean)method.invoke(connManager);
            if (isConnected){
                Toast.makeText(ctx, "GPRS", Toast.LENGTH_SHORT).show();
                return isConnected;
            }
        }
        Toast.makeText(ctx, "No connection", Toast.LENGTH_SHORT).show();
        return isConnected;

    } catch (Exception e) {
        return false;
    }

}

Sorry I was late. 对不起,我来晚了。

This is how your app runs. 这就是您的应用程序运行的方式。 No problem in it. 没问题

Without data 没有数据

图片2

With data 有数据 在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM