I'm developing a simple app for my school which will show you the newest updates from the website, but checking the internet connection seems a little problem in AIR.
I'll be more specific:
I'm using Adobe Flash CS6 to develop the app (Using AIR for android)
The app contains a menu, and the "internet frame", of which the code doesn't really work.
I've tried a couple of things already: URLMonitor(like is available = true), URLLoader(and cathing the IOError if it occurs when there's no internet connection) and something like HTMLLoader (long time ago :P, no success)
The URLLoader works "fine", but I also need to know if the webpage just isn't available (404) when there IS an active internet connection, but in either those cases it will just throw the same "stream error" , so I can distinguish them. That's why it doesn't suit my needs.
The URLMonitor also works "fine", but here comes to problem:
When testing the app on the emulator, it can without a problem detect that there is no internet connection. BUT, when exporting to .apk and running on my android device, it won't succeed in detecting the internet connectivity.
Here's my code:
var monitor:URLMonitor = new URLMonitor(new URLRequest("http://www.google.nl"));
monitor.addEventListener(StatusEvent.STATUS, netConnectivity);
monitor.start();
function netConnectivity(e:StatusEvent):void
{
if(e.target.available)
{
//checking the content
output_txt.text += "\ninternet available";
loader = new URLLoader(new URLRequest(webURL));
loader.addEventListener(IOErrorEvent.IO_ERROR, onIOErrorLoader);
loader.addEventListener(Event.COMPLETE, onCompleteLoader);
}
else
{
//
//
// NO INTERNET CONNECTION AVAILABLE!
//
//
output_txt.text += "\nno internet available";
popupnoconnection_mc.alpha = 100;
popupnoconnection_mc.play();
popupnoconnection_mc.addEventListener(MouseEvent.MOUSE_DOWN, BackToMenu);
}
monitor.stop();
}
As you can see, it adds an EventListener to the URLMonitor, starts the checking, and the function checks the availability of the internet connection. WORKS ON THE EMULATOR, NOT PROPERLY ON MY DEVICE.
What's even more interesting:
What DOES work on my device, is when the internet IS connected. It will just show the text in my output field, but it won't when there is no internet connection!
Also, when lauching the app with an internet connection set up, then entering this frame, then going back to the main menu, then turning the internet off, and then entering this frame again, this code suddently works great!
So it has got to do something with the creation of the URLMonitor, and checking the connection at the same frame I guess, but I need a little hand here!
I think this can't be too difficult!
Thank you so much in advance! (sorry for typos)
You can use NetworkInfo to detect whether there is an internet connection - it works on Android.
Related
I have an Android VPN application. When I fire the intent to start the VPN (via VPNService.prepare), it fails immediately if there's an always-on VPN already configured on the device. That seems reasonable, but I'd like to be able to easily detect that case, so I can show a helpful message to the user.
By 'always on' I mean the specific VPN always-on Android VPN flag: https://developer.android.com/guide/topics/connectivity/vpn#always-on
I can't seem to find a way to access that info, even though it is used internally in Android (e.g. here but that getAlwaysOnVpnPackage doesn't seem to be available publicly AFAICT).
The best option I've seen is Check if a VPN connection is active in Android?, which will tell you if any VPN connection is currently active, but that's not enough, because:
I don't want to know about temporary VPN connections: I'm only interested if it's an always-on VPN connection.
Sometimes 'always-on' connections aren't actually always on. If you have a disconnected connection and set it as 'always-on', it's configured as such, and blocks all other VPN installs, but there's no network connection created (Android shows a persistent warning instead, which takes you to the other app to activate the connection). Because there's no connection, the above technique doesn't work. I still need to detect this case, since it still blocks my VPN setup.
Is there any way to check whether the device currently has a VPN configured as 'always-on'?
You can use this method
private fun isVpnAlwaysOn(): Boolean {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
val alwaysOn = Settings.Secure.getString(contentResolver, "always_on_vpn_app")
return !alwaysOn.isNullOrEmpty()
} else false
}
'alwaysOn' contains the package name of the app for which always-on is configured.
In the end, it seems this isn't possible on a normal device any way that I can find. I think is possible if you're a device admin, but that requires managed enterprise devices etc.
For now, I've handled this by watching for near-instant (less than 200ms) VPN setup failures (between running startActivityForResult(vpnIntent) and receiving onActivityResult with RESULT_CANCELED) and then showing a helpful message in that case.
Full implementation is in https://github.com/httptoolkit/httptoolkit-android/commit/928fbf92a4f868042789471be0d42800a226194b in case you're trying to do the same.
My app connects to an external device using it's WiFi (the device works as a server). With introduction of Android 10 I needed to implement separate WiFi connectivity flow for different plaftorms (WifiNetworkSpecifier for Android 10+ and wifiManager.enableNetwork for < Android 10). The connectivity flow itself works fine, but I have some problems with stream communication.
In the app I have the ability to upload files to that external device. To do that I need to use HttpURLConnection. So I run:
val url = URL(UPDATE_FIRMWARE_URL)
val connection = (url.openConnection() as HttpURLConnection)
with(connection) {
doInput = true
doOutput = true
useCaches = false
requestMethod = METHOD_POST
//setRequestProperty(HEADER_CONNECTION, "Keep-Alive")
setRequestProperty("Connection", "close")
connectTimeout = 6000
setRequestProperty(HEADER_USER_AGENT, "Android Multipart HTTP Client 1.0")
setRequestProperty(HEADER_CONTENT_TYPE, "multipart/form-data; boundary=$boundary")
}
connection.connect()
val outputStream = connection.outputStream
DataOutputStream(outputStream).use { outputStream ->
// actual file upload
}
Now, the actual update consists of two files, and after first upload the device restarts, and I need to reconnect to it's wifi and upload the second file.
On Android < 9 the entire upload flow (with two files) works fine but on Android 10, after I send the first file and reconnect to the device's WiFi, when I call connection.connect() I get ConnectExcpetion with internal cause connect failed: ENETUNREACH (Network is unreachable) (which really makes no sense, cause I'm connected to that network...)
java.net.ConnectException: Failed to connect to (...)
at com.android.okhttp.internal.io.RealConnection.connectSocket(RealConnection.java:1409)
at com.android.okhttp.internal.io.RealConnection.connect(RealConnection.java:1359)
at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:221)
at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:144)
at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:106)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:400)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:333)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:483)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:135)
Initially I had a problem also with connecting for the first time on Android 10, but I found this article, and adding the connectTimeout helped, but now the connection still fails when I try to connect for the second (and every next) time. The only thing that helps is restaring the entire app (which is no real solution).
What may be the problem, that the next connections fail despite I always execute the same code?
After a few days I finally found an answer to my question. It turns out that on Android 10 when you connect to the Access Point that does not offer the internet (eg. my external device) the standard API calls (using Retrofit) works fine, but when trying to use HttpURLConnection the system tries to use some network with internet connection, and as there is none, the connection fails.
The only way for the connection to work is to force the system to use our network by using ConnectivityManager.bindProcessToNetwork(network). This solution was proposed here and I've got no idea why someone downvoted that answer. It's correct.
What's interesting is that if we connect to the no-internet network via device settings, the connection works just fine even without binding.
I'm using Connectivity library to see the internet(Wifi or network data) is active and saving the data in Storage if there is no connectivity(Offline) and synchronize with server when connected to internet. I'm having issues in public places where the internet is consistently unstable(esp. in basements, offices, stores, Coffee shops etc., where there is internet connects in and out). When I check the Connectivity is active but by the time I started synchronizing internet goes offline (Something like this). this leads inconsistent /partial updates to the server. Also, in coffee shops and Airports where wifi gets connected but there will be "Agree Terms and Conditions" page to connect. Not all the browsers will take you to that page directly after joining the Wifi. In that case I see the wifi is active in Mobile but actually it is not activated until I accept the terms and Conditions in IE or some specific browser. Any one else having difficulty in handling these kind of issue from Mobile App?
My App - Hangs on Login screen if I'm trying to login when there is in-stable/in consistent internet.It thinks wifi is there but not.
IF I'm on a screen where I will display list, screen will show blank for infinite time. Adding timeout for server request/response or something will help such scenario.
I know I'm not handling this case in code to show some kind of error message but I need some guidance to detect these conditions suing CN1 API to handle through my app.Please advise.
Code:
public boolean isOffline() {
if (Connectivity.isConnected() && forceOffline) {
relogin();
}
return forceOffline || !Connectivity.isConnected();
}
The problem is that it's impossible to detect online/offline properly as you might be connected to a local wifi/network but it might be a bad connection that won't let you reach the server. As far as the library is concerned you are connected... But in reality you don't have a connection.
First set the timeout values in NetworkManager to lower values to improve the experience although this won't solve a situation where data starts downloading and stops in the middle.
Next you need to handle these cases one by one and provide the user with a way to toggle the offline mode. Unfortunately there is no silver bullet for network reliability. You just need to go through every path and try to detect these things.
I'm studying Xamarin for two weeks now and I'm following the Xamarin.University course (Consuming REST-based Web Services (XAM150)). In an exercise we have to simply check the connection of the phone. My emulator (Android 7.0) in Visual Studio 2017 does it very well. But when I try on my actual phone (Android 7.1) using Xamarin Live Player, the app will not start and the following Error appears on my phone:
"Visualization Error. Index was outside the bounds of the array.
(IndexOutOfRangeExeption)"
I've searched Google and the forum of Xamarin.University but no luck, it seems that no one else has this problem. When I debug, it stops at when it checks the connectivity. I use the Xam.Plugin.Connectivity for asking the connection and yes, it is referenced in all the parts of the project.
I've come from using this code from the site:
using Plugin.Connectivity;
public App() {
// The root page of your application
MainPage = CrossConnectivity.Current.IsConnected
? (Page) new NetworkViewPage()
: new NoNetworkPage();
}
To this to debug:
using Plugin.Connectivity;
public App() {
InitializeComponent();
try {
var isConnected = CrossConnectivity.Current.IsConnected;
MainPage = isConnected
? (Page)new NetworkViewPage()
: (Page)new NoNetworkPage();
} catch (Exception e) {
throw e;
}
//MainPage = new NetworkViewPage();
}
All this code works for my emulator, but not for my phone. I can display the different pages on my phone but not when I check for the connectivity so the error is really from the plugin and not from my pages.
Has someone any idea what I can try to make this work?
Frauke Nonnenmacher pointed out that it could be a problem with Xamarin Live Player and apparantly that is the issue. If I implement it on my phone with USB debugging, it works just fine. It didn't occur to me that Live Player could be the issue since Xamarin.University wants you to use it and I didn't find anybody on the forum there that had the same problem.
My guess is that checking the connection gives a problem with Xamarin Live Player because it works over the network, you can't use the Player if you don't have a wifi connection. So maybe something goes wrong there.
It is still a mystery why it doesn't work, but a workaround is just USB debugging.
I am attempting to get Google Nearby API working on my handset (an s5).
I am building and running the stock project from github Google Nearby API GIT.
The app builds and runs, with no errors. Having exported the app onto two S5s (amongst other handsets I have attempted to test it with) and connecting to a WLAN from a D-Link DSL-3680. Multicasting is enabled and set to v3.
However the app refuses to connect with the neighbouring phone when corresponding 'advertise' and 'discover' instructions have been given.
Is there an effective way in which to debug this behaviour? If I can provide an effective information dump of information that might help someone identify the issue then please let me know how.
What do you mean by 'refuse to connect'?
are you getting connection status- 'Rejected'?
If you are able to advertise and discover other devices, I'm assuming all your base conditions (like connected to local network) are fulfilled
Now,
You can try logging your status in Connection call back when you try to connect
Nearby.Connections.sendConnectionRequest(mGoogleApiClient, myName,
remoteEndpointId, myPayload, new Connections.ConnectionResponseCallback() {//response conditions}
using--
inside connection callback function write
if(status.isSuccess()){
// Successful connection
} else {
// Failed connection
}
similarly, if you are not doing this, you need to accept the connection request
Nearby.Connections.acceptConnectionRequest(mGoogleApiClient, remoteEndpointId, myPayload, this)
and inside Onresult callback add-
if(status.isSuccess()){
// Successful connection
} else {
// Failed connection
}
Hope it helped