IT TIP

'모바일 네트워크 데이터'가 활성화되었는지 여부를 확인하는 방법 (WiFi로 연결된 경우에도)?

itqueen 2020. 11. 22. 21:00
반응형

'모바일 네트워크 데이터'가 활성화되었는지 여부를 확인하는 방법 (WiFi로 연결된 경우에도)?


원격 쿼리에서 연결 상태 보고서를 가져 오는 데 사용할 수있는 앱이 있습니다.

WiFi가 연결되어 있는지, 모바일 네트워크를 통해 데이터 액세스가 활성화되어 있는지 알고 싶습니다.

WiFi가 범위를 벗어나면 모바일 네트워크를 신뢰할 수 있는지 알고 싶습니다.

문제는 WiFi로 연결되면 활성화 된 데이터가 항상 true로 반환되고 WiFi로 연결되지 않은 경우에만 모바일 네트워크를 제대로 쿼리 할 수 ​​있다는 것입니다.

내가 본 모든 대답은 현재 연결이 무엇인지 확인하기 위해 폴링을 제안하지만 현재 WiFi로 연결되어 있더라도 모바일 네트워크를 사용할 수 있는지 알고 싶습니다.

연결되어 있는지 확인하기 위해 폴링하지 않고 모바일 네트워크 데이터가 활성화되었는지 여부를 알려주는 방법이 있습니까?

편집하다

따라서 WiFi로 연결되었을 때 설정으로 이동하여 '데이터 사용'을 선택 취소 한 다음 내 앱에서 다음을 수행합니다.

 boolean mob_avail = 
 conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isAvailable();

mob_avail이 'true'로 반환되지만 모바일 네트워크 데이터를 비활성화 했으므로 'false'가 될 것으로 예상합니다.

WiFi를 끄면 모바일 네트워크 데이터를 비활성화했기 때문에 연결이 (올바르게) 없습니다.

그렇다면 WiFi로 연결되었을 때 모바일 네트워크 데이터가 활성화되어 있는지 어떻게 확인합니까?

최신 정보

ss1271의 의견에서 제안한대로 getAllNetworkInfo ()를 살펴 보았습니다.

다음 3 가지 조건에서 모바일 네트워크에 대해 반환 된 정보를 출력했습니다.

WiFi 끄기-모바일 데이터 켜기

WiFi 켜기-모바일 데이터 끄기

WiFi 켜기-모바일 데이터 켜기

다음과 같은 결과를 얻었습니다.

WiFi 끄기 :

mobile [HSUPA], 상태 : CONNECTED / CONNECTED, 이유 : 알 수 없음, 추가 : 인터넷, 로밍 : false, 장애 조치 : false, isAvailable : true, featureId : -1, userDefault : false

WiFi 켜기 / 모바일 끄기

NetworkInfo : 유형 : 모바일 [HSUPA], 상태 : DISCONNECTED / DISCONNECTED, 이유 : connectionDisabled, 추가 : (없음), 로밍 : false, 장애 조치 : false, isAvailable : true, featureId : -1, userDefault : false

WiFi 켜짐 / 모바일 켜짐

NetworkInfo : 유형 : 모바일 [HSPA], 상태 : DISCONNECTED / DISCONNECTED, 이유 : connectionDisabled, 추가 : (없음), 로밍 : false, 장애 조치 : false, isAvailable : true, featureId : -1, userDefault : false

보시다시피 isAvailable은 매번 true를 반환했으며 상태는 WiFi가 영향을 받았을 때만 Disconnected로 표시되었습니다.

설명

나는 NOT 내 휴대 전화는 현재 모바일 네트워크로 연결되어 있는지를 찾고 있습니다. 나는 AM 모바일 네트워크를 통해 사용자가 사용 가능 여부 / 비활성화 데이터 액세스를 설정하려고합니다. 설정-> 무선 및 네트워크 설정-> 모바일 네트워크 설정-> 데이터 사용으로 이동하여이 기능을 켜고 끌 수 있습니다.


다음 코드는 현재 모바일 데이터 연결이 활성화되어 있는지 여부 또는 Wi-Fi가 활성화 / 활성화되었는지 여부에 관계없이 "모바일 데이터"가 활성화되었는지 여부를 알려줍니다. 이 코드는 Android 2.3 (Gingerbread) 이상에서만 작동합니다. 실제로이 코드는 이전 버전의 Android에서도 작동합니다 ;-)

    boolean mobileDataEnabled = false; // Assume disabled
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    try {
        Class cmClass = Class.forName(cm.getClass().getName());
        Method method = cmClass.getDeclaredMethod("getMobileDataEnabled");
        method.setAccessible(true); // Make the method callable
        // get the setting for "mobile data"
        mobileDataEnabled = (Boolean)method.invoke(cm);
    } catch (Exception e) {
        // Some problem accessible private API
        // TODO do whatever error handling you want here
    }

참고 : android.permission.ACCESS_NETWORK_STATE이 코드를 사용하려면 권한 이 있어야합니다.


Allesio의 답변을 업그레이드했습니다. Settings.Secure의 mobile_data int는 4.2.2 이후 Settings.Global로 이동했습니다.

Wi-Fi가 활성화되고 연결되어 있어도 모바일 네트워크가 활성화되어 있는지 알고 싶다면이 코드를 사용해보십시오.

SIM 카드를 사용할 수 있는지 확인하도록 업데이트되었습니다. murat를 지적 해 주셔서 감사합니다.

boolean mobileYN = false;

TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (tm.getSimState() == TelephonyManager.SIM_STATE_READY) {
    if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1)
    {
        mobileYN = Settings.Global.getInt(context.getContentResolver(), "mobile_data", 1) == 1;
    }
    else{
        mobileYN = Settings.Secure.getInt(context.getContentResolver(), "mobile_data", 1) == 1;
    }
}

한 가지 방법은 사용자가 설정에서 활성화 된 모바일 데이터를 가지고 있는지 확인하는 것입니다.이 데이터는 Wi-Fi가 꺼질 때 가장 많이 사용됩니다. 이것은 작동 (테스트)되었으며 API에서 숨겨진 값을 사용하지만 리플렉션을 사용하지 않습니다.

boolean mobileDataAllowed = Settings.Secure.getInt(getContentResolver(), "mobile_data", 1) == 1;

API에 따라 @ user1444325가 지적한대로 Settings.Secure 대신 Settings.Global을 확인해야합니다.

출처 : 사용자 설정 '데이터 사용'을 확인하기위한 Android API 호출


@sNash의 기능은 훌륭하게 작동합니다. 그러나 몇몇 장치에서는 데이터가 비활성화되어 있어도 true를 반환한다는 것을 알았습니다. 그래서 Android API에있는 대체 솔루션을 찾았습니다.

TelephonyManager의 getDataState () 메소드는 매우 유용합니다.

위의 기능을 사용하여 @snash의 기능을 업데이트했습니다. 아래 함수는 셀룰러 데이터가 비활성화되면 false를 반환하고 그렇지 않으면 true를 반환합니다.

private boolean checkMobileDataIsEnabled(Context context){
        boolean mobileYN = false;

        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        if (tm.getSimState() == TelephonyManager.SIM_STATE_READY) {
            TelephonyManager tel = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
//          if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1)
//          {
//              mobileYN = Settings.Global.getInt(context.getContentResolver(), "mobile_data", 0) == 1;
//          }
//          else{
//              mobileYN = Settings.Secure.getInt(context.getContentResolver(), "mobile_data", 0) == 1;
//          }
            int dataState = tel.getDataState();
            Log.v(TAG,"tel.getDataState() : "+ dataState);
            if(dataState != TelephonyManager.DATA_DISCONNECTED){
                mobileYN = true;
            }

        }

        return mobileYN;
    }

다음과 같이 시도 할 수 있습니다.

ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

//mobile
State mobile = conMan.getNetworkInfo(0).getState();

//wifi
State wifi = conMan.getNetworkInfo(1).getState();


if (mobile == NetworkInfo.State.CONNECTED || mobile == NetworkInfo.State.CONNECTING) 
{
    //mobile
}
else if (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING) 
{
    //wifi
}

실제로 연결되어 있다면 관심이 있다면

NetworkInfo.State.CONNECTED 

대신에

NetworkInfo.State.CONNECTED || NetworkInfo.State.CONNECTING

이 문제에 대한 xamarin 솔루션은 다음과 같습니다.

    public static bool IsMobileDataEnabled()
    {
        bool result = false;

        try
        {
            Context context = //get your context here or pass it as a param

            if (Build.VERSION.SdkInt >= BuildVersionCodes.JellyBeanMr1)
            {
                //Settings comes from the namespace Android.Provider
                result = Settings.Global.GetInt(context.ContentResolver, "mobile_data", 1) == 1;
            }
            else
            {
                result = Settings.Secure.GetInt(context.ContentResolver, "mobile_data", 1) == 1;
            }
        }
        catch (Exception ex)
        {
            //handle exception
        }

        return result;
    }

추신 :이 코드에 대한 모든 권한이 있는지 확인하십시오.


ConnectivityManager를 사용해야하며 NetworkInfo 세부 정보는 여기 에서 찾을 수 있습니다.


NetworkInfo 클래스를 사용 하고 isConnected가 작동해야 한다고 생각 합니다.

ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

return info != NULL || info.isConnected();

그리고 아마도 모바일 데이터가 연결되어 있는지 확인하십시오. 테스트 할 때까지 확신 할 수 없습니다. 내일까지 할 수 없습니다.

TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

if(tm .getDataState() == tm .DATA_CONNECTED)
   return true;

To identify which SIM or slot is making data connection active in mobile, we need to register action android:name="android.net.conn.CONNECTIVITY_CHANGE"  with permission   
uses-permission android:name="android.permission.CONNECTIVITY_INTERNAL" &    uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"

    public void onReceive(Context context, Intent intent) 
 if (android.net.conn.CONNECTIVITY_CHANGE.equalsIgnoreCase(intent
                .getAction())) {

IBinder b = ServiceManager.getService(Context.CONNECTIVITY_SERVICE);
 IConnectivityManager service =  IConnectivityManager.Stub.asInterface(b);
NetworkState[] states = service.getAllNetworkState();

 for (NetworkState state : states) {

                if (state.networkInfo.getType() == ConnectivityManager.TYPE_MOBILE
                        && state.networkInfo.isConnected()) {

 TelephonyManager mTelephonyManager = (TelephonyManager) context
                        .getSystemService(Context.TELEPHONY_SERVICE);
         int slotList =  { 0, 1 };
          int[] subId = SubscriptionManager.getSubId(slotList[0]);
          if(mTelephonyManager.getDataEnabled(subId[0])) {
             // this means data connection is active for SIM1 similary you 
             //can chekc for SIM2 by slotList[1]
               .................
          }
}

}

    ConnectivityManager cm = (ConnectivityManager) activity
                        .getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo info = cm.getActiveNetworkInfo();
                String networkType = "";
    if (info.getType() == ConnectivityManager.TYPE_WIFI) {
                    networkType = "WIFI";
                } 
else if (info.getType() == ConnectivityManager.TYPE_MOBILE) {

                    networkType = "mobile";
    }

안드로이드 문서 https://developer.android.com/training/monitoring-device-state/connectivity-monitoring#java 에 따르면

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

NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
                      activeNetwork.isConnectedOrConnecting();

TelephonyManager 사용

TelephonyManager tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);

tm.isDataEnabled()

안드로이드 문서에 따르면

https://developer.android.com/reference/android/telephony/TelephonyManager.html#isDataEnabled ()


다음은 다른 두 가지 답변의 간단한 해결책입니다.

        TelephonyManager tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            return tm.isDataEnabled();

        } else {
            return tm.getSimState() == TelephonyManager.SIM_STATE_READY && tm.getDataState() != TelephonyManager.DATA_DISCONNECTED;
        }

데이터 연결이 켜져 있는지 확인하는 해결 방법이 있습니다. 그러나 모든 장치에서 작동하는지 확실하지 않습니다. 당신은 그것을 확인해야합니다. (Android 하나의 장치에서 작동했습니다)

long data = TrafficStats.getMobileRxBytes();
if(data > 0){
    //Data is On
}
else{
    //Data is Off
}

If you are not aware about this method, it returns the total of bytes recieved through mobile network since the device boot up. When you turn off the mobile data connection, it will return Zero (0). When you turn on, it will return the total of bytes again. But you need to aware that there is a problem which can happen when using this workaround.

  • This method will also return 0 when you reboot the phone because the calculation starts from 0 bytes.

private boolean haveMobileNetworkConnection() {
        boolean haveConnectedMobile = false;

        ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] netInfo = cm.getAllNetworkInfo();

        for (NetworkInfo ni : netInfo) {

            if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
                if (ni.isConnected())
                    haveConnectedMobile = true;
        }
        return haveConnectedMobile;
    }

Note: you will need to have permission android.permission.ACCESS_NETWORK_STATE to be able to use this code


There is simple API that seems to be working

TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
return tm.isDataEnabled();

참고URL : https://stackoverflow.com/questions/12806709/how-to-tell-if-mobile-network-data-is-enabled-or-disabled-even-when-connected

반응형