Android Question turning on Hotspot

mhk1368

Member
hi
Does anyone have an example of turning on the phone's hotspot and sharing the mobile internet (Android 11)?
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
 
Upvote 0

mhk1368

Member
hi and thanks erel
I saw this article, the problem is that the name and password must be fixed and it should not change every time, it should work like the phone's hotspot button, just turning it on is enough for me. It means that the hotspot and internet of the phone should be turned on and the rest should be the same as the previous settings.
 
Upvote 0

mhk1368

Member
I found this code for java but I don't know how to use it for b4a can anyone help?
link: https://codegrepr.com/question/android-turn-on-off-wifi-hotspot-programmatically/

**For Oreo & PIE ** I found below way through this:
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'

We can programmatically turn on and off:
setWifiApDisable.invoke(connectivityManager, TETHERING_WIFI);//Have to disable to enable
setwifiApEnabled.invoke(connectivityManager, TETHERING_WIFI, false, mSystemCallback,null);
 
Upvote 0

mhk1368

Member
I found this code, what is its format in b4a?

work on other APP:
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Build;
import c.i.b.g;
import c.i.b.h;
import com.ertunga.wifihotspot.R;
import com.ertunga.wifihotspot.oreosupport.HotSpotIntentService;
import d.b.c.o.b;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Objects;

public class c implements InvocationHandler {
    public final /* synthetic */ b a;

    public c(d dVar, b bVar) {
        this.a = bVar;
    }

    public Object invoke(Object obj, Method method, Object[] objArr) {
        String name = method.getName();
        name.hashCode();
        if (name.equals("onTetheringStarted")) {
            HotSpotIntentService hotSpotIntentService = ((a) this.a).a;
            int i2 = HotSpotIntentService.s;
            Objects.requireNonNull(hotSpotIntentService);
            int i3 = Build.VERSION.SDK_INT;
            if (i3 >= 26) {
                NotificationManager notificationManager = (NotificationManager) hotSpotIntentService.getSystemService("notification");
                if (notificationManager.getNotificationChannel("control_app") == null) {
                    NotificationChannel notificationChannel = new NotificationChannel("control_app", hotSpotIntentService.getString(R.string.app_name), 2);
                    notificationChannel.enableLights(false);
                    notificationChannel.enableVibration(false);
                    notificationManager.createNotificationChannel(notificationChannel);
                }
            }
            Intent intent = new Intent(hotSpotIntentService, HotSpotIntentService.class);
            intent.setAction(hotSpotIntentService.getString(R.string.intent_action_turnoff));
            PendingIntent service = i3 >= 31 ? PendingIntent.getService(hotSpotIntentService, 0, intent, 33554432) : PendingIntent.getService(hotSpotIntentService, 0, intent, 0);
            h hVar = new h(hotSpotIntentService, "control_app");
            hVar.e(2, true);
            hVar.d("WifiHotSpot is On");
            hVar.f891b.add(new g(R.drawable.icon_wifi, "TURN OFF HOTSPOT", service));
            hVar.f897h = -1;
            hVar.f899j = "service";
            hVar.n.icon = R.drawable.hotspot;
            hotSpotIntentService.startForeground(1338, hVar.a());
            return null;
        } else if (!name.equals("onTetheringFailed")) {
            Map<b.C0064b<?>, Class<?>> map = b.f2178h;
            try {
                obj.getClass().getMethod(b.c(method), method.getParameterTypes()).invoke(obj, objArr);
                return null;
            } catch (InvocationTargetException e2) {
                throw e2.getCause();
            }
        } else {
            Objects.requireNonNull((a) this.a);
            return null;
        }
    }
}
 
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…