I am trying to connect Specific wifi network in android 10(Android Q). Below android 10 it was working fine. I gone through some documents. Theysaid will have to use WifiNetworkSpecifier. I tried by using below code stuff.
WifiNetworkSpecifier.Builder builder = new WifiNetworkSpecifier.Builder();
builder.setSsid(ssid);
builder.setWpa2Passphrase(password);
WifiNetworkSpecifier wifiNetworkSpecifier = builder.build();
NetworkRequest.Builder networkRequestBuilder = new NetworkRequest.Builder();
networkRequestBuilder.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
networkRequestBuilder.setNetworkSpecifier(wifiNetworkSpecifier);
NetworkRequest networkRequest = networkRequestBuilder.build();
ConnectivityManager cm = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm != null) {
cm.requestNetwork(networkRequest, new ConnectivityManager.NetworkCallback() {
#Override
public void onAvailable(#NonNull Network network) {
super.onAvailable(network);
cm.bindProcessToNetwork(network);
}
});
}
But I am unable to connect specified network. Can anyone please guide me..
Thanks in Advance.
I had this function to connect in Wifi network, below Android 10 it works fine, but when I tried on Android 10, I had a successful connection but WITHOUT internet, I knew it's a bug in Android 10 but I found this application which can connect to wifi from Android 10 with no problem.
I'm blocked for days.
My function :
private void connectToWifi(String ssid, String password)
{
WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
try {
Log.e(TAG,"connection wifi pre Q");
WifiConfiguration wifiConfig = new WifiConfiguration();
wifiConfig.SSID = "\"" + ssid + "\"";
wifiConfig.preSharedKey = "\"" + password + "\"";
int netId = wifiManager.addNetwork(wifiConfig);
wifiManager.disconnect();
wifiManager.enableNetwork(netId, true);
wifiManager.reconnect();
} catch ( Exception e) {
e.printStackTrace();
}
} else {
Log.e(TAG,"connection wifi Q");
WifiNetworkSpecifier wifiNetworkSpecifier = new WifiNetworkSpecifier.Builder()
.setSsid( ssid )
.setWpa2Passphrase(password)
.build();
NetworkRequest networkRequest = new NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.setNetworkSpecifier(wifiNetworkSpecifier)
.build();
connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
networkCallback = new ConnectivityManager.NetworkCallback() {
#Override
public void onAvailable(Network network) {
super.onAvailable(network);
connectivityManager.bindProcessToNetwork(network);
Log.e(TAG,"onAvailable");
}
#Override
public void onLosing(#NonNull Network network, int maxMsToLive) {
super.onLosing(network, maxMsToLive);
Log.e(TAG,"onLosing");
}
#Override
public void onLost(Network network) {
super.onLost(network);
Log.e(TAG, "losing active connection");
}
#Override
public void onUnavailable() {
super.onUnavailable();
Log.e(TAG,"onUnavailable");
}
};
connectivityManager.requestNetwork(networkRequest,networkCallback);
}
}
So far what is working for me on the majority of devices I have tested with, with a fallback option to at least stop the dreaded 'looping request' and to allow a successful manual connection
The below code is written in Kotlin, please google how to covert to Java if needed.
Create a NetworkCallback which is required for API >= 29 (prior it was not required but could be used)
val networkCallback = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
super.onAvailable(network)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// To make sure that requests don't go over mobile data
connectivityManager.bindProcessToNetwork(network)
} else {
connectivityManager.setProcessDefaultNetwork(network)
}
}
override fun onLost(network: Network) {
super.onLost(network)
// This is to stop the looping request for OnePlus & Xiaomi models
connectivityManager.bindProcessToNetwork(null)
connectivityManager.unregisterNetworkCallback(networkCallback)
// Here you can have a fallback option to show a 'Please connect manually' page with an Intent to the Wifi settings
}
}
Connect to a network as follows:
val wifiNetworkSpecifier = WifiNetworkSpecifier.Builder()
.setSsid(ssid)
.setWpa2Passphrase(pass)
.build()
val networkRequest = NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
// Add the below 2 lines if the network should have internet capabilities.
// Adding/removing other capabilities has made no known difference so far
// .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
// .addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
.setNetworkSpecifier(wifiNetworkSpecifier)
.build()
connectivityManager.requestNetwork(networkRequest, networkCallback)
As stated here by Google, some OEM Roms are not 'holding on to the request' and therefore the connection is dropping instantly. OnePlus have fixed this problem in some of their later models but not all. This bug will continuously exist for certain phone models on certain Android builds, therefore a successful fallback (i.e. a manual connection with no network disruption) is required. No known workaround is available, but if found I will update it here as an option.
To remove the network, do the following:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//This is required for Xiaomi models for disconnecting
connectivityManager.bindProcessToNetwork(null)
} else {
connectivityManager.setProcessDefaultNetwork(null)
}
connectivityManager.unregisterNetworkCallback(it)
Please keep in mind, an automatic connection allows for an automatic & manual disconnection. A manual connection (such as the suggested fallback for OnePlus devices) does not allow an automatic disconnection. This will also need to be handled within the app for a better UX design when it comes to IoT devices.
Some extra small tips & info:
now that a system dialog opens, the app calls onPause and onResume respectively. This affected my logic regarding automatic connection to IoT devices. In some case, onResume is called before the network callback is finished.
In regards to tests, I have yet to be able to get around the dialog by just using espresso and it may block some tests that were working before API 29. It may be possible using other frameworks such as uiautomator. In my case I adjusted the tests to work up until the dialog shows, and run further tests thereafter.
Using Intents.init() does not work.
onUnavailable is called when the the network has been found, but the user cancels. It is not called when the network was not found or if the user cancels the dialog before the network has been found, in this case no other methods are called, use onResume to catch it.
when it fails on the OnePlus it called onAvailable() -> onCapabilitiesChanged() -> onBlockedStatusChanged (blocked: false) -> onCapabilitiesChanged() -> onLost() respectively
removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) wont help keep the connection on a OnePlus as stated here
setting the Bssid wont help keep the connection on a OnePlus as stated here
google cannot help, they have stated it is out of their hands here
OnePlus forum posts confirming it working for some models (but not all) after an update, see here, here & here
when GPS is switched off, the SSID names of networks are not available
if the dialog comes several times, check your own activity lifecycle, in my case some models were calling onResume before the network callback was received.
manually connecting to a network without internet capabilities needs user confirmation to keep the connection (sometimes in the form of a dialog or as a notification), if ignored, the system will disconnect from the network shortly afterwards
List of devices tested:
Google Pixel 2 - No issues found
Samsung S10 SM-G970F - No issues found
Samsung S9 SM-G960F - No issues found
One Plus A5000 (OxegenOS 10.0.1) - Major Issue with automatic connection
HTC One M8 (LineageOS 17.1) - No issues found
Xiaomi Mi Note 10 - Issue with disconnecting (Fixed, see code example)
Samsung A50 - Dialog repetitively appears after successful connection (sometimes)
Huawei Mate Pro 20 - Dialog repetitively appears after successful connection (sometimes)
Huawei P40 Lite - Doesn't call onLost()
CAT S62 Pro - No issues found
Sony Xperia SZ2 - No issues found
Samsung Note10 - No issues found
In case if you want to connect to WiFi with INTERNET, you should use this kind of NetworkRequest:
NetworkRequest request = new NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.setNetworkSpecifier(wifiNetworkSpecifier)
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
.build();
Also, you need specify default route for your process to make requests to connected WiFi AP permanently. Just add call of next method to your NetworkCallback under onAvaliable like this:
networkCallback = new ConnectivityManager.NetworkCallback() {
#Override
public void onAvailable(Network network) {
createNetworkRoute(network, connectivityManager);
}
};
if (connectivityManager!= null) connectivityManager.requestNetwork(request, networkCallback);
.
#RequiresApi(Build.VERSION_CODES.LOLLIPOP)
private static void createNetworkRoute(Network network, ConnectivityManager connectivityManager) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
connectivityManager.bindProcessToNetwork(network);
} else {
ConnectivityManager.setProcessDefaultNetwork(network);
}
}
Don't forget disconnect from the bound network:
connectivityManager.unregisterNetworkCallback(networkCallback);
Finally, you can find best practice in different libraries like WifiUtils.
You can try wifisuggestion api, I'm able to connect using them.
final WifiNetworkSuggestion suggestion1 =
new WifiNetworkSuggestion.Builder()
.setSsid("YOUR_SSID")
.setWpa2Passphrase("YOUR_PRE_SHARED_KEY")
.build();
final List<WifiNetworkSuggestion> suggestionsList =
new ArrayList<WifiNetworkSuggestion>();
suggestionsList.add(suggestion1);
WifiManager wifiManager =
(WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
int status = wifiManager.addNetworkSuggestions(suggestionsList);
if (status == 0 ){
Toast.makeText(this,"PSK network added",Toast.LENGTH_LONG).show();
Log.i(TAG, "PSK network added: "+status);
}else {
Toast.makeText(this,"PSK network not added",Toast.LENGTH_LONG).show();
Log.i(TAG, "PSK network not added: "+status);
}
Since Android 10, I've have to use the following code to connect to a specific wifi network.
private ConnectivityManager mConnectivityManager;
#Override
public void onCreate(#Nullable Bundle savedInstanceState){
// instantiate the connectivity manager
mConnectivityManager = (ConnectivityManager) this.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
}
public void connect(String ssid, String password) {
NetworkSpecifier networkSpecifier = new WifiNetworkSpecifier.Builder()
.setSsid(ssid)
.setWpa2Passphrase(password)
.setIsHiddenSsid(true) //specify if the network does not broadcast itself and OS must perform a forced scan in order to connect
.build();
NetworkRequest networkRequest = new NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.setNetworkSpecifier(networkSpecifier)
.build();
mConnectivityManager.requestNetwork(networkRequest, mNetworkCallback);
}
public void disconnectFromNetwork(){
//Unregistering network callback instance supplied to requestNetwork call disconnects phone from the connected network
mConnectivityManager.unregisterNetworkCallback(mNetworkCallback);
}
private ConnectivityManager.NetworkCallback mNetworkCallback = new ConnectivityManager.NetworkCallback(){
#Override
public void onAvailable(#NonNull Network network) {
super.onAvailable(network);
//phone is connected to wifi network
}
#Override
public void onLosing(#NonNull Network network, int maxMsToLive) {
super.onLosing(network, maxMsToLive);
//phone is about to lose connection to network
}
#Override
public void onLost(#NonNull Network network) {
super.onLost(network);
//phone lost connection to network
}
#Override
public void onUnavailable() {
super.onUnavailable();
//user cancelled wifi connection
}
};
References:
https://anutoshdatta.medium.com/new-wifi-apis-on-android-10-481c525108b7
https://developer.android.com/guide/topics/connectivity/wifi-suggest
I was also facing the same issue, even after 3 months I was unable to solve this. But I have found one awesome and cool solution.
startActivity(new Intent("android.settings.panel.action.INTERNET_CONNECTIVITY"))
Just add these lines instead of connecting to the wifi from the app, this will prompt user to select a wifi and connect and as soon as user do it, it will connect to the wifi and also it will have internet also.
Just connecting to the wifi from the app will not access the internet. Do this, this is the best solution.
So, the solution for me is compile your app with targetSdkVersion 28.
and for connection to wifi use this function
connectToWifi(String ssid, String key)
it's just a workaround for the moment, waiting Google to publish a fix for this bug, for more information the issue reported to Google : issuetracker.google.com/issues/138335744
public void connectToWifi(String ssid, String key) {
Log.e(TAG, "connection wifi pre Q");
WifiConfiguration wifiConfig = new WifiConfiguration();
wifiConfig.SSID = "\"" + ssid + "\"";
wifiConfig.preSharedKey = "\"" + key + "\"";
int netId = wifiManager.addNetwork(wifiConfig);
if (netId == -1) netId = getExistingNetworkId(wifiConfig.SSID);
wifiManager.disconnect();
wifiManager.enableNetwork(netId, true);
wifiManager.reconnect();
}
If you have root access (adb root):
Manually connect to the Wifi Network of your choosing.
Pull these ADB files:
adb pull /data/misc/wifi/WifiConfigStore.xml
adb pull /data/misc/wifi/WifiConfigStore.xml.encrypted-checksum
Save in a folder that would designate the Wifi Network:
Ex: GarageWifi
Ex: BusinessWifi
Copy to location of your choosing. Don't change the names of the files you pulled.
Whenever you want to connect to a desired wifi network:
adb push <location>\WifiConfigStore.xml /data/misc/wifi/
adb push <location>\WifiConfigStore.xml.encrypted-checksum /data/misc/wifi/
adb reboot
I'm establishing a connection to a specified network by ssid/pass using WifiNetworkSpecifier. Below is my code:
specifier = new WifiNetworkSpecifier.Builder()
.setSsid(this.ssid)
.setWpa2Passphrase(this.pass)
.build();
NetworkRequest networkRequest = new NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.addCapability(NetworkCapabilities.NET_CAPABILITY_TRUSTED)
.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)
.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN)
.removeCapability(NetworkCapabilities.NET_CAPABILITY_FOREGROUND)
.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_CONGESTED)
.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)
.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING)
.setNetworkSpecifier(specifier)
.build();
cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
callback = new ConnectivityManager.NetworkCallback() {
#Override
public void onUnavailable() {
[....]
}
#Override
public void onAvailable(#NonNull Network network) {
[....]
}
};
cm.requestNetwork(networkRequest, callback, TIMEOUT);
And here is my question. Can I auto connect to the only network available? The behaviour now is like this : a popup displayed with the only network available and I have to tap connect. I see it as an useless step for my app.
Mention: It is an internal app and I always have to be connected on my local wifi.
Thank you!
Since Android Q doesn't allow the WifiManager to add Networks, they gave the advise to use WifiNetworkSpecifier instead.
With the WifiNetworkSuggestionBuilder I was already able to display the notification on the statusbar, that user can join the network. But this API doesn't fulfill my requirements since that I don't the user to have to use the suggestion from the statusbar.
With WifiNetworkSpecifier I was also already able to display a popup about joining the network and the app also established a connection to the app. But that wifi connection seems only be available in the scope of the app. How is it possible to overcome this scope of the app, so other apps and for example also the browser is able to use this new established connection?
Below is my code
WifiNetworkSpecifier.Builder builder = new WifiNetworkSpecifier.Builder();
builder.setSsid("abcdefgh");
builder.setWpa2Passphrase("1234567890");
WifiNetworkSpecifier wifiNetworkSpecifier = builder.build();
NetworkRequest.Builder networkRequestBuilder = new NetworkRequest.Builder();
networkRequestBuilder.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
networkRequestBuilder.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED);
networkRequestBuilder.addCapability(NetworkCapabilities.NET_CAPABILITY_TRUSTED);
networkRequestBuilder.setNetworkSpecifier(wifiNetworkSpecifier);
NetworkRequest networkRequest = networkRequestBuilder.build();
ConnectivityManager cm = (ConnectivityManager) App.getInstance().getBaseContext().getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm != null) {
cm.requestNetwork(networkRequest, new ConnectivityManager.NetworkCallback() {
#Override
public void onAvailable(#NonNull Network network) {
//Use this network object to Send request.
//eg - Using OkHttp library to create a service request
super.onAvailable(network);
}
});
A bit late to the party, but maybe it will help someone else that encounters this problem.
It seems like you are right.
In android Q once the app is killed, the system automatically disconnects the WiFi network we've connected to through WifiNetworkSpecifier and there is no way to prevent the system from doing so.
The best solution I've come up with, is using WifiNetworkSpecifier with WifiNetworkSuggestion. This allows us to use WifiNetworkSpecifier while we are using our app, and suggest wifi networks for the system to auto connect to once the system disconnects from our WiFi due to the app being terminated.
Here is some sample code:
WifiNetworkSuggestion.Builder builder = new WifiNetworkSuggestion.Builder()
.setSsid("YOUR_SSID")
.setWpa2Passphrase("YOUR_PASSWORD")
WifiNetworkSuggestion suggestion = builder.build();
ArrayList<WifiNetworkSuggestion> list = new ArrayList<>();
list.add(suggestion);
WifiManager manager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
int status = manager.addNetworkSuggestions(list);
if (status == STATUS_NETWORK_SUGGESTIONS_SUCCESS) {
//We have successfully added our wifi for the system to consider
}
Cheers,
I tried this code its working fine
WifiNetworkSpecifier.Builder builder = new WifiNetworkSpecifier.Builder();
builder.setSsid("abcdefgh");
builder.setWpa2Passphrase("1234567890");
WifiNetworkSpecifier wifiNetworkSpecifier = builder.build();
NetworkRequest.Builder networkRequestBuilder = new NetworkRequest.Builder();
networkRequestBuilder.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
networkRequestBuilder.setNetworkSpecifier(wifiNetworkSpecifier);
NetworkRequest networkRequest = networkRequestBuilder.build();
ConnectivityManager cm = (ConnectivityManager)
App.getInstance().getBaseContext().getApplicationContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm != null) {
cm.requestNetwork(networkRequest, new ConnectivityManager.NetworkCallback() {
#Override
public void onAvailable(#NonNull Network network) {
super.onAvailable(network);
cm.bindProcessToNetwork(network)
}});
You must add this line for use internet. networkRequestBuilder.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
I want to do the following with my Android app:
I have a connected object that emits a Wi-fi network (soft AP) so my app can communicate with it
Connects to the local device on the network 192.168.0.1 which is emitting the Wi-fi
I want to open a socket to communicate with this device
socket = new Socket();
socket.setSoTimeout(10000);
socket.connect(new InetSocketAddress("192.168.0.1", 80), 5000);
This code works on most of my test devices, except on Nexus 6 (Android 7) I have the following cases
Case where it's not workking
Phone connected to Wifi AND connected to 3G/4G
-> Socket can't open!
Case where it's working
Phone connected to Wifi AND NOT connected to 3G/4F
--> Socket opens successfully!
What can I do programmatically to make it work in all cases?
I finally found the solution
final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkRequest.Builder req = new NetworkRequest.Builder();
req.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
cm.requestNetwork(req.build(), new ConnectivityManager.NetworkCallback() {
#Override
public void onAvailable(Network network) {
cm.unregisterNetworkCallback(this);
network.bindSocket(socket);
socket.setSoTimeout(SOCKET_TIMEOUT);
socket.connect(new InetSocketAddress(ip, port), CONNECTION_TIMEOUT);
}
}
});