2013-12-10 70 views
1

我在檢查WIFI_SLEEP_POLICY是否設置爲WIFI_SLEEP_POLICY_NEVER。它在某些設備和仿真器中運行良好,但不適用於其他設備。例如,它可以在Nexus S仿真程序上運行,其中API 10但不在Nexus One仿真程序中,API 8。當它不工作,我得到這個消息無法在某些設備上檢查WIFI_SLEEP_POLICY

12-10 15:57:19.625: W/System.err(477): android.provider.Settings$SettingNotFoundException: wifi_sleep_policy 
12-10 15:57:19.625: W/System.err(477): at android.provider.Settings$System.getInt(Settings.java:807) 

下面的代碼

WifiManager wm = (WifiManager) m_activity.getSystemService(Context.WIFI_SERVICE); 
    ContentResolver cr = m_activity.getContentResolver(); 
    int policyNever = android.provider.Settings.System.WIFI_SLEEP_POLICY_NEVER; 
    String WIFI_SLEEP_POLICY = android.provider.Settings.System.WIFI_SLEEP_POLICY; 
     try { 
     if(android.provider.Settings.System.getInt(cr, WIFI_SLEEP_POLICY) != policyNever) 
     { 
      if (Build.VERSION.SDK_INT>=17){ 
       showWifiSleepWarning(restartAction); 
       return false; 
      } 
      else 
       android.provider.Settings.System.putInt(cr, WIFI_SLEEP_POLICY, policyNever); 
     } 
    } catch (SettingNotFoundException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

回答

0

有趣的是,雖然getInt返回一個錯誤,putInt工作正常。所以如果我試圖在沒有先檢查它的狀態的情況下改變它,它就可以工作。當然,對於API 17及以上版本而言(與文檔相同),新代碼將處理這兩種情況。

 WifiManager wm = (WifiManager) m_activity.getSystemService(Context.WIFI_SERVICE); 
     if(!wm.isWifiEnabled()) 
     { 
      return true; 
     } 
     ContentResolver cr = m_activity.getContentResolver(); 
     int policyNever = android.provider.Settings.System.WIFI_SLEEP_POLICY_NEVER; 
     try 
     { 
      android.provider.Settings.System.putInt(cr, WIFI_SLEEP_POLICY, policyNever); 
     } 
     catch(Exception e) 
     { 
      e.printStackTrace(); 
     } 
     try 
     { 
      if(android.provider.Settings.System.getInt(cr, WIFI_SLEEP_POLICY) != policyNever) 
      { 
       //if (Build.VERSION.SDK_INT>=17) 
       showWifiSleepWarning(restartAction); 
       return false; 
      } 
     } 
     catch (Exception e) 
     { 
      e.printStackTrace(); 
     } 
相關問題