1

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 LTE, LTE to 3G, 3G to 2G, etc.

I found the class NetworkStateReceiver for BroadcastReceiver here but doesn't show anything when I change network.

May someone help me how would be a way to not only shows the network type when app is launched but shows/detect the event of a network type change?

I'm trying for Android 6.0.1

package com.example.myapp;

import androidx.appcompat.app.AppCompatActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;



public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        TelephonyManager teleMan = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
        int networkType = teleMan.getNetworkType();

        switch (networkType)
        {
            case 1:     Log.e("TAG", "GPRS");       break;
            case 2:     Log.e("TAG","EDGE");        break;
            case 3:     Log.e("TAG","UMTS");        break;
            case 13:    Log.e("TAG","LTE");             break;
        }

    }

    public class NetworkStateReceiver extends BroadcastReceiver
    {
        public void onReceive(Context context, Intent intent)
        {
            Log.e("app","Network connectivity change");

            if(intent.getExtras() != null)
            {
                NetworkInfo ni = (NetworkInfo) intent.getExtras().get(ConnectivityManager.EXTRA_NETWORK);
                if(ni != null && ni.getState() == NetworkInfo.State.CONNECTED)
                {
                    Log.e("app", "Network " + ni.getTypeName() + " connected");
                }
            }

            if(intent.getExtras().getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY, Boolean.FALSE))
            {
                Log.e("app", "There's no network connectivity");
            }
        }
    }
}

The manifest I have is like this:

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />


    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
            </intent-filter>
        </activity>
    </application>

Thanks for any help.

UPDATE 2

I've been looking without success for a way to trigger the event when a phone changes network type (i.e. from 2G to 3G, 3G to LTE and vice).

I found some codes like this here that works very well to trigger the event when the phone changes from "No internet connection" to "Wifi" or to "Mobile Data" using a Broacaster Receiver and ConnectivityManager with .TYPE_WIFI and TYPE_MOBILE and sending a Toast message to display to alert about the change.

What I understand is that ConnectivityManager helps to trigger the event when changes from WIFI to MOBILE or viceversa, but when the phone is in status TYPE_MOBILE and there are changes in network type between 2G, 3G or LTE, there is no trigger generated for these changes. I even add TelephonyManager to handle the different NETWORK_TYPEs but it doesn't work.

What is needed to do in order to trigger the event when the phone changes between 2G, 3G or LTE in the moment that occurs the change?

I've incorporated the current answer but doesn't work for my goal.

I'm trying for Android 6.

The Util class I have so far is this:

class NetworkUtil{

public static String getConnectivityStatusString(Context context) {
    String status = null;
    String mobile_status = null;

    ConnectivityManager cm = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();


    TelephonyManager mTelephonyManager = (TelephonyManager)
            context.getSystemService(Context.TELEPHONY_SERVICE);
    int networkType = mTelephonyManager.getNetworkType();
    switch (networkType) {
        case TelephonyManager.NETWORK_TYPE_GPRS:
        case TelephonyManager.NETWORK_TYPE_EDGE:
            mobile_status = "2G"; break;
        case TelephonyManager.NETWORK_TYPE_UMTS:
        case TelephonyManager.NETWORK_TYPE_HSPA:
            mobile_status = "3G"; break;
        default:
            mobile_status = "Unknown"; break;
    }


    if (activeNetwork != null) {
        if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
            status = "Wifi enabled";
            return status;
        } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE && mobile_status == "2G") {
            status = "2G enabled";
            return status;
        } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE && mobile_status == "3G") {
            status = "3G enabled";
            return status;
        } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE && mobile_status == "Unknown") {
            status = "Mobile unknown enabled";
            return status;
        }
    } else {
        status = "No internet is available";
        return status;
    }

    return status;
}

Thanks for any help.

Ger Cas
  • 2,188
  • 2
  • 18
  • 45
  • 1
    Did you register your receiver? – Tariqul Islam Aug 20 '19 at 06:13
  • Create a dynamic receiver and register it. getNetworkType gets connection type, but it is not a listener. https://stackoverflow.com/questions/42315539/dynamic-broadcastreceiver-to-check-online-connectivity – zakjma Aug 20 '19 at 07:25
  • @zakjma Hello. Thanks for answer. I'm very new to Android programming. What do you mean with register the receiver? May you show me an example please. I saw the link you shared and they seems to monitor the connectivity. That would work to monitor when the network type changes? – Ger Cas Aug 20 '19 at 15:34
  • @TariqulIslam Hello. Thanks for answer. What does mean register the receiver? – Ger Cas Aug 20 '19 at 15:35
  • You using NetworkStateReceiver. This is caled broadcast receiver and these receiver need to be register for enable. registerReceiver(yourReceiver,intentFileter). interfilter indicates which part want to monitor – Tariqul Islam Aug 20 '19 at 16:10
  • @TariqulIslam I'm very new to Android programming. May you show me an example how would be the correct way to define/register the broadcast receiver for this purpose please. Thanks again – Ger Cas Aug 20 '19 at 16:51
  • 1
    There is two type of receiver registration 1. By java code. 2. By manifest. you can get an idea about broadcast receiver of network change from https://www.viralpatel.net/android-internet-connection-status-network-change/ – Tariqul Islam Aug 21 '19 at 04:11
  • @TariqulIslam Hello again. Many thanks for the link share. I've tried that code and it helped a lot. The only thing is for me is working partially since when I activate WiFi is not showing that correctly for example. May you see my update in my original post please. Thanks – Ger Cas Aug 21 '19 at 07:02
  • What intent filter I should use for network type detection? https://stackoverflow.com/questions/72473630/detect-network-type-changes-in-broadcast-receiver – Hoo Jun 03 '22 at 02:25

1 Answers1

3

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";
}
Tariqul Islam
  • 680
  • 6
  • 14
  • Thanks for your answer. This enriches the code since if it is mobile data will tell the network type. The issue I found is that never seems to show `wifi enabled` in the code of link you shared even the condition exists in the code. What I see is the code is not working as expected since says "No internet connection" when there is mobile data for example or immediately I put the Air Plane mode in OFF shows "no internet connection".Is like the trigger shows the wrong message. I don't know. I hope make sense. – Ger Cas Aug 21 '19 at 10:45
  • Ok. actually i gave the link for understanding how to register broadcast receiver that nearly similar to your work. I hope i will give you some good resources that how i you will get network type state – Tariqul Islam Aug 21 '19 at 10:59
  • Thanks so much for your help and the info. I'll check the new link you shared. – Ger Cas Aug 21 '19 at 15:21