How to detect the event of network type change Android?

前端 未结 1 1849
忘了有多久
忘了有多久 2020-12-12 06:10

I have the following code that works to detect the current network type when is launched, but I would like the app detects when network type changes, for example from 3G to

相关标签:
1条回答
  • 2020-12-12 06:30

    From your question i understand that you need to know what is network state of phone. In case 5 it partially correct because both wifi and mobile data opened. So when you got mobile data open call your method whose contains TelephonyManager. and you can get what is mobile data current state. Below method is the sample of getting network state.

    Note call this method when you got callback that your mobile data is enable

    .

    String getMobileDataState(Context context){
    TelephonyManager mTelephonyManager = (TelephonyManager)
                context.getSystemService(Context.TELEPHONY_SERVICE);
        int networkType = mTelephonyManager.getNetworkType();
        switch (networkType) {
            case TelephonyManager.NETWORK_TYPE_GPRS:
            case TelephonyManager.NETWORK_TYPE_EDGE:
            case TelephonyManager.NETWORK_TYPE_CDMA:
            case TelephonyManager.NETWORK_TYPE_1xRTT:
            case TelephonyManager.NETWORK_TYPE_IDEN:
                return "2G";
            case TelephonyManager.NETWORK_TYPE_UMTS:
            case TelephonyManager.NETWORK_TYPE_EVDO_0:
            case TelephonyManager.NETWORK_TYPE_EVDO_A:
            case TelephonyManager.NETWORK_TYPE_HSDPA:
            case TelephonyManager.NETWORK_TYPE_HSUPA:
            case TelephonyManager.NETWORK_TYPE_HSPA:
            case TelephonyManager.NETWORK_TYPE_EVDO_B:
            case TelephonyManager.NETWORK_TYPE_EHRPD:
            case TelephonyManager.NETWORK_TYPE_HSPAP:
                return "3G";
            case TelephonyManager.NETWORK_TYPE_LTE:
                return "4G";
            default:
                return "Unknown";
    }
    
    0 讨论(0)
提交回复
热议问题