2017-08-31 132 views
3

我知道如何使用以下方法在android中使用反射來開啓/關閉wifi熱點。如何在Android 8.0(Oreo)中以編程方式打開/關閉wifi熱點

private static boolean changeWifiHotspotState(Context context,boolean enable) { 
     try { 
      WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); 
      Method method = manager.getClass().getDeclaredMethod("setWifiApEnabled", WifiConfiguration.class, 
        Boolean.TYPE); 
      method.setAccessible(true); 
      WifiConfiguration configuration = enable ? getWifiApConfiguration(manager) : null; 
      boolean isSuccess = (Boolean) method.invoke(manager, configuration, enable); 
      return isSuccess; 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     return false; 
    } 

但上述方法不適用於Android 8.0(奧利奧)。

當我在Android 8.0中執行上面的方法時,我在logcat中獲得了下面的語句。

com.gck.dummy W/WifiManager: com.gck.dummy attempted call to setWifiApEnabled: enabled = true 

是否有任何其他的方式,在Android 8.0

+0

是否要關閉wifi或熱點 – MrAppMachine

+0

我想打開/關閉熱點...不是wifi ... – Chandrakanth

+0

是否有可能他們刪除了這種方式在Android O ?打開wifi熱點不是Android SDK的一部分。因此,這種方式使用反射是有點hacky – Rafa

回答

4

開/關熱點我終於得到了解決。 Android 8.0,他們提供了公開的api來打開/關閉熱點。 WifiManager

下面是代碼開啓熱點

@RequiresApi(api = Build.VERSION_CODES.O) 
    private void turnOnHotspot(){ 
     WifiManager manager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE); 

     manager.startLocalOnlyHotspot(new WifiManager.LocalOnlyHotspotCallback(){ 

      @Override 
      public void onStarted(WifiManager.LocalOnlyHotspotReservation reservation) { 
       super.onStarted(reservation); 
       Log.d(TAG, "Wifi Hotspot is on now"); 
      } 

      @Override 
      public void onStopped() { 
       super.onStopped(); 
       Log.d(TAG, "onStopped: "); 
      } 

      @Override 
      public void onFailed(int reason) { 
       super.onFailed(reason); 
       Log.d(TAG, "onFailed: "); 
      } 
     },new Handler()); 
    } 

onStarted(WifiManager.LocalOnlyHotspotReservation reservation)方法,如果熱點已開啓你打電話close()方法關閉熱點將被稱爲..使用WifiManager.LocalOnlyHotspotReservation參考。

更新: 要打開熱點,在Location(GPS)應在設備中啓用。否則,它會拋出SecurityException

+0

我有這個錯誤「java.lang.SecurityException:UID 10103沒有位置權限」,雖然我啓用設備中的位置並在清單文件中添加權限。你添加的權限是什麼? –

+0

@JeanCreuzédesChâtelliers根據文檔,應用程序應具有CHANGE_WIFI_STATE和ACCESS_COARSE_LOCATION權限。在打開熱點之前,GPS(位置)應該打開。確保上面提到的2個權限被授予。 – Chandrakanth

+0

哎呀,對不起。我忘記激活ACCESS_COARSE_LOCATION權限,儘管我將它添加到清單中。 –

相關問題