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;
}
}
使用年龄
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'
setWifiApDisable.invoke(connectivityManager, TETHERING_WIFI);//Have to disable to enable
setwifiApEnabled.invoke(connectivityManager, TETHERING_WIFI, false, mSystemCallback,null);
APManager apManager = APManager.getApManager(this);
apManager.turnOnHotspot(this, new APManager.OnSuccessListener() {
@Override
public void onSuccess(String ssid, String password) {
//write your logic
}
}, new APManager.OnFailureListener() {
@Override
public void onFailure(int failureCode, @Nullable Exception e) {
//handle error like give access to location permission,write system setting permission,
//disconnect wifi,turn off already created hotspot,enable GPS provider
//or use DefaultFailureListener class to handle automatically
}
});