2016-04-12 10 views
0

私のアプリは、モバイルデータを介して接続する必要がある場合があります。私は特定のアプリがモバイルデータだけを使用できるようにするアプリがあることを知っています。私はアプリでWi-Fiをどのようにオフにできるのか知っています。しかし、私のアプリにモバイル接続を使用するように指示する方法はありますか?AndroidアプリにWi-Fiをオフにせずにモバイルデータを使用させる

答えて

0

私はルート付き電話機でのみ機能する回避策を使用します。

setMobileDataEnabledメソッドがConnectivityManagerから削除されましたが、この機能のためにgetDataEnabledとsetDataEnabledの2つのメソッドがTelephonyManagerに追加されました。

public void setMobileDataState(boolean mobileDataEnabled) 
{ 
    try 
    { 
     TelephonyManager telephonyService = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); 

     Method setMobileDataEnabledMethod = telephonyService.getClass().getDeclaredMethod("setDataEnabled", boolean.class); 

     if (null != setMobileDataEnabledMethod) 
     { 
      setMobileDataEnabledMethod.invoke(telephonyService, mobileDataEnabled); 
     } 
    } 
    catch (Exception ex) 
    { 
     Log.e(TAG, "Error setting mobile data state", ex); 
    } 
} 

public boolean getMobileDataState() 
{ 
    try 
    { 
     TelephonyManager telephonyService = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); 

     Method getMobileDataEnabledMethod = telephonyService.getClass().getDeclaredMethod("getDataEnabled"); 

     if (null != getMobileDataEnabledMethod) 
     { 
      boolean mobileDataEnabled = (Boolean) getMobileDataEnabledMethod.invoke(telephonyService); 

      return mobileDataEnabled; 
     } 
    } 
    catch (Exception ex) 
    { 
     Log.e(TAG, "Error getting mobile data state", ex); 
    } 

    return false; 
} 

しかし、あなたはそうしないと、SecurityExceptionを取得するマニフェストファイルにこの権限(MODIFY_PHONE_STATE)を追加する必要があります。

0

アプリごとに通信チャネルを明示的に強制することはできません(ConnectivityManager.setNetworkPreference(...)で優先モードの使用をリクエストできますが、強制的に使用することはできません)。

// and to be sure: 
    ConnectivityManager.setNetworkPreference(ConnectivityManager.TYPE_MOBILE); 
+0

何が管理者に必要ですか?あなたの最初の行は何もしませんか? – Ginso

+0

はいコードを編集しましたが、その時点でWi-Fiをオフにする必要があります – Pitty

関連する問題