How to detect the event of network type change Android?

Deadly 提交于 2020-01-05 04:07:07

问题


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.


回答1:


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";
}


来源:https://stackoverflow.com/questions/57602868/how-to-show-network-type-changes-with-broadcaster-receiver-and-telephonymanager

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!