1. Are you ready for the Galaxy S20? Here is everything we know so far!

Local Hotspot - Personalized and Fixed SSID

Discussion in 'Android Development' started by jesusgcabal, Feb 4, 2021.

  1. jesusgcabal

    jesusgcabal Lurker
    Thread Starter

    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. :)
    Code (Java):
    1. public class WiFi extends AppCompatActivity {
    2.  
    3.     private Button on_off_wifi;
    4.     private Button discover_wifi;
    5.     public TextView connectionState_tv;
    6.     private ListView peerListView;
    7.  
    8.     WifiManager myWifiManager;
    9.     private WifiManager.LocalOnlyHotspotReservation mReservation;
    10.     private boolean isHotspotEnabled = false;
    11.     private final int REQUEST_ENABLE_LOCATION_SYSTEM_SETTINGS = 101;
    12.  
    13.     public WifiP2pManager myWifiP2PManager;
    14.     public Context context;
    15.     WifiP2pManager.Channel myChannel;
    16.  
    17.     BroadcastReceiver myReceiver;
    18.     IntentFilter myIntentFilter;
    19.  
    20.     List<WifiP2pDevice> peers = new ArrayList<WifiP2pDevice>();
    21.     String[] deviceNameArray;
    22.     WifiP2pDevice[] deviceArray;
    23.  
    24.     @Override
    25.     protected void onCreate(@Nullable Bundle savedInstanceState) {
    26.         super.onCreate(savedInstanceState);
    27.         setContentView(R.layout.activity_wifi);
    28.         initialize();
    29.  
    30.         on_off_wifi.setOnClickListener(new View.OnClickListener() {
    31.             @RequiresApi(api = Build.VERSION_CODES.O)
    32.             @Override
    33.             public void onClick(View v) {
    34.                 if(myWifiManager.isWifiEnabled()){
    35.                     myWifiManager.setWifiEnabled(false);
    36.                     on_off_wifi. setText("WiFi ON");
    37.                     enableLocationSettings();
    38.                 }else {
    39.                     turnOffHotspot();
    40.                     myWifiManager.setWifiEnabled(true);
    41.                     on_off_wifi.setText("WiFi OFF");
    42.                 }
    43.             }
    44.         });
    45.     }
    46.  
    47.     @RequiresApi(api = Build.VERSION_CODES.O)
    48.     private void enableLocationSettings() {
    49.         LocationRequest mLocationRequest = new LocationRequest();
    50.         /*mLocationRequest.setInterval(10);
    51.         mLocationRequest.setSmallestDisplacement(10);
    52.         mLocationRequest.setFastestInterval(10);
    53.         mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);*/
    54.         LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
    55.         builder.addLocationRequest(mLocationRequest)
    56.                 .setAlwaysShow(false); // Show dialog
    57.  
    58.         Task<LocationSettingsResponse> task= LocationServices.getSettingsClient(this).checkLocationSettings(builder.build());
    59.  
    60.         task.addOnCompleteListener(task1 -> {
    61.             try {
    62.                 LocationSettingsResponse response = task1.getResult(ApiException.class);
    63.                 // All location settings are satisfied. The client can initialize location
    64.                 // requests here.
    65.                 toggleHotspot();
    66.  
    67.             } catch (ApiException exception) {
    68.                 switch (exception.getStatusCode()) {
    69.                     case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
    70.                         // Location settings are not satisfied. But could be fixed by showing the
    71.                         // user a dialog.
    72.                         try {
    73.                             // Cast to a resolvable exception.
    74.                             ResolvableApiException resolvable = (ResolvableApiException) exception;
    75.                             // Show the dialog by calling startResolutionForResult(),
    76.                             // and check the result in onActivityResult().
    77.                             resolvable.startResolutionForResult(WiFi.this, REQUEST_ENABLE_LOCATION_SYSTEM_SETTINGS);
    78.                         } catch (IntentSender.SendIntentException e) {
    79.                             // Ignore the error.
    80.                         } catch (ClassCastException e) {
    81.                             // Ignore, should be an impossible error.
    82.                         }
    83.                         break;
    84.                     case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
    85.                         // Location settings are not satisfied. However, we have no way to fix the
    86.                         // settings so we won't show the dialog.
    87.                         break;
    88.                 }
    89.             }
    90.         });
    91.     }
    92.     @RequiresApi(api = Build.VERSION_CODES.O)
    93.     private void toggleHotspot() {
    94.         if(!isHotspotEnabled){
    95.             turnOnHotspot();
    96.         }else {
    97.             turnOffHotspot();
    98.         }
    99.     }
    100.  
    101.     private boolean isLocationPermissionEnable() {
    102.         if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
    103.             ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_COARSE_LOCATION}, 2);
    104.             return false;
    105.         }
    106.         return true;
    107.     }
    108.  
    109.     @RequiresApi(api = Build.VERSION_CODES.O)
    110.     private void turnOnHotspot() {
    111.         if (!isLocationPermissionEnable()) {
    112.             return;
    113.         }
    114.         WifiManager manager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    115.  
    116.         if (manager != null) {
    117.             // Don't start when it started (existed)
    118.             manager.startLocalOnlyHotspot(new WifiManager.LocalOnlyHotspotCallback() {
    119.  
    120.                 @Override
    121.                 public void onStarted(WifiManager.LocalOnlyHotspotReservation reservation) {
    122.                     super.onStarted(reservation);
    123.  
    124.                     System.out.println(reservation.getWifiConfiguration() + "*****************************************************");
    125.                     //Log.d(TAG, "Wifi Hotspot is on now");
    126.                     mReservation = reservation;
    127.                     isHotspotEnabled = true;
    128.                 }
    129.  
    130.                 @Override
    131.                 public void onStopped() {
    132.                     super.onStopped();
    133.                     //Log.d(TAG, "onStopped: ");
    134.                     isHotspotEnabled = false;
    135.                 }
    136.  
    137.                 @Override
    138.                 public void onFailed(int reason) {
    139.                     super.onFailed(reason);
    140.                     //Log.d(TAG, "onFailed: ");
    141.                     isHotspotEnabled = false;
    142.                 }
    143.             }, new Handler());
    144.         }
    145.     }
    146.  
    147.     @RequiresApi(api = Build.VERSION_CODES.O)
    148.     private void turnOffHotspot() {
    149.         if (!isLocationPermissionEnable()) {
    150.             return;
    151.         }
    152.         if (mReservation != null) {
    153.             mReservation.close();
    154.             isHotspotEnabled = false;
    155.         }
    156.     }
    157.  
    158.     @RequiresApi(api = Build.VERSION_CODES.O)
    159.     @Override
    160.     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    161.         super.onActivityResult(requestCode, resultCode, data);
    162.         final LocationSettingsStates states = LocationSettingsStates.fromIntent(data);
    163.         switch (requestCode) {
    164.             case REQUEST_ENABLE_LOCATION_SYSTEM_SETTINGS:
    165.                 switch (resultCode) {
    166.                     case Activity.RESULT_OK:
    167.                         // All required changes were successfully made
    168.                         toggleHotspot();
    169.                         Toast.makeText(WiFi.this, states.isLocationPresent() + "", Toast.LENGTH_SHORT).show();
    170.                         break;
    171.                     case Activity.RESULT_CANCELED:
    172.                         // The user was asked to change settings, but chose not to
    173.                         Toast.makeText(WiFi.this, "Canceled", Toast.LENGTH_SHORT).show();
    174.                         break;
    175.                     default:
    176.                         break;
    177.                 }
    178.                 break;
    179.         }
    180.     }
    181.  
    182.     private void mylistener() {
    183.         on_off_wifi.setOnClickListener(new View.OnClickListener() {
    184.  
    185.             @Override
    186.             public void onClick(View v) {
    187.                 if(myWifiManager.isWifiEnabled()){
    188.                     myWifiManager.setWifiEnabled(false);
    189.                     on_off_wifi. setText("WiFi ON");
    190.                 }else {
    191.                     myWifiManager.setWifiEnabled(true);
    192.                     on_off_wifi.setText("WiFi OFF");
    193.                 }
    194.             }
    195.         });
    196.  
    197.         discover_wifi.setOnClickListener(new View.OnClickListener() {
    198.             @Override
    199.             public void onClick(View v) {
    200.                 myWifiP2PManager.discoverPeers(myChannel, new WifiP2pManager.ActionListener() {
    201.                     @Override
    202.                     public void onSuccess() {
    203.                         connectionState_tv.setText("Discovery started");
    204.                     }
    205.  
    206.                     @Override
    207.                     public void onFailure(int reason) {
    208.                         connectionState_tv.setText("Discovery starting failed");
    209.  
    210.                     }
    211.                 });
    212.             }
    213.         });
    214.  
    215.         peerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    216.             @Override
    217.             public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    218.  
    219.                 final WifiP2pDevice device = deviceArray[position];
    220.                 WifiP2pConfig config = new WifiP2pConfig();
    221.                 config.deviceAddress  = device.deviceAddress;
    222.                 myWifiP2PManager.connect(myChannel, config, new WifiP2pManager.ActionListener() {
    223.                     @Override
    224.                     public void onSuccess() {
    225.                         Toast.makeText(getApplicationContext(),"Connectect to "+device.deviceName,Toast.LENGTH_SHORT).show();
    226.                     }
    227.  
    228.                     @Override
    229.                     public void onFailure(int reason) {
    230.                         Toast.makeText(getApplicationContext(),"Not connectected ",Toast.LENGTH_SHORT).show();
    231.                     }
    232.                 });
    233.             }
    234.         });
    235.     }
    236.  
    237.     private void initialize() {
    238.         on_off_wifi = (Button) findViewById(R.id.on_off);
    239.         discover_wifi = (Button) findViewById(R.id.discover);
    240.         connectionState_tv = (TextView) findViewById(R.id.connectionState);
    241.         peerListView = (ListView) findViewById(R.id.peerListView);
    242.  
    243.         myWifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    244.  
    245.         myWifiP2PManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
    246.         myChannel = myWifiP2PManager.initialize(this,getMainLooper(),null);
    247.  
    248.         myReceiver = new recovics.htwk.recovics_exo_hand.WifiDirectBroadcastReceiver(myWifiP2PManager,myChannel, WiFi.this);
    249.  
    250.         myIntentFilter = new IntentFilter();
    251.         myIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
    252.         myIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
    253.         myIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
    254.         myIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
    255.  
    256.     }
    257.  
    258.  
    259.     WifiP2pManager.PeerListListener peerListListener = new WifiP2pManager.PeerListListener() {
    260.         @Override
    261.         public void onPeersAvailable(WifiP2pDeviceList peerlist) {
    262.             if(!peerlist.getDeviceList().equals(peers)) {
    263.                 peers.clear();
    264.                 peers.addAll(peerlist.getDeviceList());
    265.  
    266.                 deviceNameArray =  new String[peerlist.getDeviceList().size()];
    267.                 deviceArray = new WifiP2pDevice[peerlist.getDeviceList().size()];
    268.                 int index = 0;
    269.  
    270.                 for (WifiP2pDevice device : peerlist.getDeviceList()){
    271.                     deviceNameArray[index]=device.deviceName;
    272.                     deviceArray[index]=device;
    273.                     index++;
    274.                 }
    275.  
    276.                 ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,deviceNameArray);
    277.                 peerListView.setAdapter(adapter);
    278.  
    279.                 if(peers.size()==0){
    280.                     Toast.makeText(getApplicationContext(),"No Devices found",Toast.LENGTH_SHORT).show();
    281.                     return;
    282.                 }
    283.             }
    284.         }
    285.     };
    286.  
    287.     WifiP2pManager.ConnectionInfoListener connectionInfoListener = new WifiP2pManager.ConnectionInfoListener() {
    288.         @Override
    289.         public void onConnectionInfoAvailable(WifiP2pInfo info) {
    290.             final InetAddress groupOwnerAddress = info.groupOwnerAddress;
    291.             if(info.groupFormed && info.isGroupOwner){
    292.                 connectionState_tv.setText("host");
    293.             }else if(info.groupFormed){
    294.                 connectionState_tv.setText("Client");
    295.             }
    296.         }
    297.     };
    298.     @Override
    299.     protected void onResume() {
    300.         super.onResume();
    301.         registerReceiver(myReceiver,myIntentFilter);
    302.     }
    303.  
    304.     @Override
    305.     protected void onPause() {
    306.         super.onPause();
    307.         unregisterReceiver(myReceiver);
    308.     }
    309.  
    310. }



    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 }
     



    1. Download the Forums for Android™ app!


      Download

       
Loading...
Similar Threads - Local Hotspot Personalized
  1. theguy1991
    Replies:
    3
    Views:
    298
  2. OnGoGS7A
    Replies:
    1
    Views:
    338
  3. Night Knight
    Replies:
    0
    Views:
    662
  4. EnthusiasticMalfunction
    Replies:
    2
    Views:
    445
  5. Sonofsun3042
    Replies:
    0
    Views:
    721
  6. Aquitaine
    Replies:
    3
    Views:
    1,042
  7. ChristopherMugg
    Replies:
    5
    Views:
    456
  8. moglisati
    Replies:
    4
    Views:
    704
  9. manjula1
    Replies:
    0
    Views:
    582
  10. Andre0815
    Replies:
    0
    Views:
    1,018

Share This Page

Loading...