【问题标题】:Has the user enabled the mobile data?用户是否启用了移动数据?
【发布时间】:2023-03-25 22:01:01
【问题描述】:

我想获取“使用移动网络”设置值(true 或 false)。有一种方法可以知道是否启用了 wifi,并且可以这样做:

WifiManager wm = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
int state = wm.getWifiState();
boolean pref = state == WifiManager.WIFI_STATE_ENABLED || state == WifiManager.WIFI_STATE_ENABLING;

但是我怎样才能对数据进行同样的检查呢?

【问题讨论】:

  • 我相信 [this][1] 链接可以解决您的问题。 [1]:stackoverflow.com/q/8243305/790568
  • @CRemons 添加您的评论作为答案,我会将此问题标记为已回答。

标签: android


【解决方案1】:

希望对你有帮助:)

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

Boolean isConnected = connect.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected();

【讨论】:

    【解决方案2】:

    你可以试试这个:

    public boolean getMobileDataEnabled() throws Exception {
        ConnectivityManager mcm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        Class ownerClass = mcm.getClass();
        Method method = ownerClass.getMethod("getMobileDataEnabled");
        return (Boolean)method.invoke(mcm);
    }
    

    并将权限添加到AndroidManifest.xml:

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

    【讨论】:

    • 在很多地方都看到了这个答案,对我来说效果很好。但是,出于某种原因,从 API 20 开始,调用失败了。这里建议的权限添加解决了这个问题!谢谢。
    【解决方案3】:

    您是否尝试过使用 TelephonyManager 类中的 getDataState()

    TelephonyManager tm = (TelephonyManager)Context.getSystemService (Context.TELEPHONY_SERVICE);
    int state = tm.getDataState();
    boolean pref = state == TelephonyManager.DATA_CONNECTED;
    

    这应该检查数据连接的状态。

    【讨论】:

    • 在发布此问题之前尝试过。 TelephonyManager.DATA_CONNECTED 显示设备是否连接到移动网络,因此当未连接时显示 DISCONNECTED,即使用户启用了移动数据。
    猜你喜欢
    • 2012-09-10
    • 1970-01-01
    • 2020-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多