Checking server availability doesn't work - android

I'm trying to check if server is available but when running this code I get error that server is not available or sometimes application freezes even server is properly running:
InetAddress in;
in = null;
try {
in = InetAddress.getByAddress(new byte[] { (byte)192, (byte)168, (byte)16, (byte)48});
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if (in.isReachable(5000)) {
loadProduct();
} else
{
showAlertBox("Warning", "Server not available!");
}
} catch (IOException e) {
showAlertBox("Warning", "Server not available!");
}
Is there any better way to check if server is online?

Is there any better way to check if server is online
Yes. Try to connect to it. That is an infallible test. Don't do it until you need to, of course. Don't try to predict the future. Just connect and handle the failure.

I have tried with this
Socket socket = null;
boolean reachable = false;
try {
socket = new Socket("192.168.16.48", 80);
reachable = true;
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
showAlertBox("Warning", "Server not available!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
showAlertBox("Warning", "Server not available!");
} finally {
if (socket != null) try { socket.close(); } catch(IOException e) { }
}
It works, but sometimes I get meesage that that applications is not responding, even if socket timeout is adjusted.

You can try to locate the server using its host name. The advantage: unlike the dynamic ip address, the host name probably has a longer validity. In the following example, both network interfaces can refer to the same host.
byte[] b = { 10, 0, 0, 1 };
String name = "Hostname";
InetAddress ia = Inet4Address.getByAddress(b);
InetAddress ia2 = Inet4Address.getByName(name);
Another possible solution: before using network operations on android, you must get the corresponding permissions from the android manifest. I don't know exactly, which of the following are must-haves:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />

Related

How to find if the device is configured as a portable hotspot

I can't find in the doc how to retrieve if device is configured as a portable hotspot.
I've read How to detect if a network is (configured as) a mobile hotspot on Android? but I don't know if the feature has been implemented?
You can use below code to check if Tethering is enabled or not on your device:
private static Method isWifiApEnabledMethod;
public static boolean isWifiApEnabled(WifiManager wifiManager) {
if (isWifiApEnabledMethod == null) {
try {
isWifiApEnabledMethod = wifiManager.getClass().getDeclaredMethod("isWifiApEnabled");
isWifiApEnabledMethod.setAccessible(true); //in the case of visibility change in future APIs
} catch (NoSuchMethodException e) {
Log.w(TAG, "Can't get method by reflection", e);
}
}
if (isWifiApEnabledMethod != null) {
try {
return (Boolean) isWifiApEnabledMethod.invoke(wifiManager);
} catch (IllegalAccessException e) {
Log.e(TAG, "Can't invoke method by reflection", e);
} catch (InvocationTargetException e) {
Log.e(TAG, "Can't invoke method by reflection", e);
}
}
return false;
}
Don't forget to add below permission in AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
For the SO link mentioned above in question:
This feature is not available i.e. has not been implemented.
For more information check this link where Google officially marked the status as Status: Won't Fix (Obsolete)
Hope this will help you. Thanks!

Is it possible to make an L2CAP socket connection by using Bluetooth?

I have a collection of bluetooth earpieces and wanted to be able to connect directly to their AVRCP profile.
The main sticking point is that there is no publicly accessible way to construction an L2CAP socket.
In theory the code below ought to work, but I am getting a permssion denied error.
I do have these in my manifest:
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
The code snippet is here:
private BluetoothSocket createL2CAP(BluetoothDevice bd, UUID uuid) {
BluetoothSocket result = null;
try {
c=BluetoothSocket.class.getDeclaredConstructor(int.class,int.class,boolean.class,boolean.class, BluetoothDevice.class,int.class,ParcelUuid.class);
result=(BluetoothSocket) c.newInstance(BluetoothSocket.TYPE_L2CAP, -1, true, true, bd, -1, new ParcelUuid(uuid));
} catch (NoSuchMethodException e) {
addln("BluetoothSocket: No Such Constructor");
} catch (IllegalAccessException e) {
addln("BluetoothSocket: Illegal access");
} catch (InvocationTargetException e) {
addln("BluetoothSocket: Target exception "+e.getMessage());
} catch (InstantiationException e) {
addln("BluetoothSocket: "+e.getMessage());
}
return result;
}
It's finding the constructor, but throwing the IllegalAccessException.
Has anyone had any luck persuading Android Bluetooth to make any connection type other than RFCOMM? And/or is there a different approach which may have more success?
(PS: addln is just sending messages to a textview so I can see what is happening)

InetAddress.getLocalHost() is always crashing

I'm developing an android app which I want it to display all the IP addresses on the network, I have used it in a java application which works well but when I use it in an android app it crashes when it arrives at InetAddress.getLocalHost(), can this work on an android app or is there another way to do it?
code
InetAddress localhost = null;
try {
localhost = InetAddress.getLocalHost(); // it crashes here
System.out.println("after");
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
System.out.println("the application stoped here");
e1.printStackTrace();
}
System.out.println("3");
// this code assumes IPv4 is used
byte[] ip = localhost.getAddress();
for (int i = 0; i <= 254; i++) {
ip[3] = (byte) i;
InetAddress address = null;
try {
address = InetAddress.getByAddress(ip);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
PingThread p = new PingThread(address);
p.start();
}
You can solve this problem by adding this to your code before the try/catch:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
...and this to your AndroidManifest file:
<uses-permission android:name="android.permission.INTERNET" >
</uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" >
</uses-permission>
Refer to the Android Docs for more details about the StrictMode.

Android application is freezed - Socket Exception

I made android application that connects to remote server and send some data.
Remote server is Windows application.
Connection method:
private void ConnectToMonitor() {
try {
s = new Socket(SERVER_ADDRESS, TCP_SERVER_PORT);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
This works perfectly if server is online. Application is sending data and server is receiving. But if server is offline android app. is blocked. My question is how to handle this? How to continue with application and avoid error even the server is down?
Remember to call this outside the UIThread.
Follow this tutorial. In android all connections need to be managed outside the UIThread, in the tutorial I linked you will find easy ways to post your results back to the UI (handlers, asynctasks...)
Of course we don't know if the problem is about the thread with just the given code, but it is the most usual error.
First remember to set the socket timeout :
mSocket.setSoTimeout(timeout); //in milliseconds
You can however specify different timeout for connection and for all other I/O operations through the socket:
private void connectToMonitor() {
try {
socket = new Socket();
InetAddress[] iNetAddress = InetAddress.getAllByName(SERVER_ADDRESS);
SocketAddress address = new InetSocketAddress(iNetAddress[0], TCP_SERVER_PORT);
socket.setSoTimeout(10000); //timeout for all other I/O operations, 10s for example
socket.connect(address, 20000); //timeout for attempting connection, 20 s
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Second, in Android, you should perform any network I/O in separate threads!
As an example, using regular Java Threads :
String threadName = getClass().getName() + "::connect";
new Thread(new Runnable() {
#Override
public void run() {
connectToMonitor();
}
}, threadName).start();
You can set A timeout for the socket. Use Socket.setSoTimeout method
socket.setSoTimeout(timesinmilis);
by using this your socket will throw a socket timout exception. You can catch that and do what you want

Android connect to Blackberry 655+ bluetooth headset

I'm trying to write a test app which connects to BlackBerry 655+ bluetooth headset. Basically what i want to do in this app is connect to the headset and catch button pressures on it. I think that could be done by reading the socket's inputstream. Anyway, i get some errors right when i try to connect to the socket. Here's the code:
BluetoothSocket tmp = null;
try {
tmp = mDevice.createRfcommSocketToServiceRecord(
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
} catch(IOException e) {}
mSocket = tmp;
mBtAdapter.cancelDiscovery();
try {
mSocket.connect(); // THIS ONE GIVES A "Service discovery failed" exception
} catch (IOException e1) {
Method m = null;
try {
m = mDevice.getClass().getMethod(
"createRfcommSocket", new Class[] {int.class});
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
try {
tmp = (BluetoothSocket) m.invoke(mDevice, 1);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
mSocket = tmp;
try {
mSocket.connect(); // THIS ONE GIVES A "Connection refused" EXCEPTION
} catch (IOException e) {
e.printStackTrace();
}
}
What am i doing wrong? I already tried different ports in the m.invoke(mDevice, X) instruction but it always gives "Connection refused"
I worked with Bluetooth before but with python and Java ME so I understand the basics. I don't know much about the android API though.
Where did you get the UUID code from? That could be one of the reasons for the Service discovery failed.
Each bluetooth device may have several services each of them associated to one port (or channel). If you are running ubuntu try using the hci tools to know to which channel connect or which service to search for.
Here you have an official list with UUIDs from Bluetooth SIG. For Headset Profile the UUID is 0x1108, the UUID used by you it is Base Universally Unique Identifier and it is used for SDP.

Categories

Resources