is there a possiblity to explicitely use the wifi connection for doing Http Url requests?
In fact i just need to know if an internet connection (access to google.com for example) is possible via wifi.
(not via 2g / 3g / ..)
As far as I know, no. This is all abstracted from us by the platform.
But you can check to see if WIFI is available:
ConnectivityManager conMan = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
if(conMan!=null){
try {
NetworkInfo[] networkInfos = conMan.getAllNetworkInfo();
for(NetworkInfo ni : networkInfos){
if(ni.isAvailable() && ni.isConnected() && ni.getTypeName().equals("WIFI")){
result = true;
break;
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
You may find this useful:
public class ConnectivityHelper {
public static boolean isWiFiNetworkConnected(Context context) {
return getWiFiNetworkInfo(context).isConnected();
}
private static NetworkInfo getWiFiNetworkInfo(Context context) {
return getConnectivityManager(context).getNetworkInfo(ConnectivityManager.TYPE_WIFI);
}
private static ConnectivityManager getConnectivityManager(Context context) {
return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
}
}
I havent done this, so i'm not sure, but I found this looking through the documentation.
public boolean wifiAvailable() {
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = connMgr.getActiveNetworkInfo();
if((info.isAvailable() && info.isConnected() && (info.getType()==ConnectivityManager.TYPE_WIFI))) return true;
return false;
}
Where you are going to fire a request, evaluate this method, if it returns true the system will automatically use WiFi, android will always use wifi over 3G/2G when available AFAIK.
Related
So in this app, it is required to use some sort of network because there's API calls involved. There's an error that pops up when there's no mobile data around. The thing is, it also pops up when I turn the WiFi off, while the mobile data is still on. Is there a way to only have the error message pop up for the mobile data status only and not both the WiFi and mobile data. Here's the code I believe is verifying the network state.
public static boolean verifyNetWork(#NonNull Context context) {
ConnectivityManager cm = (ConnectivityManager)context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm == null) {
return false;
}
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}
Any help and advice is appreciated. Thanks
Note that you need to add the ACCESS_NETWORK_STATE permission to your app's AndroidManifest.xml file in order to use the ConnectivityManager class:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
To check for the availability of mobile data in an Android app, you can use the ConnectivityManager class provided by the Android framework.
public boolean isMobileDataAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected() && activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE;
}
You can then call this method in your code and check its return value to determine whether mobile data is available:
if (isMobileDataAvailable()) {
// Mobile data is available
} else {
// Mobile data is not available
}
Yes, the updated code I provided checks for both mobile data and Wi-Fi.
public boolean isMobileDataAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected() &&
(activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE ||
activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI);
}
One of the things android 10 is changing is that we cannot get READ_PHONE_STATE automatically,
And have to direct the user to manually give the permission by going to app info > permissions > phone > turn on.
is there any way to get network state (if the phone is on wifi / 3g, etc) on android 10 and above
Without directing the user to go to the application settings by himself and change the permission manually?
I was thinking to bypass the permission asking with
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkCapabilities caps = cm.getNetworkCapabilities(cm.getActivityNetwork());
boolean isMobile = caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR);
boolean isWifi = caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI);
would that be ok and then not needed to use the READ_PHONE_STATE permission ?
There is a class NetworkInfo it have a function
getTypeName() that return string value contain MOBILE or WIFI
I try to write function I hope it will be helpful for you :
/**
* #param mType : type of network connection "MOBILE" or "WIFI"
* #return : true of false
*/
public boolean isMyType(String mType) {
ConnectivityManager connectivityManager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
//
if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
return activeNetworkInfo.getTypeName().equals(mType);
} else {
// no internet connection
return false;
}
}
than you can call it :
boolean isMobile = isMyType("MOBILE");
boolean isWifi = isMyType("WIFI");
// for logcat debug
Log.i("typeNetwork", "is mobile :" + isMobile);
Log.i("typeNetwork", "is wifi :" + isWifi);
let me know if this works for you..
I am trying to detect if there are any active internet connections (WIFI or MOBILE INTERNET). The code is as follows:
private boolean haveNetwork() {
ConnectivityManager connMgr =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
boolean flag=false;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
for (Network network : connMgr.getAllNetworks()) {
NetworkInfo networkInfo = connMgr.getNetworkInfo(network);
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
flag=true;
break;
} else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
flag=true;
break;
}
}
}
Log.d("flag", String.valueOf(flag)); //returns true even if there's no internet connection
return flag;
}
As the title says, my connection status always remains to be true, even if there is no internet connection
What you have currently will only tell you if there is either a mobile or Wi-Fi network tracked by ConnectivityManager, not whether you are connected to it or not.
Since you appear to be doing this synchronously, you want to use these two methods:
ConnectivityManager.getActiveNetwork()
ConnectivityManager.getNetworkCapabilities(Network network)
You can use this if you want to call ConnectivityManager synchronously by replacing your for loop.
Network activeNetwork = connMgr.getActiveNetwork();
if (null == activeNetwork) {
return false;
}
NetworkCapabilities nc = connMgr.getNetworkCapabilities(activeNetwork);
return nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
&& nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
Use NetworkCapabilities as NetworkInfo is deprecated and check the getLinkDownstreamBandwidthKbps() is greater then 1kbps for 1g 32 kbps for at least 2g speed
I have been working on an android application.For one of the feature, I need the active network information(i.e. whether it's connected with Wi-Fi or mobile data). I got this piece of code from the internet.
NetworkInfo activeNetworkInfo = context.getSystemService(ConnectivityManager.class).getActiveNetworkInfo();
But this API is deprecated and I don't want to use any deprecated API.
After some more googling, I found that we should use ConnectivityManager.NetworkCallback instead. But I am not able to get an example of it. How can I use this?. Please help me if anyone having an idea about using ConnectivityManager.NetworkCallback
Check out this function in Kotlin
fun networkConnection(): Boolean {
var networkAvailable = false
val connectivityManager: ConnectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val network: Network = connectivityManager.activeNetwork!!
val networkCapabilities: NetworkCapabilities = connectivityManager.getNetworkCapabilities(network)!!
if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
networkAvailable = true
} else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
networkAvailable = true
} else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN)) {
networkAvailable = true
}
return networkAvailable
}
try the following code:
private void registerNetworkCallback(Context context) {
final ConnectivityManager manager =
(ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
manager.registerNetworkCallback(
new NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.addTransportType(NetworkCapabilities.TRANSPORT_ETHERNET)
.build(),
new NetworkCallback() {
#Override
public void onAvailable(Network network) {
/** here to get the available info
this ternary operation is not quite true, because non-metered
doesn't yet mean, that it's wifi
nevertheless, for simplicity let's assume that's true
*/
Log.i("vvv", "connected to " + (manager.isActiveNetworkMetered() ? "LTE" : "WIFI"));
}
#Override
public void onCapabilitiesChanged(Network network,
NetworkCapabilities networkCapabilities){
/**here to get the change network info
Value is TRANSPORT_CELLULAR, TRANSPORT_WIFI,
TRANSPORT_BLUETOOTH, TRANSPORT_ETHERNET, TRANSPORT_VPN
*/
if(networkCapabilities.hasTransport("type")){
}
}
});
}
connectivityManager = (ConnectivityManager)
context.getSystemService(ConnectivityManager.class);
#RequiresApi(api = Build.VERSION_CODES.M)
private void getActiveNet() {
Network currentNetwork = connectivityManager.getActiveNetwork();
}
Note that "active network" is synonymous in android with "default network".
ConnectivityManager#getActiveNetworkInfo()
Returns details about the currently active default data network...
ConnectivityManager#registerDefaultNetworkCallback(NetworkCallback)
Registers to receive notifications about changes in the application's
default network...
Therefore using ConnectivityManager#registerDefaultNetworkCallback(NetworkCallback) you can listen for default (aka "active") network changes. Unfortunately, this only returns the Network object which does not have information regarding transport (Wi-Fi vs Cellular) in which case you'll need to make an additional call to ConnectivityManager#getNetworkCapabilities(Network) to get that info.
Here is an example:
final ConnectivityManager connectivityManager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkCallback networkCallback = new NetworkCallback() {
#Override
void onAvailable(Network network) {
// Triggers when a default network is available.
NetworkCapabilities nc = connectivityManager.getNetworkCapabilities(network);
boolean isWifi = nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI);
boolean isCellular = nc.hasTransport(NetworkCapabilities. TRANSPORT_CELLULAR);
}
};
connectivityManager.registerDefaultNetworkCallback(networkCallback);
Does anyone know how to handle a ConnectTimeoutException? i'm posting variables to a url using AsyncTask but my internet connection is shocking so i'm recieving null data back because of a ConnectTimeoutException. What are the best ways to handle this for example if time out occurs try run again etc i have not had this problem before so don't have a clue how to handle but i feel it needs handling to improve user experience. so any ideas?
You could use an Handler to let your Activity know you got a ConnectTimeoutException
Catch this exception in your AsyncTask and send a message to your Handler (then do whatever you want)
Just for information, AsyncTask aren't designed for long running operation, if so you should use a Thread
this is how you shoud check for the network status
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
//execute your AsyncTask method
} else {
//maketoast..."No network connection available"
}
Make a separate class called Activity helper, and implement it in your async task for any class that you make in which requires a webservice call.
public class ActivityHelper {
public static final String NETWORK_CONNECTION_MESSAGE = "No Network Connection. Please make sure you have a Network Connection.";
public static boolean isNetworkPresent(Context applicationContext){
boolean hasService = false;
NetworkInfo info=(NetworkInfo)( (ConnectivityManager)applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
hasService = (info==null || !info.isConnected())?false:true;
return hasService;
}
}
call Activity Helper in "doInBackground" Method kinda like this..
private class YourAsyncTask extends AsyncTask<String, Void, String> {
Message message = new Message();
String type = "";
protected void onPreExecute() {
ActivityHelper.onUserInteraction(getApplicationContext());
dialog = ProgressDialog.show(LocationType.this,
"Connecting to server", "Please wait...", true, true);
dialog.setCancelable(false);
}
protected String doInBackground(final String... args) {
try {
if(!ActivityHelper.isNetworkPresent(getApplicationContext())){
message.what = ActivityHelper.NONETWORKCONNECTION;
return null;
}
} catch (Exception e) {
Log.e(this.getClass().getName(),
"Exception Message");
}
return null;
}