Cant ping wan IP programatically in android - android

I'm working with connecting and retrieving data from IP in android. To check whether IP is online before retrieving data, I'm pinging IP using InetAddress.getByName(hostName).isReachable(20000). It's working fine for LAN, But for WAN, getting timeOut.
Any help is appreciated!!

try {
boolean b = InetAddress.getByName(hostname).isReachable(40000);
}
catch (Exception e)
{
e.printStackTrace();
}
you have to add this 20000 milllisecod to 40000 milliseconds..
so this is paramter if you not reach your network at 20000 then you got timeout..
I hope its useful to you.

Related

Android call method but don't work on wifi but work on gprs

we work with xamarin android and visual studio 2015.
we have an app who works since several months fine :)
This app when it starts call a webservice for to retrieve some data in json format.
All work fine, but last week we have a problem and we are COMPLETY lost about it !
Since last week, for one device when it call the web service we receive this error in the catch exception :
unable to read data from the transport connection Connection reset by peer ...
Here is it the method on the device who call the WS:
public override HttpResult ExecuteGet(Uri target)
{
var client = new HttpClient();
client.MaxResponseContentBufferSize = 25600000;
try
{
var response = client.GetAsync(target).Result;
if (response.IsSuccessStatusCode)
{
var content = response.Content.ReadAsStringAsync().Result;
return new HttpResult(content, null, null);
}
return new HttpResult(null, " ERROR MESSAGE ", response.StatusCode.ToString());
}
catch (Exception e)
{
return new HttpResult(null, " ERROR MESSAGE", e.Message);
}
}
well, now with the same device if we stop the wifi and call the webservice in GPRS that work.
Also we have two wifi, we also have noticed if the device connect on the second wifi and try to call the web service => that's work !
After talk with some colleague, they tell me to look to update my android version of the device , or wifi app on the device but for me the first thing we need to do will be to compare wifi 1 and wifi 2.
My question is, how i can compare two wifi ?
All suggestion are welcome because we search and we find nothing ...
Thanks for all guys that's really great to share your knowledge ...

rfcomm bluetooth on google glass

I am having an Android-App [1] which I partly want to port to google-glass - this app uses bluetooth rfcomm. Now I am facing the following problem: when I use my connection code I see a pairing dialog on glass - showing me a large number and asks for a tap to confirm. But this is strange - as I usually have to enter my 4 digit pin on the phone - also I am getting auth problems ( smells like it is caused by not letting me enter the PIN )
Anyone using bluetooth-rfcomm on google-glass?
[1] https://github.com/ligi/DUBwise
I was having the exact problem like this! In this post I put my complete solution to this problem.
But basically the pairing is done like this:
In the BroadcastReceiver
if(BluetoothDevice.ACTION_PAIRING_REQUEST.equals(action)){
BluetoothDevice device = ListDev.get(selectedDevice);
byte[] pinBytes = getStrFromName(device.getName(),7,11).getBytes(); // My devices had their own pin in their name, you can put a constant pin here or ask for one...
try {
Method m = device.getClass().getMethod("setPin", byte[].class);
m.invoke(device, pinBytes);
try {
device.getClass().getMethod("setPairingConfirmation", boolean.class).invoke(device, true);
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
So the pin is set automatically in this example, but you can always ask for a pin to the user.
Hope it helps!

Android, internet connection and no answer for ordinary calling

I wrote simple application, for my Galaxy SII, for permanent connection with remote server. Ones for 5 second it sends and receives data. While application is working nobody can't call to me. Network answers him - interlocutor is unavailable.
The same happend me when I use mail client like K-9. It doesn't matter I use GPRS or 3G connection.
What is a main rule (if is it?) to construct internet application to avoid this problem (I mean problem with ordinary incomming phone connection)?
My ordinary code for sending data (in remote service) is like this:
While (condition)
{
try {
Thread.sleep(500);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
out.write(data + "\n");
out.flush();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Regards,
Artik
First, if you want to wait for 5 seconds you should use Thread.sleep(5000); not Thread.sleep(500); which is half a second.
Second, consider sending your data to the server using Timer instead of Thread.sleep() and while(condition)
After modifying your code with the above suggestions, try to test from the emulator and simulate a phone call.

Android - Detect if Wifi Requires Browser Login

My university has an open wifi access point, however it requires you to enter your e-mail before it allows you to use the web. My problem is that the Wifi is stupid in that it seems to drop my connection and force me to enter my e-mail again every 10 minutes.
I wanted to create my own app that I can use to automatically do this step for me, but I cannot seem to find any documentation for a nice and easy way to detect if a Wifi access point has a browser login page. Is there a way in Android to get this information, or is it just to see if my connection to something is always redirected to 1.1.1.1?
See the "Handling Network Sign-On" section of the HttpUrlConnection documentation:
Some Wi-Fi networks block Internet access until the user clicks through a sign-on page. Such sign-on pages are typically presented by using HTTP redirects. You can use getURL() to test if your connection has been unexpectedly redirected. This check is not valid until after the response headers have been received, which you can trigger by calling getHeaderFields() or getInputStream().
They have a snippet of sample code there. Whether this will cover your particular WiFi AP, I can't say, but it is worth a shot.
Ping an external IP address (like google.com) to see if it responds.
try {
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("ping -c 1 " + "google.com");
proc.waitFor();
int exitCode = proc.exitValue();
if(exitCode == 0) {
Log.d("Ping", "Ping successful!";
} else {
Log.d("Ping", "Ping unsuccessful.");
}
}
catch (IOException e) {}
catch (InterruptedException e) {}
The only downside is this would also indicate that a web login is required when there is simply no internet connectivity on the WiFi access point.
#CommonsWare I believe this is a better answer than opening a UrlConnection and checking the host, since the host doesn't always change even when displaying the redirect page. For example, I tested on a Belkin router and it leaves whatever you typed in the browser as is, but still displays its own page. urlConnection.getUrl().getHost() returns what it should because of this.
I think #FlyWheel is on the right path, but I would use http://clients1.google.com/generate_204 and if you don't get a 204, you know you are behind a captive portal. You can run this in a loop until you do get a 204 in which case you know you are not behind a captive portal anymore.
#FlyWheel wrote: The only downside is this would also indicate that a web login is required when there is simply no internet connectivity on the WiFi access point.
You can solve this by registering a receiver to android.net.conn.CONNECTIVITY_CHANGE. You can check if Wifi is ON and is connected by looking at the Supplicant State of the connection.
Here is a snippet, but I didn't run it:
WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wm.getConnectionInfo();
SupplicantState suppState = wifiInfo.getSupplicantState();
if (wm.isWifiEnabled()) {
if (suppState == SupplicantState.COMPLETED){
// TODO - while loop checking generate_204 (FlyWheels code)Using intent service.
}
}
I can't remember if the SupplicantState is COMPLETED or ASSOCIATED, you will have to check that. You should use an IntentService for checking the generate_204 since broadcast receivers have a short lifetime.
I used the following code using google's 204 endpoint.
private boolean networkAvailable() {
ConnectivityManager mManager = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
if(mManager != null) {
NetworkInfo activeNetwork = mManager.getActiveNetworkInfo();
if(activeNetwork== null || !activeNetwork.isConnectedOrConnecting()){
return false;
}
}
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://clients1.google.com/generate_204")
.build();
try {
Response response = client.newCall(request).execute();
if(response.code() != 204)
return false; // meaning it either responded with a captive html page or did a redirection to captive portal.
return true;
} catch (IOException e) {
return true;
}
}
Many applications including Google Chrome use http://clients1.google.com/generate_204 to verify that the the connection is not locked under captive portal.
The issue might rather be - today at least - that newer Android versions (5.1+?) keep the 3G/4G connection up and running until the wifi login actually leads to a fully functional wifi connection.
I haven't tried it, but maybe with the enum value CAPTIVE_PORTAL_CHECK of NetworkInfos DetailedState one can try to detect such a mode properly?

Android Bluetooth - source code

I have been strugling with a Bluetooth project on Android for weeks. Does anyone know where I can go to see the actual code that's used by Google to make their Bluetooth pairing and connection logic work?
I have been through all the documentaiton, the BluetoothChat application (which doesn't work as advertised ... tried it on 3 different handsets), as well as a bunch of other sites on the net, but still no luck. I need to get an app up and running on 2.1 or higher.
Any advice or help is greatly appreciated.
Yes the Bluetooth project didn't work for me also because the code for socket connection is not working
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
if (secure) {
tmp = device.createRfcommSocketToServiceRecord(
MY_UUID_SECURE);
} else {
tmp = device.createInsecureRfcommSocketToServiceRecord(
MY_UUID_INSECURE);
}
} catch (IOException e) {
Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e);
}
this is not working ...
replace this by the following code
BluetoothDevice hxm = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(device.getAddress());
Method m;
m = hxm.getClass().getMethod("createRfcommSocket", new Class[]{int.class});
socket = (BluetoothSocket)m.invoke(hxm, Integer.valueOf(1));
Ah, if you're having issues with application level code I'm not sure staring at the Bluetooth manager source will be much help, but here you go: https://android.googlesource.com/platform/packages/apps/Bluetooth the Bluetooth manager app code.
I'll re-iterate it: this is honestly probably not going to be helpful for what you want. You should be able to get a reasonably working Bluetooth app without having to look at this.
EDIT: if you want the code that implements the Bluetooth packages (android.bluetooth), see https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/bluetooth for that.
You can browse all the android.bluetooth package around here:
http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.1.1_r1/android/bluetooth/BluetoothClass.java#BluetoothClass

Categories

Resources