How to get device hotspot SSID programmatically in Android? - java

I'm struggling to find a way to find hotspot ssid of the device, all solutions which I found were returning Wi-Fi name to which device is connected while I want to find the hotspot name, which the device created.
getting wifi name
public static String getWifiName(Context context) {
WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
if (manager.isWifiEnabled()) {
WifiInfo wifiInfo = manager.getConnectionInfo();
if (wifiInfo != null) {
NetworkInfo.DetailedState state = WifiInfo.getDetailedStateOf(wifiInfo.getSupplicantState());
if (state == NetworkInfo.DetailedState.CONNECTED || state == NetworkInfo.DetailedState.OBTAINING_IPADDR) {
return wifiInfo.getSSID();
}
}
}
return null;
}

Related

How to detect when user turn one wifi connection to other wifi?

I have problem with WiFi connection detection. My goal is to detect when user is switching between different WiFis. I found this, but it only detects when WiFi was established. In my case I need to know when one WiFi network changed to another on phone.
You can use BroadcastReceiver
public class ConnectivityReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMan.getActiveNetworkInfo();
if(intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
if(netInfo.isConnected()) {
WifiManager wifiManager = (WifiManager) context.getAplicationContext().getSystemService (Context.WIFI_SERVICE);
WifiInfo info = wifiManager.getConnectionInfo ();
String ssid = info.getSSID();
Log.d("Wifi Connected", "Wifi name is "+ info.getSSID());
}
}
}
}

Connection to specific WiFi if already have connection to another

I've been fighting like a fish for two days already, and I can not find a solution. I tried this code but it through time worked on Android 5(Lollipop) and didn't work at 7.1.1.(Nougat) I have another Scenario where phone loses connection and after this, it needs to return to the old Wifi.
public void setWifiConnection1(View view){
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
WifiConfiguration wc = new WifiConfiguration();
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
wc.SSID = "\"NETWORK_NAME\"";
wc.preSharedKey = "\"PASSWORD\"";
wc.status = WifiConfiguration.Status.ENABLED;
wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
wc.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
wc.priority = 999999;
wifiManager.setWifiEnabled(true);
int netId = wifiManager.addNetwork(wc);
if (netId == -1) {
netId = getExistingNetworkId(wc.SSID);
}
wifiManager.disconnect();
wifiManager.enableNetwork(netId, true);
wifiManager.reconnect();
}
private int getExistingNetworkId(String SSID) {
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
List<WifiConfiguration> configuredNetworks = wifiManager.getConfiguredNetworks();
if (configuredNetworks != null) {
for (WifiConfiguration existingConfig : configuredNetworks) {
if (existingConfig.SSID.equals(SSID)) {
return existingConfig.networkId;
}
}
}
return -1;
}
wifiManager.setWifiEnabled(true);
You can't execute your code right after this line. You should do a wifiManager.isWifiEnabled() check and subscribe to a broadcast if it's disabled.
Next...
wifiManager.disconnect();
wifiManager.enableNetwork(netId, true);
wifiManager.reconnect();
This part is very odd: why do you disconnect ? Be aware that most of WifiManager operations are asynchronous so that's why you observe different results each time - real "disconnect" may occur after you've tried to enable your desired network.
You can always get inspiration from system API: https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r30/wifi/java/android/net/wifi/WifiManager.java#2773
So correct sequence is:
wifiManager.addNetwork(...);
wifiManager.enableNetwork(netId, true);
wifiManager.saveConfiguration();
wifiManager.reconnect();
But if you are allowed to do so, it's more convenient to use system API directly.

Android: How to Scan WiFi, Connect to an AP and then Establish a TCP Connection?

I am writing an Android app. In my app, I want it to scan the WiFi network, and then connect to a dedicated Access Point (AP) by checking the SSID. And then after connected to the AP, establish a TCP connection to it.
Above I have described 3 tasks in order. I know how to do each task independently, however I do not know the proper way to finish them in sequence. Examples are appreciated.
Currently my code is to start scan the WiFi network whenever the user pressed a button by:
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if (wifiManager.isWifiEnabled() == false) {
wifiManager.setWifiEnabled(true);
Toast.makeText(MainActivity.this, "WiFi is enabled", Toast.LENGTH_SHORT).show();
}
wifiManager.startScan();
I used a broadcast receiver to check when the scanning finished, and then invoke a method ( ReconnectAP() ) to connect WiFi to the AP. I also used the broadcast receiver to check when it connected to the AP, then I want to execute an Async Task to establish the TCP network. However, by googling, I learn that it is a bad practice to execute async task in a broadcast receiver, because the async task can be killed by Android when the receiver finished.
private String networkSSID = "The_AP_SSID";
// In onCreate of MainActivity, register the broadcast receiver:
registerReceiver(WiFireceiver, new IntentFilter(
WifiManager.NETWORK_STATE_CHANGED_ACTION));
registerReceiver(WiFireceiver, new IntentFilter(
WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
// Implement my broadcast receiver class:
BroadcastReceiver WiFireceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action)) {
Log.d(TAG, "WiFiReceiver received broadcast, action is SCAN_RESULTS_AVAILABLE_ACTION");
Log.d(TAG, "Start to check if need to reconnect to Charger AP");
ReconnectAP();
}
if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) {
Log.d(TAG, "WiFiReceiver received broadcast, action is NETWORK_STATE_CHANGED_ACTION");
NetworkInfo netInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
// If the connection type is WiFi...
if (netInfo != null && ConnectivityManager.TYPE_WIFI == netInfo.getType()) {
// If it is connected now....
if (netInfo.isConnected()) {
Log.d(TAG, "WiFi connected");
// Get WiFi connection information, eg SSID
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
String ssid = wifiInfo.getSSID();
Log.d(TAG, "WiFi connected SSID is : " + ssid);
if(ssid.equals(networkSSID)) {
// Start async task to establish a TCP connection:
new ConnectTCPAsynTask().execute();
}
} else {
Log.d(TAG, "WiFi disconnected");
}
}
}
}
};
int ReconnectAP() {
Log.d(TAG, "In ReconnectAP( )");
wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
String ssid = wifiInfo.getSSID();
Log.d(TAG, "Original connected AP SSID: " + ssid);
if (!ssid.equals(networkSSID)) {
Log.d(TAG, "It is not equal to the dedicated AP SSID,
we will disconnect the current WiFi connection,
and then connect to our dedicate AP");
List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
for (WifiConfiguration i : list) {
if (i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
Log.d(TAG, "Start disconnect and reconnect to " + networkSSID);
wifiManager.disconnect();
wifiManager.enableNetwork(i.networkId, true);
wifiManager.reconnect();
return 1;
}
}
Log.d(TAG,"Reach here if cannot find the target SSID");
return -1;
}
Log.d(TAG, "Reach here if we already connected to the dedicated AP");
return 0;
}
Pass a flag from the broadcast receiver back to the main activity and let the main activity handle the task.

Android check WIFI status (disconnected or user changed WIFI) How to FLAG it?

I is there a way to Flag if a WIFI connection got disconnected/ dropped off OR if the user actually changed the WIFI network ?
I need my app to do :
Connect to a WIFI XYZ, if XYZ get disconnect (FLAG 1) or dropped off Then reconnect to XYZ.
But is the user change to another wifi BTOpen (FLAG 2) then allow the connect and Stop my service.
If user connect to XYZ again then start the loop again.
What I got so far is :
<!-- WIFI Receiver -->
<receiver android:name=".ReceiverWifi" >
<intent-filter>
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
<service android:name=".ServiceWifiMonitor" />
<receiver android:name=".ServiceController" >
<intent-filter >
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
BroadcastReceiver:
myApplication = (MyApplication) context.getApplicationContext();
conManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
networkInfo = conManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
boolean isConnected = networkInfo != null && networkInfo.isConnected();
int reconnectedCount = myApplication.getReconnectedCount();
if (wifiManager.isWifiEnabled()) {
if("android.net.conn.CONNECTIVITY_CHANGE".equals(intent.getAction())) {
//Start and Stop Service
if(myApplication.isReconnect()) startServiceWifiMonitor(); else stopServiceWifiMonitor();
if (isConnected) {
//There is a WIFI Connection
myApplication.setConnectedWifi(NetworkUtil.getCurrentSSID(context));
myApplication.setWifiStatus("connected");
if (NetworkUtil.isConnectedToXYZ(context)) {
startServiceWifiMonitor();
if(pref.getisFirstTime())
{
myApplication.setWifiByChoise("XYZ");
pref.setisFirstTime(false);
}
else { myApplication.setisReconnect(true); }
}
else {
//Connected to different NetWork
if(myApplication.isReconnect() && NetworkUtil.isXYZAvailable(context))
{
//ReConnect to XYZ
NetworkUtil.connectToXYZ(context);
myApplication.setReconnectedCount(reconnectedCount++);
}
else { resetValues("AAAA"); }
}
}//end if
else
{
if(NetworkUtil.isXYZAvailable(context) && myApplication.getWifiByChoise().equals("XYZ"))
{
NetworkUtil.connectToXYZ(context);
myApplication.setReconnectedCount(reconnectedCount++);
}
else { resetValues(""); }
}
}//end CONNECTIVITY_CHANGE
Service Monitor:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "onStartCommand > Received start id " + startId + ": " + intent);
objHandler.postDelayed(mTasks, 1000);
return START_STICKY;
}//end onStartCommand
private Runnable mTasks = new Runnable() {
public void run() {
if(myApplication.getWifiByChoise().equals("XYZ") && NetworkUtil.isXYZAvailable(context)) {
try
{
//Get the numbers of Reconnection
int count = myApplication.getReconnectedCount();
if(!NetworkUtil.isWifiConnected(context))
{
NetworkUtil.connectToXYZ(context);
myApplication.setisReconnect(true);
myApplication.setReconnectedCount(count++);
}
if(!NetworkUtil.isConnectedToXYZ(context))
{
NetworkUtil.connectToXYZ(context);
myApplication.setisReconnect(true);
myApplication.setReconnectedCount(count++);
}
} catch (Exception e) {e.printStackTrace();}
}
else { stopSelf(); }
int ms_interval = 3000;
objHandler.postDelayed(mTasks, ms_interval);
}
};//end Runnable mTasks
The problem with my app is that :
It crashed the device, Seems like its eating up all the memory ram.
sometimes with the wifi XYZ get disconnect it wont connect again and if user change to another wifi, it won't allow the connection.
I really appreciate your help. Thank you.
Check the network connected Name by using:
public String getWifiName(Context context) {
WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
if (manager.isWifiEnabled()) {
WifiInfo wifiInfo = manager.getConnectionInfo();
if (wifiInfo != null) {
DetailedState state = WifiInfo.getDetailedStateOf(wifiInfo.getSupplicantState());
if (state == DetailedState.CONNECTED || state == DetailedState.OBTAINING_IPADDR) {
return wifiInfo.getSSID();
}
}
}
return null;
}
if this name matches your networkSSID, i.e. XYZ, then resume the service, else if it doesn't match, then stop the service:
if getWifiName(this).compareTo("XYZ") == 0 { //XYZ is your network name on which you want to resume the service
//code to resume
} else {
//code to stop the service
}
This is how I handle it in my app:
public class WifiStateWatcher extends BroadcastReceiver {
private MainActivity activity;
public WifiStateWatcher(MainActivity activity) {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
}
#Override
public void onReceive(Context context, Intent intent) {
SupplicantState supState;
WifiManager wifiManager = (WifiManager) activity.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
supState = wifiInfo.getSupplicantState();
if (supState.equals(SupplicantState.COMPLETED)) {
//we are connected to Wi-Fi network
} else {
//we lost Wi-Fi connectivity
}
}
}
You will need android.permission.ACCESS_WIFI_STATE permission
What you have done is almost correct. you need to check the network ssd name with the user connected wifi name.If it matched then do your part.
WifiManager wifiManager= (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
if (wifiManager.isWifiEnabled()) {
WifiInfo networkInfo = wifiManager.getConnectionInfo();
if (networkInfo != null) {
DetailedState state = WifiInfo.getDetailedStateOf(networkInfo .getSupplicantState());
if (state == DetailedState.CONNECTED ) {
return networkInfo.getSSID();
}
}
}
return null;
Now you have the network SSID so try to check with the your wifi name and SSID then you will get to know the connection status.....
Happy Programming
Also just checked this and found out that the main difference is:
/** IP traffic should be available. */
DetailedState.CONNECTED
and:
/**
* …
* This state indicates that the supplicant has completed its
* processing for the association phase and that data connection is
* fully configured. Note, however, that there may not be any IP
* address associated with the connection yet. Typically, a DHCP
* request needs to be sent at this point to obtain an address.
*/
SupplicantState.COMPLETED
So to trust that wifi is completely up, i now added the checks that:
boolean isConnected = activeNetworkInfo.isConnected();
and DetailedState.CONNECTED :)
happy coding

How can I find wifi speed in Android and how can I display wifi speed in TextView?

To find wifi speed I used this code:
WifiManager wifiManager = (WifiManager)this.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
if (wifiInfo != null) {
int linkSpeed = wifiInfo.getLinkSpeed(); //measured using WifiInfo.LINK_SPEED_UNITS
//txtSpeed.setText(linkSpeed);
}
I want to display the speed in my TextView. How can I do this?
Try This ::
TextView speedcount;
String s = Integer.toString(linkSpeed);
speedcount = (TextView)findViewById(R.id.textview);
speedcount.setText(s);
txtSpeed.setText(""+linkSpeed); or textSpeed.setText(Integer.toString(linkSpeed));. Make sure txtSpeed is instantiated properly.

Categories

Resources