如何检测Android网络类型更改事件? [英] How to detect the event of network type change Android?

查看:79
本文介绍了如何检测Android网络类型更改事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码可用于在启动时检测当前的网络类型,但是我希望该应用能够检测到网络类型发生变化的时间,例如从3G变为LTE,从LTE变为3G,从3G变为2G等./p>

我在此处找到了广播接收器的类NetworkStateReceiver,但未显示当我更换网络时,一切都会改变.

有人可以帮助我,如何在启动应用程序时不仅显示网络类型,还显示/检测网络类型更改的event?

我正在尝试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");
            }
        }
    }
}

我的清单是这样的:

    <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.

更新2

我一直在寻找一种方法来成功,当电话更改网络类型(即从2G更改为3G,从3G更改为LTE等)时触发事件.

我在此处当电话通过Broacaster ReceiverConnectivityManager.TYPE_WIFITYPE_MOBILE并发送Toast从电话从无互联网连接"更改为"Wifi"或移动数据"时,触发事件的效果很好要显示的消息,以提醒您有关更改.

我了解到,当ConnectivityManagerWIFI更改为MOBILE或反之亦然时,ConnectivityManager有助于触发事件,但是当手机处于状态TYPE_MOBILE且2G,3G之间的网络类型发生变化时或LTE,则不会为这些更改生成触发器.我什至添加了TelephonyManager来处理不同的NETWORK_TYPEs,但它不起作用.

在发生变化的那一刻,当电话在2G,3G或LTE之间转换时,触发事件需要怎么做?

我已经合并了当前答案,但不能达到我的目标.

我正在尝试使用Android 6.

到目前为止,我拥有的Util类是这样:

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

感谢您的帮助.

解决方案

根据您的问题,我了解到您需要知道手机的网络状态是什么.在情况5 中,由于wifi和移动数据均已打开,因此部分正确.因此,当您打开移动数据时,调用包含TelephonyManager的方法.您可以获取移动数据的当前状态.下面的方法是获取网络状态的示例.

注意,当您收到启用移动数据的回调时,调用此方法

.

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

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.

解决方案

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

这篇关于如何检测Android网络类型更改事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆