LoginSignup
2
2

More than 5 years have passed since last update.

[Android]データ接続設定を確認する

Posted at

モバイルデータ接続

ネットワーク状況を確認する時に、ネットワークタイプや機内モードかどうかは確認できますが、モバイル通信の時に、データ接続の設定が有効かどうかはAndroidのAPIでは取得できません。

しかし、@hideな隠しAPIで用意されているので必要な場合はリフレクションで取得することができます。
ユーザがオフにしてしまっている時にエラーメッセージを出し分けたい場合は、取得することができるでしょう。

ConnectivityManager.getMobileDataEnabled

ConnectivityManagerにはgetMobileDataEnabledという隠しメソッドがあるので、実行して取得できます。

How to tell if 'Mobile Network Data' is enabled or disabled (even when connected by WiFi)?

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.Manifest.permission.ACCESS_NETWORK_STATEのpermissionが必要です。

TelephonyManager

Android5.0からはConnectionManager.getMobileDataEnabled関数はDeprecatedになりました。

Deprecated:
Talk to TelephonyManager directly

まだ使えるようですが、TelephonyManagerに記述が移動したようです。
5.0からはそちらを呼ぶことも可能です。

        TelephonyManager tm = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        try {
            Class cmClass = Class.forName(tm.getClass().getName());
            Method method = cmClass.getDeclaredMethod("getDataEnabled");
            method.setAccessible(true);
            // Make the method callable get the setting for "mobile data"
            return (Boolean) method.invoke(tm);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return false;

ちょっと権限は調べられていませんが、同じかと思います。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2