2016-04-12 50 views
0

我的應用有時需要通過移動數據連接才能工作。我知道有些應用程序可以讓某個應用程序只使用移動數據,我知道如何使用我的應用程序關閉無線網絡。但是,有沒有辦法告訴我的應用程序從現在開始使用移動連接,並在另一個點解除這個限制?強制安卓應用使用移動數據而無需關閉WiFi

回答

0

我使用了一種只適用於固定電話的解決方法。

已將setMobileDataEnabled方法從ConnectivityManager中刪除,但兩種方法getDataEnabled和setDataEnabled已添加到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; 
} 

但你需要這個權限(MODIFY_PHONE_STATE)添加到清單文件,否則你會得到一個SecurityException。

0

您不能在每個應用程序的基礎上明確強制通信通道(您可以通過ConnectivityManager.setNetworkPreference(...)請求使用首選模式,但這不是「強制」)。

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

你需要經理做什麼?你的第一行什麼都沒做,是嗎? – Ginso

+0

是的,我編輯的代碼,但在那個時候你必須關閉WiFi – Pitty

相關問題