How to get history/logs of Wifi Hotspot names? - android

I just want to get SSID of wifi hotspot. Below code snippet is enough to get current wifi hotspot name, but I want previous one.
try {
WifiManager manager = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);
Method getWifiApConfigurationMethod = manager.getClass().getMethod("getWifiApConfiguration");
WifiConfiguration config = (WifiConfiguration) getWifiApConfigurationMethod.invoke(manager);
Log.e("CLIENT", "SSID:" + config.SSID);
} catch (Exception e) {
e.printStackTrace();
}
Please help...

Related

turn off wifi in Android Q

Is there any way besides the standard ConnectivityManager-API to modify wifi state in android q? I've just read google removed the api in android 10. Im willing to give the app android device administrator status, grant all permissions with adb, etc as I wont publish the app and will only use it for myself.
Your app must be a device owner as a variant to use wifiManager.setWifiEnabled(false) method that is deprecated started from Q.
Deprecation Exemptions:
Device Owner (DO), Profile Owner (PO) and system apps.
WifiManager
You can use the following code to disable wifi :
try {
WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
return wifiManager.setWifiEnabled(false);
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
to disconnect wifi :
WifiManager wifiManager = (WifiManager)context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wifiManager.disconnect();
and the following code to forget a particular wifi network :
try {
WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
List wifiNetworks = wifiManager.getConfiguredNetworks();
for (Object wifiConf : wifiNetworks) {
if (((WifiConfiguration) wifiConf).SSID.equalsIgnoreCase(SSID)) {
return wifiManager.removeNetwork(wifiManager.getConnectionInfo().getNetworkId()) && wifiManager.saveConfiguration();
}
}
} catch (Exception ex) {
ex.printStackTrace();
}

How does ShareIt create and configure hotspot

I have to create a Wifi Hotspot with specific SSID and PASSWORD dynamically in my Android app project. I checked the ShareIt mobile app which creates a hotspot with SSID and PASSWORD and the receiver will connect to that hotspot, am expecting something similar to that.
Requirement is like, Android app should be able to create the Wifi hotspot with specific SSID and PASSWORD which will get from the server.
WifiManager wifimanager = (WifiManager) context.getSystemService(context.WIFI_SERVICE);
WifiConfiguration wificonfiguration = null;
try {
wificonfiguration = new WifiConfiguration();
wificonfiguration.SSID = apName;
// if WiFi is on, turn it off
if(isApOn(context)) {
wifimanager.setWifiEnabled(false);
// if ap is on and then disable ap
disableAp(context);
}
Method method = wifimanager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
method.invoke(wifimanager, wificonfiguration, true);
return true;
}
catch (Exception e) {
e.printStackTrace();
}
I tried this code snippet, which is gives an error NoSuchMethodException.
Checking for Android version 9 Pie
Any help will be appreciated.
App like ShareIt is creating hotspot using Local Only Hotspot
But in this case android is creating hotspot with a ssid and password that we cannot configure (Android is choosing a random ssid and password)

how to obtain the ip address of the connected wifi router in android programmatically?

I want to obtain the ip address of the the wifi router to which my android phone is connected? I know that we can get the mac/BSSId and SSID by using the android APIS but I don't find the way to find the way to find the ip address of it?
I found the code for obtaining the ip address of phone owns wifi router
WifiManager myWifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo myWifiInfo = myWifiManager.getConnectionInfo();
int ipAddress = myWifiInfo.getIpAddress();
System.out.println("WiFi address is " + android.text.format.Formatter.formatIpAddress(ipAddress))
but failed to get what I want
What you likely want is DhcpInfo:
final WifiManager manager = (WifiManager) super.getSystemService(WIFI_SERVICE);
final DhcpInfo dhcp = manager.getDhcpInfo();
final String address = Formatter.formatIpAddress(dhcp.gateway);
This will yield the (formatted) gateway IP address, which should be what you're looking for.
Since formatIpAddress is Deprecatted, here is the alternative :
public String getHotspotAdress(){
final WifiManager manager = (WifiManager)super.getSystemService(WIFI_SERVICE);
final DhcpInfo dhcp = manager.getDhcpInfo();
int ipAddress = dhcp.gateway;
ipAddress = (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) ?
Integer.reverseBytes(ipAddress) : ipAddress;
byte[] ipAddressByte = BigInteger.valueOf(ipAddress).toByteArray();
try {
InetAddress myAddr = InetAddress.getByAddress(ipAddressByte);
return myAddr.getHostAddress();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
Log.e("Wifi Class", "Error getting Hotspot IP address ", e);
}
return "null"
}

how to set advanced settings of android wifihotspot

I'm turning portable wifi hotspot ON by following code:
private void createWifiAccessPoint() {
WifiManager wifiManager = (WifiManager)getBaseContext().getSystemService(Context.WIFI_SERVICE);
if(wifiManager.isWifiEnabled())
{
wifiManager.setWifiEnabled(false);
}
Method[] wmMethods = wifiManager.getClass().getDeclaredMethods(); //Get all declared methods in WifiManager class
boolean methodFound=false;
for(Method method: wmMethods){
if(method.getName().equals("setWifiApEnabled")){
methodFound=true;
WifiConfiguration netConfig = new WifiConfiguration();
netConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
try {
boolean apstatus=(Boolean) method.invoke(wifiManager, netConfig,true);
//statusView.setText("Creating a Wi-Fi Network \""+netConfig.SSID+"\"");
for (Method isWifiApEnabledmethod: wmMethods)
{
if(isWifiApEnabledmethod.getName().equals("isWifiApEnabled")){
while(!(Boolean)isWifiApEnabledmethod.invoke(wifiManager)){
};
for(Method method1: wmMethods){
if(method1.getName().equals("getWifiApState")){
int apstate;
apstate=(Integer)method1.invoke(wifiManager);
// netConfig=(WifiConfiguration)method1.invoke(wifi);
//statusView.append("\nSSID:"+netConfig.SSID+"\nPassword:"+netConfig.preSharedKey+"\n");
}
}
}
}
if(apstatus)
{
System.out.println("SUCCESSdddd");
//statusView.append("\nAccess Point Created!");
//finish();
//Intent searchSensorsIntent = new Intent(this,SearchSensors.class);
//startActivity(searchSensorsIntent);
}else
{
System.out.println("FAILED");
//statusView.append("\nAccess Point Creation failed!");
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
if(!methodFound){
//statusView.setText("Your phone's API does not contain setWifiApEnabled method to configure an access point");
}
}
It works for me....... Hotspot turns on...... But there are also advanced settings by clicking 'menu' button.... And here is a problem... DHCP becomes disabled in LanSettings and Power Mode is only 5 minutes working on.... I want DHCP tto be ENABLED and PowerMode - "always on"...How can I resolve it?
You might have to look through the Android source code to find the answer to this. With your code is a device able to connect and get an IP address? If that is the case then DHCP for the AP is working.
Personally I don't even have a DHCP enabled or disabled option or a PowerMode on ICS.

How to detect WiFi tethering state

I want to know how to detect state of WiFi tethering. I've seen an article: Android 2.3 wifi hotspot API But it doesn't work! It returns always WIFI_AP_STATE_DISABLED = 1. It doesn't depend on real state of WiFi tethering.
Using reflection:
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
Method[] wmMethods = wifi.getClass().getDeclaredMethods();
for (Method method: wmMethods) {
if (method.getName().equals("isWifiApEnabled")) {
try {
boolean isWifiAPenabled = method.invoke(wifi);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
As you can see here
In addition to the reflexion, to get the Wifi tethering status update, you can listen to this broadcast Action :
IntentFilter filter = new IntentFilter("android.net.wifi.WIFI_AP_STATE_CHANGED");
To get all tethering option update :
IntentFilter filter = new IntentFilter("android.net.conn.TETHER_STATE_CHANGED");
Those actions are hidden inside the Android source code
First, you need to get WifiManager:
Context context = ...
final WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
Then:
public static boolean isSharingWiFi(final WifiManager manager)
{
try
{
final Method method = manager.getClass().getDeclaredMethod("isWifiApEnabled");
method.setAccessible(true); //in the case of visibility change in future APIs
return (Boolean) method.invoke(manager);
}
catch (final Throwable ignored)
{
}
return false;
}
Also you need to request a permission in AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
Here is the Xamarin C# version if anyone is looking:
static Method isWifiApEnabledMethod;
public static bool IsWifiApEnabled ()
{
var wifiManager = WifiManager.FromContext (Application.Context);
if (isWifiApEnabledMethod == null)
{
try
{
isWifiApEnabledMethod = wifiManager.Class.GetDeclaredMethod ("isWifiApEnabled");
isWifiApEnabledMethod.Accessible = true; //in the case of visibility change in future APIs
}
catch (NoSuchMethodException e)
{
Debug.WriteLine ("Can't get method by reflection" + e);
}
catch (System.Exception ex)
{
Debug.WriteLine ("Can't get method by reflection" + ex);
}
}
if (isWifiApEnabledMethod != null)
{
try
{
return (bool)isWifiApEnabledMethod.Invoke (wifiManager);
}
catch (System.Exception ex)
{
Debug.WriteLine ("Can't invoke by reflection" + ex);
}
}
return false;
}
(without using reflection since they say google is restricting it)
I'm writting this answer 10 years later. also I don't know if this can be considered a good aproach or not but I first get the Wlan network interface IPs
and if there is no address I assume that it tethering isn't enabled. if there is an address, I check using the connectivity manger whether WI-FI is connected to a network or not. if there is an IP for the Wlan network interface but it isn't connected to a network, I assume tethering is enabled.
you probably would need to add this line to your manifest file
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
code to get the ip of an inteface (this only gets the IPv4, you can modify it to get the IPv6 or both if you want)
// method used to retrieve Wlan ip addresses IPv4 of the device.
public static String IpAddresses() throws NoAddressFoundException, SocketException {
Enumeration<NetworkInterface> Nics = NetworkInterface.getNetworkInterfaces();
while (Nics.hasMoreElements()) {
NetworkInterface NIC = Nics.nextElement();
if (NIC.isUp() && !NIC.isLoopback() && NIC.getName().contains("wlan")) {
Enumeration<InetAddress> Addresses = NIC.getInetAddresses();
while (Addresses.hasMoreElements()) {
InetAddress WlanAddress = Addresses.nextElement();
if (WlanAddress instanceof Inet4Address)
return WlanAddress.getHostAddress();
}
}
}
throw new NoAddressFoundException("No suitable wifi address found");
}
then if there is an address i check if wifi is connected by this method:
//method to check if the device is connected to a Wi-Fi network; it doesn't matter if network has access to internet
public static boolean isWifiConnected(Context context) {
ConnectivityManager ConMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo WifiInfo = ConMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
return WifiInfo.isConnected();
}
NOTE: the "NoAddressFoundException" is a custom exception in my app if anyone is wondering. it won't exist in your case.
Reflection is a poor way to achieve this.
We can inspect the DhcpInfo to determine if the device is allocating addresses (mobile hotspot) or is being allocated by another DHCP server.
Here is a kotlin function that will determine if a device is a mobile hotspot, it has not been widely tested so YMMV.
fun isMobileHotspot(manager: WifiManager): Boolean {
val info = manager.dhcpInfo
return (
info.ipAddress == 0
&& info.netmask == 0
&& info.gateway == 0
&& info.serverAddress == 16885952) // 192.168.1.1
}

Categories

Resources