Esiste una API per attivare/disattivare WiFi HotSpot su Android a livello di programmazione?
Quali metodi dovrei chiamare per accenderlo/spegnerlo?
AGGIORNARE:C'è questa opzione per avere l'HotSpot abilitato e basta attivare/disattivare il WiFi, ma questa non è una buona soluzione per me.
Usa la classe qui sotto per cambiare/controllare l'impostazione Wifi hotspot
:
import Android.content.*;
import Android.net.wifi.*;
import Java.lang.reflect.*;
public class ApManager {
//check whether wifi hotspot on or off
public static boolean isApOn(Context context) {
WifiManager wifimanager = (WifiManager) context.getSystemService(context.WIFI_SERVICE);
try {
Method method = wifimanager.getClass().getDeclaredMethod("isWifiApEnabled");
method.setAccessible(true);
return (Boolean) method.invoke(wifimanager);
}
catch (Throwable ignored) {}
return false;
}
// toggle wifi hotspot on or off
public static boolean configApState(Context context) {
WifiManager wifimanager = (WifiManager) context.getSystemService(context.WIFI_SERVICE);
WifiConfiguration wificonfiguration = null;
try {
// if WiFi is on, turn it off
if(isApOn(context)) {
wifimanager.setWifiEnabled(false);
}
Method method = wifimanager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
method.invoke(wifimanager, wificonfiguration, !isApOn(context));
return true;
}
catch (Exception e) {
e.printStackTrace();
}
return false;
}
} // end of class
Devi aggiungere le autorizzazioni di seguito al tuo AndroidMainfest:
<uses-permission Android:name="Android.permission.CHANGE_NETWORK_STATE" />
<uses-permission Android:name="Android.permission.CHANGE_WIFI_STATE" />
<uses-permission Android:name="Android.permission.ACCESS_WIFI_STATE" />
Utilizzare questa classe autonoma di ApManager da qualsiasi luogo come segue:
ApManager.isApOn(YourActivity.this); // check Ap state :boolean
ApManager.configApState(YourActivity.this); // change Ap state :boolean
Spero che questo aiuti qualcuno
Non ci sono metodi nell'SDK Android relativi alla funzione hotspot WiFi - scusa!
È possibile utilizzare il codice seguente per abilitare, disabilitare e interrogare lo stato diretto wifi in modo programmatico.
package com.kusmezer.androidhelper.networking;
import Java.lang.reflect.Method;
import com.google.common.base.Preconditions;
import Android.content.Context;
import Android.net.wifi.WifiConfiguration;
import Android.net.wifi.WifiManager;
import Android.util.Log;
public final class WifiApManager {
private static final int WIFI_AP_STATE_FAILED = 4;
private final WifiManager mWifiManager;
private final String TAG = "Wifi Access Manager";
private Method wifiControlMethod;
private Method wifiApConfigurationMethod;
private Method wifiApState;
public WifiApManager(Context context) throws SecurityException, NoSuchMethodException {
context = Preconditions.checkNotNull(context);
mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
wifiControlMethod = mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class,boolean.class);
wifiApConfigurationMethod = mWifiManager.getClass().getMethod("getWifiApConfiguration",null);
wifiApState = mWifiManager.getClass().getMethod("getWifiApState");
}
public boolean setWifiApState(WifiConfiguration config, boolean enabled) {
config = Preconditions.checkNotNull(config);
try {
if (enabled) {
mWifiManager.setWifiEnabled(!enabled);
}
return (Boolean) wifiControlMethod.invoke(mWifiManager, config, enabled);
} catch (Exception e) {
Log.e(TAG, "", e);
return false;
}
}
public WifiConfiguration getWifiApConfiguration()
{
try{
return (WifiConfiguration)wifiApConfigurationMethod.invoke(mWifiManager, null);
}
catch(Exception e)
{
return null;
}
}
public int getWifiApState() {
try {
return (Integer)wifiApState.invoke(mWifiManager);
} catch (Exception e) {
Log.e(TAG, "", e);
return WIFI_AP_STATE_FAILED;
}
}
}
Per Android 8.0, c'è una nuova API per gestire gli hotspot. Per quanto ne so, il vecchio modo di usare la riflessione non funziona più . Si prega di fare riferimento a:
void startLocalOnlyHotspot (WifiManager.LocalOnlyHotspotCallback callback,
Handler handler)
Richiedi un hotspot solo locale che un'applicazione può utilizzare per comunicare tra i dispositivi co-localizzati connessi all'hotspot WiFi creato. La rete creata con questo metodo non avrà accesso a Internet.
Stack Overflow
Come attivare/disattivare l'hotspot Wi-Fi a livello di programmazione in Android 8.0 (Oreo)
il metodo onStarted (WifiManager.LocalOnlyHotspotReservation) verrà chiamato se l'hotspot è attivato. Usando il riferimento WifiManager.LocalOnlyHotspotReservation chiami il metodo close () per disattivare l'hotspot.
La tua migliore scommessa riguarderà la classe WifiManager. In particolare la funzione setWifiEnabled(bool)
.
Vedere la documentazione all'indirizzo: http://developer.Android.com/reference/Android/net/wifi/WifiManager.html#setWifiEnabled(boolean)
Un tutorial su come usarlo (comprese le autorizzazioni necessarie) può essere trovato qui: http://www.tutorialforandroid.com/2009/10/turn-off-turn-on-wifi-in- Android-using.html
Si applica a Oreo + solo ...
Ho creato un'app con codice qui su GitHub che utilizza reflection e DexMaker per 'ottenere' la funzionalità di tethering di Oreo, che ora è in ConnectionManager
, piuttosto che WifiManager
.
La roba in WifiManager
è valida solo per una rete wifi chiusa (che ha spiegato il bit chiuso nei nomi delle classi!).
Altre spiegazioni https://stackoverflow.com/a/49356255/772333 .
Questo funziona bene per me:
WifiConfiguration apConfig = null;
Method method = wifimanager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, Boolean.TYPE);
method.invoke(wifimanager, apConfig, true);
** Per Oreo & PIE ** ho trovato sotto il modo attraverso questo
private WifiManager.LocalOnlyHotspotReservation mReservation;
private boolean isHotspotEnabled = false;
private final int REQUEST_ENABLE_LOCATION_SYSTEM_SETTINGS = 101;
private boolean isLocationPermissionEnable() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_COARSE_LOCATION}, 2);
return false;
}
return true;
}
@RequiresApi(api = Build.VERSION_CODES.O)
private void turnOnHotspot() {
if (!isLocationPermissionEnable()) {
return;
}
WifiManager manager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
if (manager != null) {
// Don't start when it started (existed)
manager.startLocalOnlyHotspot(new WifiManager.LocalOnlyHotspotCallback() {
@Override
public void onStarted(WifiManager.LocalOnlyHotspotReservation reservation) {
super.onStarted(reservation);
//Log.d(TAG, "Wifi Hotspot is on now");
mReservation = reservation;
isHotspotEnabled = true;
}
@Override
public void onStopped() {
super.onStopped();
//Log.d(TAG, "onStopped: ");
isHotspotEnabled = false;
}
@Override
public void onFailed(int reason) {
super.onFailed(reason);
//Log.d(TAG, "onFailed: ");
isHotspotEnabled = false;
}
}, new Handler());
}
}
@RequiresApi(api = Build.VERSION_CODES.O)
private void turnOffHotspot() {
if (!isLocationPermissionEnable()) {
return;
}
if (mReservation != null) {
mReservation.close();
isHotspotEnabled = false;
}
}
@RequiresApi(api = Build.VERSION_CODES.O)
private void toggleHotspot() {
if (!isHotspotEnabled) {
turnOnHotspot();
} else {
turnOffHotspot();
}
}
@RequiresApi(api = Build.VERSION_CODES.O)
private void enableLocationSettings() {
LocationRequest mLocationRequest = new LocationRequest();
/*mLocationRequest.setInterval(10);
mLocationRequest.setSmallestDisplacement(10);
mLocationRequest.setFastestInterval(10);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);*/
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(mLocationRequest)
.setAlwaysShow(false); // Show dialog
Task<LocationSettingsResponse> task= LocationServices.getSettingsClient(this).checkLocationSettings(builder.build());
task.addOnCompleteListener(task1 -> {
try {
LocationSettingsResponse response = task1.getResult(ApiException.class);
// All location settings are satisfied. The client can initialize location
// requests here.
toggleHotspot();
} catch (ApiException exception) {
switch (exception.getStatusCode()) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied. But could be fixed by showing the
// user a dialog.
try {
// Cast to a resolvable exception.
ResolvableApiException resolvable = (ResolvableApiException) exception;
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
resolvable.startResolutionForResult(HotspotActivity.this, REQUEST_ENABLE_LOCATION_SYSTEM_SETTINGS);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
} catch (ClassCastException e) {
// Ignore, should be an impossible error.
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied. However, we have no way to fix the
// settings so we won't show the dialog.
break;
}
}
});
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
final LocationSettingsStates states = LocationSettingsStates.fromIntent(data);
switch (requestCode) {
case REQUEST_ENABLE_LOCATION_SYSTEM_SETTINGS:
switch (resultCode) {
case Activity.RESULT_OK:
// All required changes were successfully made
toggleHotspot();
Toast.makeText(HotspotActivity.this,states.isLocationPresent()+"",Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
// The user was asked to change settings, but chose not to
Toast.makeText(HotspotActivity.this,"Canceled",Toast.LENGTH_SHORT).show();
break;
default:
break;
}
break;
}
}
Useage
btnHotspot.setOnClickListenr(view -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Step 1: Enable the location settings use Google Location Service
// Step 2: https://stackoverflow.com/questions/29801368/how-to-show-enable-location-dialog-like-google-maps/50796199#50796199
// Step 3: If OK then check the location permission and enable hotspot
// Step 4: https://stackoverflow.com/questions/46843271/how-to-turn-off-wifi-hotspot-programmatically-in-Android-8-0-oreo-setwifiapen
enableLocationSettings();
return;
}
}
<uses-permission Android:name="Android.permission.ACCESS_COARSE_LOCATION" />
implementation 'com.google.Android.gms:play-services-location:15.0.1'
Possiamo programmaticamente accendere e spegnere
setWifiApDisable.invoke(connectivityManager, TETHERING_WIFI);//Have to disable to enable
setwifiApEnabled.invoke(connectivityManager, TETHERING_WIFI, false, mSystemCallback,null);
Usando la classe di callback, per attivare automaticamente l'hotspot in torta (9.0) è necessario disattivare programmaticamente e l'accensione.