• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Local Hotspot - Personalized and Fixed SSID

Hello everyone. I am quite new in the Apps development. I have been reading so many Q&A, forums, and post from so many people around. I have a question, and I hope someone of you could kindly give me support to clarify my doubts. I would like to enable a local hotspot on a tablet (Huawei Mediapad T5 with Android 8 - Oreo). I am developing an App with different functionalities, but I realized I need to switch between my Wireless connection and to enable my Local Hotspot (One it is already saved and configured on my tablet). And I have managed to do the switch in between the networks. The big problem comes with the SSID. If I enable manually my Local Hotspot, it connects automatically with my other device (Arduino MKR 1010), but if I do it programmatically, the Hotspot that I enable, changes every single time the SSID. Is there any way set a fixed SSID with this methodology? I read in some posts that this is already hardcoded and it is not possible to do as I wish. I hope you can help me to understand it better, clarify or to find a solution. Thank you so much in advance. I post my activity code, and the Logcat with two attempts. :)
Java:
public class WiFi extends AppCompatActivity {

    private Button on_off_wifi;
    private Button discover_wifi;
    public TextView connectionState_tv;
    private ListView peerListView;

    WifiManager myWifiManager;
    private WifiManager.LocalOnlyHotspotReservation mReservation;
    private boolean isHotspotEnabled = false;
    private final int REQUEST_ENABLE_LOCATION_SYSTEM_SETTINGS = 101;

    public WifiP2pManager myWifiP2PManager;
    public Context context;
    WifiP2pManager.Channel myChannel;

    BroadcastReceiver myReceiver;
    IntentFilter myIntentFilter;

    List<WifiP2pDevice> peers = new ArrayList<WifiP2pDevice>();
    String[] deviceNameArray;
    WifiP2pDevice[] deviceArray;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wifi);
        initialize();

        on_off_wifi.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onClick(View v) {
                if(myWifiManager.isWifiEnabled()){
                    myWifiManager.setWifiEnabled(false);
                    on_off_wifi. setText("WiFi ON");
                    enableLocationSettings();
                }else {
                    turnOffHotspot();
                    myWifiManager.setWifiEnabled(true);
                    on_off_wifi.setText("WiFi OFF");
                }
            }
        });
    }

    @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(WiFi.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)
    private void toggleHotspot() {
        if(!isHotspotEnabled){
            turnOnHotspot();
        }else {
            turnOffHotspot();
        }
    }

    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);

                    System.out.println(reservation.getWifiConfiguration() + "*****************************************************");
                    //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)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, 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(WiFi.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(WiFi.this, "Canceled", Toast.LENGTH_SHORT).show();
                        break;
                    default:
                        break;
                }
                break;
        }
    }

    private void mylistener() {
        on_off_wifi.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if(myWifiManager.isWifiEnabled()){
                    myWifiManager.setWifiEnabled(false);
                    on_off_wifi. setText("WiFi ON");
                }else {
                    myWifiManager.setWifiEnabled(true);
                    on_off_wifi.setText("WiFi OFF");
                }
            }
        });

        discover_wifi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myWifiP2PManager.discoverPeers(myChannel, new WifiP2pManager.ActionListener() {
                    @Override
                    public void onSuccess() {
                        connectionState_tv.setText("Discovery started");
                    }

                    @Override
                    public void onFailure(int reason) {
                        connectionState_tv.setText("Discovery starting failed");

                    }
                });
            }
        });

        peerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                final WifiP2pDevice device = deviceArray[position];
                WifiP2pConfig config = new WifiP2pConfig();
                config.deviceAddress  = device.deviceAddress;
                myWifiP2PManager.connect(myChannel, config, new WifiP2pManager.ActionListener() {
                    @Override
                    public void onSuccess() {
                        Toast.makeText(getApplicationContext(),"Connectect to "+device.deviceName,Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onFailure(int reason) {
                        Toast.makeText(getApplicationContext(),"Not connectected ",Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    private void initialize() {
        on_off_wifi = (Button) findViewById(R.id.on_off);
        discover_wifi = (Button) findViewById(R.id.discover);
        connectionState_tv = (TextView) findViewById(R.id.connectionState);
        peerListView = (ListView) findViewById(R.id.peerListView);

        myWifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);

        myWifiP2PManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
        myChannel = myWifiP2PManager.initialize(this,getMainLooper(),null);

        myReceiver = new recovics.htwk.recovics_exo_hand.WifiDirectBroadcastReceiver(myWifiP2PManager,myChannel, WiFi.this);

        myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
        myIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
        myIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
        myIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);

    }


    WifiP2pManager.PeerListListener peerListListener = new WifiP2pManager.PeerListListener() {
        @Override
        public void onPeersAvailable(WifiP2pDeviceList peerlist) {
            if(!peerlist.getDeviceList().equals(peers)) {
                peers.clear();
                peers.addAll(peerlist.getDeviceList());

                deviceNameArray =  new String[peerlist.getDeviceList().size()];
                deviceArray = new WifiP2pDevice[peerlist.getDeviceList().size()];
                int index = 0;

                for (WifiP2pDevice device : peerlist.getDeviceList()){
                    deviceNameArray[index]=device.deviceName;
                    deviceArray[index]=device;
                    index++;
                }

                ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,deviceNameArray);
                peerListView.setAdapter(adapter);

                if(peers.size()==0){
                    Toast.makeText(getApplicationContext(),"No Devices found",Toast.LENGTH_SHORT).show();
                    return;
                }
            }
        }
    };

    WifiP2pManager.ConnectionInfoListener connectionInfoListener = new WifiP2pManager.ConnectionInfoListener() {
        @Override
        public void onConnectionInfoAvailable(WifiP2pInfo info) {
            final InetAddress groupOwnerAddress = info.groupOwnerAddress;
            if(info.groupFormed && info.isGroupOwner){
                connectionState_tv.setText("host");
            }else if(info.groupFormed){
                connectionState_tv.setText("Client");
            }
        }
    };
    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(myReceiver,myIntentFilter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(myReceiver);
    }

}




The Logcat looks as next:

D/WifiManager: LocalOnlyHotspotCallbackProxy: handle message what: 0 msg: { when=-2ms what=0 obj=* ID: -2 SSID: AndroidShare_6018 PROVIDER-NAME: null BSSID: null FQDN: null PRIO: 0 HIDDEN: false
NetworkSelectionStatus NETWORK_SELECTION_ENABLED
hasEverConnected: false
KeyMgmt: WPA2_PSK Protocols:
AuthAlgorithms:
PairwiseCiphers:
GroupCiphers:
PSK: *

Enterprise config:
IP config:
IP assignment: UNASSIGNED
Proxy settings: UNASSIGNED
cuid=-1 luid=-1 lcuid=0 userApproved=USER_UNSPECIFIED noInternetAccessExpected=false roamingFailureBlackListTimeMilli: 1000
target=android.net.wifi.WifiManager$LocalOnlyHotspotCallbackProxy$1 }
================
OR
================
D/WifiManager: LocalOnlyHotspotCallbackProxy: handle message what: 0 msg: { when=0 what=0 obj=* ID: -2 SSID: AndroidShare_6787 PROVIDER-NAME: null BSSID: null FQDN: null PRIO: 0 HIDDEN: false
NetworkSelectionStatus NETWORK_SELECTION_ENABLED
hasEverConnected: false
KeyMgmt: WPA2_PSK Protocols:
AuthAlgorithms:
PairwiseCiphers:
GroupCiphers:
PSK: *

Enterprise config:
IP config:
IP assignment: UNASSIGNED
Proxy settings: UNASSIGNED
cuid=-1 luid=-1 lcuid=0 userApproved=USER_UNSPECIFIED noInternetAccessExpected=false roamingFailureBlackListTimeMilli: 1000
target=android.net.wifi.WifiManager$LocalOnlyHotspotCallbackProxy$1 }
 

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones