Multi Networking in Lollipop - android

I am working on an app that saves your credentials and logs in to the university wifi automatically when connected to a particular ssid. Everything is working fine. But when mobile data is on and wifi gets connected, the login request is sent through the mobile data (since the wifi connection is not active).
I read on the documentation and tried this.
if(Build.VERSION.SDK_INT >= 21){
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkRequest.Builder requestBuilder = new NetworkRequest.Builder();
requestBuilder.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
connectivityManager.registerNetworkCallback(requestBuilder.build(), new ConnectivityManager.NetworkCallback() {
#Override
public void onAvailable(Network network) {
ConnectivityManager.setProcessDefaultNetwork(network);
}
});
}
new LoginTask().execute();
This doesn't solve my problem.
Any suggestions?

I solved this problem myself.
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
Network[] networks = connectivityManager.getAllNetworks();
NetworkInfo networkInfo;
Network network;
for (int i = 0; i < networks.length; i++){
network = networks[i];
networkInfo = connectivityManager.getNetworkInfo(network);
if ((networkInfo.getType() == ConnectivityManager.TYPE_WIFI) && (networkInfo.getState().equals(NetworkInfo.State.CONNECTED))) {
ConnectivityManager.setProcessDefaultNetwork(network);
break;
}
}

Related

How to check if still connected to the network set by setProcessDefaultNetwork()

I have the following code that sets the default network of my internet connection.
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
NetworkRequest.Builder builder = new NetworkRequest.Builder();
builder.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
builder.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);
NetworkCallback networkCallback = new NetworkCallback() {
#Override
public void onAvailable(Network network) {
boolean result = ConnectivityManager.setProcessDefaultNetwork(network);
Log.d(TAG, "success? " + result);
}
};
NetworkRequest networkRequest = builder.build();
connMgr.requestNetwork(networkRequest, networkCallback);
connMgr.registerNetworkCallback(networkRequest, networkCallback);
}
This works properly. However, later on, when I check using the following code:
ConnectivityManager connMgr = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfoMobile =
connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
networkInfoMobile.isConnected(); // returns false!
This always returns false. What am I doing wrong?
What I did is I saved the network provided by onAvailable() callback. Then later, I checked the connectivity thru:
NetworkInfo networkInfo = connMgr.getNetworkInfo(networkFromOnAvailable);
networkInfo.isConnected();
Cheers!

request wifi and lte on same time in android

I have to use WiFi and lte at the same time on Android.
Using ConnectivityManager, I was able to send a request via lte while wifi was active
However, I never used the two at the same time.
I currently use these methods.
private static ConnectivityManager cm;
private static NetworkRequest.Builder req;
cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
req = new NetworkRequest.Builder();
req.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
req.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);
cm.requestNetwork(req.build(), new ConnectivityManager.NetworkCallback() {
#Override
public void onAvailable(Network network) {
//here you can use bindProcessToNetwork
cm.bindProcessToNetwork(network);
}
});
Is there a way I can request wifi and lte at the same time?
You can use onAvailable() of NetworkCallback to check for network changes.
In addition, bindProcessToNetwork() declares that only certain networks will be used.
Use ConnectivityManager.getAllNetworks() with the my simple example below.
ConnectivityManager connectivityManager = (ConnectivityManager) getApplicationContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
Network []networks = connectivityManager.getAllNetworks();
for(int i = 0 ; i < networks.length ; i++) {
NetworkInfo info = connectivityManager.getNetworkInfo(networks[i]);
if(info.getTypeName().equals("MOBILE")) {
// This is mobile network (3G/LTE)
// Use networks[i].bindSocket(java.net.Socket) for low-level socket communication
// Use networks[i].openConnection(java.net.URL) for HTTP request
}
else if(info.getTypeName().equals("WIFI")) {
// This is WiFi network
// Use networks[i].bindSocket(java.net.Socket) for low-level socket communication
// Use networks[i].openConnection(java.net.URL) for HTTP request
}
else {
// This is another network (WIFI_P2P, Ethernet, Bluetooth, ...)
}
}

Cannot get android app to detect wifi connections [duplicate]

I don't want my user to even try downloading something unless they have Wi-Fi connected. However, I can only seem to be able to tell if Wi-Fi is enabled, but they could still have a 3G connection.
android.net.wifi.WifiManager m = (WifiManager) getSystemService(WIFI_SERVICE);
android.net.wifi.SupplicantState s = m.getConnectionInfo().getSupplicantState();
NetworkInfo.DetailedState state = WifiInfo.getDetailedStateOf(s);
if (state != NetworkInfo.DetailedState.CONNECTED) {
return false;
}
However, the state is not what I would expect. Even though Wi-Fi is connected, I am getting OBTAINING_IPADDR as the state.
You should be able to use the ConnectivityManager to get the state of the Wi-Fi adapter. From there you can check if it is connected or even available.
ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mWifi.isConnected()) {
// Do whatever
}
NOTE: It should be noted (for us n00bies here) that you need to add
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
to your
AndroidManifest.xml for this to work.
NOTE2: public NetworkInfo getNetworkInfo (int networkType) is now deprecated:
This method was deprecated in API level 23. This method does not
support multiple connected networks of the same type. Use
getAllNetworks() and getNetworkInfo(android.net.Network) instead.
NOTE3: public static final int TYPE_WIFI is now deprecated:
This constant was deprecated in API level 28.
Applications should instead use NetworkCapabilities.hasTransport(int) or requestNetwork(NetworkRequest, NetworkCallback) to request an appropriate network. for supported transports.
Since the method NetworkInfo.isConnected() is now deprecated in API-23, here is a method which detects if the Wi-Fi adapter is on and also connected to an access point using WifiManager instead:
private boolean checkWifiOnAndConnected() {
WifiManager wifiMgr = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if (wifiMgr.isWifiEnabled()) { // Wi-Fi adapter is ON
WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
if( wifiInfo.getNetworkId() == -1 ){
return false; // Not connected to an access point
}
return true; // Connected to an access point
}
else {
return false; // Wi-Fi adapter is OFF
}
}
I simply use the following:
SupplicantState supState;
wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
supState = wifiInfo.getSupplicantState();
Which will return one of these states at the time you call getSupplicantState();
ASSOCIATED - Association completed.
ASSOCIATING - Trying to associate with
an access point.
COMPLETED - All authentication
completed.
DISCONNECTED - This state indicates
that client is not associated, but is
likely to start looking for an access
point.
DORMANT - An Android-added state that
is reported when a client issues an
explicit DISCONNECT command.
FOUR_WAY_HANDSHAKE - WPA 4-Way Key
Handshake in progress.
GROUP_HANDSHAKE - WPA Group Key
Handshake in progress.
INACTIVE - Inactive state.
INVALID - A pseudo-state that should
normally never be seen.
SCANNING - Scanning for a network.
UNINITIALIZED - No connection.
I am using this in my apps to check if the active network is Wi-Fi:
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni != null && ni.getType() == ConnectivityManager.TYPE_WIFI)
{
// Do your work here
}
I had a look at a few questions like this and came up with this:
ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo wifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo mobile = connManager .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifi.isConnected()){
// If Wi-Fi connected
}
if (mobile.isConnected()) {
// If Internet connected
}
I use if for my license check in Root Toolbox PRO, and it seems to work great.
The NetworkInfo class is deprecated as of API level 29, along with the related access methods like ConnectivityManager#getNetworkInfo() and ConnectivityManager#getActiveNetworkInfo().
The documentation now suggests people to use the ConnectivityManager.NetworkCallback API for asynchronized callback monitoring, or use ConnectivityManager#getNetworkCapabilities or ConnectivityManager#getLinkProperties for synchronized access of network information
Callers should instead use the ConnectivityManager.NetworkCallback API to learn about connectivity changes, or switch to use ConnectivityManager#getNetworkCapabilities or ConnectivityManager#getLinkProperties to get information synchronously.
To check if WiFi is connected, here's the code that I use:
Kotlin:
val connMgr = applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
connMgr?: return false
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val network: Network = connMgr.activeNetwork ?: return false
val capabilities = connMgr.getNetworkCapabilities(network)
return capabilities != null && capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
} else {
val networkInfo = connMgr.activeNetworkInfo ?: return false
return networkInfo.isConnected && networkInfo.type == ConnectivityManager.TYPE_WIFI
}
Java:
ConnectivityManager connMgr = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
if (connMgr == null) {
return false;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Network network = connMgr.getActiveNetwork();
if (network == null) return false;
NetworkCapabilities capabilities = connMgr.getNetworkCapabilities(network);
return capabilities != null && capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI);
} else {
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
return networkInfo.isConnected() && networkInfo.getType() == ConnectivityManager.TYPE_WIFI;
}
Remember to also add permission ACCESS_NETWORK_STATE to your Manifest file.
While Jason's answer is correct, nowadays getNetWorkInfo (int) is a deprecated method. So, the next function would be a nice alternative:
public static boolean isWifiAvailable (Context context)
{
boolean br = false;
ConnectivityManager cm = null;
NetworkInfo ni = null;
cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
ni = cm.getActiveNetworkInfo();
br = ((null != ni) && (ni.isConnected()) && (ni.getType() == ConnectivityManager.TYPE_WIFI));
return br;
}
Many of answers use deprecated code, or code available on higer API versions. Now I use something like this
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivityManager != null) {
for (Network net : connectivityManager.getAllNetworks()) {
NetworkCapabilities nc = connectivityManager.getNetworkCapabilities(net);
if (nc != null && nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
&& nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET))
return true;
}
}
return false;
The following code (in Kotlin) works from API 21 until at least current API version (API 29).
The function getWifiState() returns one of 3 possible values for the WiFi network state:
Disable, EnabledNotConnected and Connected that were defined in an enum class.
This allows to take more granular decisions like informing the user to enable WiFi or, if already enabled, to connect to one of the available networks.
But if all that is needed is a boolean indicating if the WiFi interface is connected to a network, then the other function isWifiConnected() will give you that. It uses the previous one and compares the result to Connected.
It's inspired in some of the previous answers but trying to solve the problems introduced by the evolution of Android API's or the slowly increasing availability of IP V6.
The trick was to use:
wifiManager.connectionInfo.bssid != null
instead of:
getIpAddress() == 0 that is only valid for IP V4 or
getNetworkId() == -1 that now requires another special permission (Location)
According to the documentation: https://developer.android.com/reference/kotlin/android/net/wifi/WifiInfo.html#getbssid
it will return null if not connected to a network. And even if we do not have permission to get the real value, it will still return something other than null if we are connected.
Also have the following in mind:
On releases before android.os.Build.VERSION_CODES#N, this object
should only be obtained from an Context#getApplicationContext(), and
not from any other derived context to avoid memory leaks within the
calling process.
In the Manifest, do not forget to add:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
Proposed code is:
class MyViewModel(application: Application) : AndroidViewModel(application) {
// Get application context
private val myAppContext: Context = getApplication<Application>().applicationContext
// Define the different possible states for the WiFi Connection
internal enum class WifiState {
Disabled, // WiFi is not enabled
EnabledNotConnected, // WiFi is enabled but we are not connected to any WiFi network
Connected, // Connected to a WiFi network
}
// Get the current state of the WiFi network
private fun getWifiState() : WifiState {
val wifiManager : WifiManager = myAppContext.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
return if (wifiManager.isWifiEnabled) {
if (wifiManager.connectionInfo.bssid != null)
WifiState.Connected
else
WifiState.EnabledNotConnected
} else {
WifiState.Disabled
}
}
// Returns true if we are connected to a WiFi network
private fun isWiFiConnected() : Boolean {
return (getWifiState() == WifiState.Connected)
}
}
Using WifiManager you can do:
WifiManager wifi = (WifiManager) getSystemService (Context.WIFI_SERVICE);
if (wifi.getConnectionInfo().getNetworkId() != -1) {/* connected */}
The method getNeworkId returns -1 only when it's not connected to a network;
ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
boolean is3g = manager.getNetworkInfo(
ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting();
boolean isWifi = manager.getNetworkInfo(
ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();
Log.v("", is3g + " ConnectivityManager Test " + isWifi);
if (!is3g && !isWifi) {
Toast.makeText(
getApplicationContext(),
"Please make sure, your network connection is ON ",
Toast.LENGTH_LONG).show();
}
else {
// Put your function() to go further;
}
This works for Android devices before and after Q
fun isWifiConnected(context: Context):Boolean {
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val capabilities = cm.getNetworkCapabilities(cm.activeNetwork)
capabilities?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)==true
} else {
val activeNetwork: NetworkInfo? = cm.activeNetworkInfo
activeNetwork?.typeName?.contains("wifi",ignoreCase = true)?:false
}
}
Try out this method.
public boolean isInternetConnected() {
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
boolean ret = true;
if (conMgr != null) {
NetworkInfo i = conMgr.getActiveNetworkInfo();
if (i != null) {
if (!i.isConnected()) {
ret = false;
}
if (!i.isAvailable()) {
ret = false;
}
}
if (i == null)
ret = false;
} else
ret = false;
return ret;
}
This method will help to find internet connection available or not.
This works for me:
ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// Mobile
State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
// Wi-Fi
State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
// And then use it like this:
if (mobile == NetworkInfo.State.CONNECTED || mobile == NetworkInfo.State.CONNECTING)
{
Toast.makeText(Wifi_Gprs.this,"Mobile is Enabled :) ....",Toast.LENGTH_LONG).show();
}
else if (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING)
{
Toast.makeText(Wifi_Gprs.this,"Wifi is Enabled :) ....",Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(Wifi_Gprs.this,"No Wifi or Gprs Enabled :( ....",Toast.LENGTH_LONG).show();
}
And add this permission:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Similar to #Jason Knight answer, but in Kotlin way:
val connManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
if (mWifi.isConnected) {
// Do whatever
}
Here is what I use as a utility method in my apps:
public static boolean isDeviceOnWifi(final Context context) {
ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
return mWifi != null && mWifi.isConnectedOrConnecting();
}
In new version Android
private void getWifiInfo(Context context) {
ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
Network[] networks = connManager.getAllNetworks();
if(networks == null || networks.length == 0)
return;
for( int i = 0; i < networks.length; i++) {
Network ntk = networks[i];
NetworkInfo ntkInfo = connManager.getNetworkInfo(ntk);
if (ntkInfo.getType() == ConnectivityManager.TYPE_WIFI && ntkInfo.isConnected() ) {
final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
if (connectionInfo != null) {
// add some code here
}
}
}
}
and add premission too
This is an easier solution. See Stack Overflow
question Checking Wi-Fi enabled or not on Android.
P.S. Do not forget to add the code to the manifest.xml file to allow permission. As shown below.
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" >
</uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" >
</uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" >
</uses-permission>
Try
wifiManager.getConnectionInfo().getIpAddress()
This returns 0 until the device has a usable connection (on my machine, a Samsung SM-T280, Android 5.1.1).
You can turn WIFI on if it's not activated as the following
1. check WIFI state as answered by #Jason Knight
2. if not activated, activate it
don't forget to add WIFI permission in the manifest file
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Your Java class should be like that
public class TestApp extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//check WIFI activation
ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mWifi.isConnected() == false) {
showWIFIDisabledAlertToUser();
}
else {
Toast.makeText(this, "WIFI is Enabled in your devide", Toast.LENGTH_SHORT).show();
}
}
private void showWIFIDisabledAlertToUser(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("WIFI is disabled in your device. Would you like to enable it?")
.setCancelable(false)
.setPositiveButton("Goto Settings Page To Enable WIFI",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
Intent callGPSSettingIntent = new Intent(
Settings.ACTION_WIFI_SETTINGS);
startActivity(callGPSSettingIntent);
}
});
alertDialogBuilder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
}
Add this for JAVA:
public boolean CheckWifiConnection() {
ConnectivityManager conMgr = (ConnectivityManager) getSystemService (Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected()) {
return true;
} else {
return false;
}
}
in Manifest file add the following permissions:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Kind of old a question but this is what i use. requires min api level 21 also takes in consideration deprecated Networkinfo apis.
boolean isWifiConn = false;
ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Network network = connMgr.getActiveNetwork();
if (network == null) return false;
NetworkCapabilities capabilities = connMgr.getNetworkCapabilities(network);
if(capabilities != null && capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)){
isWifiConn = true;
Toast.makeText(context,"Wifi connected Api >= "+Build.VERSION_CODES.M,Toast.LENGTH_LONG).show();
}else{
Toast.makeText(context,"Wifi not connected Api >= "+Build.VERSION_CODES.M,Toast.LENGTH_LONG).show();
}
} else {
for (Network network : connMgr.getAllNetworks()) {
NetworkInfo networkInfo = connMgr.getNetworkInfo(network);
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI && networkInfo.isConnected()) {
isWifiConn = true;
Toast.makeText(context,"Wifi connected ",Toast.LENGTH_LONG).show();
break;
}else{
Toast.makeText(context,"Wifi not connected ",Toast.LENGTH_LONG).show();
}
}
}
return isWifiConn;
val wifi = context!!.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager?
if (wifi!!.isWifiEnabled)
//do action here
else
//do action here
This works with the latest versions of android:
fun getConnectionType(context: Context): ConnectivityType {
var result = NONE
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (cm != null) {
val capabilities = cm.getNetworkCapabilities(cm.activeNetwork)
if (capabilities != null) {
when {
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> {
result = WIFI
}
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> {
result = MOBILE_DATA
}
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN) -> {
result = VPN
}
}
}
}
} else {
if (cm != null) {
val activeNetwork = cm.activeNetworkInfo
if (activeNetwork != null) {
// connected to the internet
when (activeNetwork.type) {
ConnectivityManager.TYPE_WIFI -> {
result = WIFI
}
ConnectivityManager.TYPE_MOBILE -> {
result = MOBILE_DATA
}
ConnectivityManager.TYPE_VPN -> {
result = VPN
}
}
}
}
}
return result
}
enum class ConnectivityType {
NONE,
MOBILE_DATA,
WIFI,
VPN,
}
And in the manifest:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Access internet through mobile data when wifi is connected to OBD in marshmallow

I have both WIFI and mobile data enabled. In wifi I have connected to an OBD which has no internet connection but will stream some data if connected. In order to start that stream I used the below code:
ConnectivityManager connectivityManager = (ConnectivityManager) getCurrentActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = connectivityManager.getActiveNetworkInfo();
if (SDK_INT >= LOLLIPOP) {
NetworkRequest.Builder request = new NetworkRequest.Builder();
request.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
connectivityManager.registerNetworkCallback(request.build(), new ConnectivityManager.NetworkCallback() {
#Override
public void onAvailable(Network network) {
if (SDK_INT >= LOLLIPOP && SDK_INT < M) {
ConnectivityManager.setProcessDefaultNetwork(network);
} else if (SDK_INT >= M) {
connectivityManager.bindProcessToNetwork(network);
}
}
});
}
I got the code from this answer.
How to stay connected through mobile network after WIFI is connected on Android?
When it comes to get the active network into at connectivityManager.getActiveNetworkInfo() I get the network type as MOBILE[LTE]. Once it hits the onAvailable method, whenever I try to get the active network type it says WIFI[].
After this the stream gets started. Now I want the mobile data to be activated again since it is enabled. So I tried the same code after the stream started by just replacing TRANSPORT_WIFI with TRANSPORT_CELLULAR in request.addTransportType.
ConnectivityManager connectivityManager = (ConnectivityManager) getCurrentActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = connectivityManager.getActiveNetworkInfo();
if (SDK_INT >= LOLLIPOP) {
NetworkRequest.Builder request = new NetworkRequest.Builder();
request.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);
connectivityManager.registerNetworkCallback(request.build(), new ConnectivityManager.NetworkCallback() {
#Override
public void onAvailable(Network network) {
if (SDK_INT >= LOLLIPOP && SDK_INT < M) {
ConnectivityManager.setProcessDefaultNetwork(network);
} else if (SDK_INT >= M) {
connectivityManager.bindProcessToNetwork(network);
}
}
});
}
What happens is, when I debug this process, NetworkInfo always has the WIFI connection even after it hits the onAvailable method.
Please pinpoint if I was wrong somewhere or am I missing something.

How to know if wifi is connected with new Android Lollipop wifi management

I need to connect my mobile by wifi to a connected device. This hot spot have not internet.
Before 5.0 I did like this to check if I was connected to the wifi
ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if(mWifi.isConnected()&& wifiManager.getConnectionInfo().getNetworkId()==addedNetwork)
But now with the 5.0 version of android, when I check isConnected it always returns false because of the none connectivity to internet.
How can I manage this case ?
Regards
I haven't tried this out but as per the google docs this should work
ConnectivityManager cManager = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkRequest.Builder builder = new Builder();
//Indicates that this network should be able to reach the internet.
builder.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
NetworkRequest build = builder.build();
cManager.requestNetwork(build, new NetworkCallback() {
#Override
public void onAvailable(Network network) {
super.onAvailable(network);
// do what you want to do here
}
});`

Categories

Resources