I have a socket that connects to a TCP server using either Wifi or 4G signal that receives a PING every 5 minutes from the server. But if I turn Wifi off on the device, I would like the socket to detect this and reconnect using a 4g signal.
I was wondering if there was a way to reconnect the socket automatically to 4G if I go out of the range of the wifi or if I turn wifi off?
Also is there a way to go the other way as well(From 4g to wifi if the wifi is available?
Register an inclass BroadCastReceiver to listen to WIFI on or off :
IntentFilter filter = new IntentFilter();
filter.addAction("android.net.wifi.supplicant.CONNECTION_CHANGE");
receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
boolean isConnected = intent.getBooleanExtra(WifiManager.EXTRA_SUPPLICANT_CONNECTED, false);
if (isConnected ) {
//Reconnect using Wifi.
} else {
//Reconnect using 4G.
}
}
}
registerReceiver(receiver, filter);
Dont forget to unregister the receiver:
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(receiver);
}
Regarding the EXTRA_SUPPLICANT_CONNECTED extra, the documentation states:
The lookup key for a boolean that indicates whether a connection to
the supplicant daemon has been gained or lost. true means a connection
now exists. Retrieve it with getBooleanExtra(String, boolean).
Constant Value: "connected"
Related
Phone A has mobile data ON and is sharing internet via Wi-Fi hotspot to Phone B. If Mobile Data is TURNED OFF in phone A, no connectivity change is received #PhoneB. How can I get this change in Phone B when mobile data is turned ON/OFF in Phone A?
Phone B is Android phone.
Yes there is. Simply register BroadcastReceiver for connectivity changes:
#Override
public void register(Context context) {
receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (isOnline()) {
if (listener != null) {
listener.onConnected();
}
hideNoConnectionError();
} else {
showNoConnectionError();
}
}
};
final IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
context.registerReceiver(receiver, intentFilter);
}
and on change event check whatever connectivity change there was
I'm trying to check if my BluetoothDevice is connected to something.
If it is connected, obtain the data of the other device
I want to implement this function to my application since I need to monitor if the connection was lost or is still connected and add a visual indicator in case the connection changes.
Tried with this function but the toast shows nearby devices (not connected) constantly:
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String name = device.getName();
Toast.makeText(getApplicationContext(),name,Toast.LENGTH_SHORT).show();
}
AFAIK there is no way to view the state of the connection. Instead you monitor for changes in the state of the bluetooth connection. So you can register a receiver and then receive a broadcast when the device is disconnected.
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
this.registerReceiver(rec, filter);
private BroadcastReceiver rec = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_DISCONNECTED.equals(action)) {
// Bluetooth is now disconnected
}
}
I want to check available networks bssids "just check no connecting" for that i use this code
wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
wifiManager.startScan();
IntentFilter filter = new IntentFilter();
filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
registerReceiver(myrec, filter);
------------------------
private BroadcastReceiver myrec=new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d(tag+" myrec","scan complete");
}
};
its work fine in many phone i tested but in galaxytab4 "smt231" in sleep mode not working and in normal mode take too long time to complete scan "more than 2 min" but when i go to settings>wifi my brodcast registered right away.
can anyone help me about this problem.
update
i found wifilock and now my code is
wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
_wifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_SCAN_ONLY, this.getClass().getName() + ".WIFI_LOCK");
_wifiLock.setReferenceCounted(true);
if(!_wifiLock.isHeld()){
_wifiLock.acquire();
}
wifiManager.startScan();
-----------------
private BroadcastReceiver myrec=new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d(tag+" myrec","scan complete");
}
};
but still not working in sleep mode.
and i am sure about running my code but scan reciver broadcast never going to run in sleep mode.
intersting thing is when you turn your wifi on even when your phone is in sleep mode when your going to range of known wifi network its going to connect to network and get notifications like emails. so its possible to check for wifi networks in sleep mode the thing is how?
I'm working on an app that searches for discoverable devices and displays them as buttons.
When calling startDiscovery() I would say it works 30% of the time, based on the way I'm currently debugging it, with the BroadcastReceiver and ACTION_DISCOVERY_FINISHED.
I'm also using isDiscovering() to test if the startDiscovery() function is called but it returns false.
Is there a way to know if startDiscovery() is called successfully? And can you identify something in my code that would make it not fail?
Obs.: I have both BLUETOOTH AND BLUETOOTH_ADMIN permissions.
Here is my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
String Address;
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Address = device.getAddress();
System.out.println("Found Address: " + Address ); //DEBUG
//Do something with Address
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
System.out.println("Discovery finished");
}
}
};
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
MainActivity.mBluetoothAdapter.startDiscovery();
if (MainActivity.mBluetoothAdapter.isDiscovering()) {
System.out.println("Discovering..."); //DEBUG
}
}
Although I have a few discoverable devices available, none of them trigger onReceive() with ACTION_FOUND
UPDATE: I went to "Scan" under Bluetooth Settings while the app was running and I could not scan for new devices. I disabled/enabled Bluetooth and returned to the app and the problem was resolved. I don't know if that indicates that the adapter is busy or halted somehow.
I confirm this issue.
On some telephones you just need to disable/active BT. You can doit programatically with
mBluetoothAdapter.disable();
mBluetoothAdapter.enable();
On some telephones its not enough ( Samsung S5 ). To detect it, I use timer, and if on end of timeout the change of BT broadcast state (BluetoothAdapter.ACTION_DISCOVERY_STARTED or BluetoothAdapter.ACTION_DISCOVERY_FINISHED ) wasnt received => its sign that BT is not working. Actually I show dialog which propose to user reboot the telephone.
In android how can my Activity will get to know if a Bluetooth A2DP device is connected to my device.
Is there any broadcast receiver for that?
How to write this broadcast receiver?
Starting from API 11 (Android 3.0) you can use BluetoothAdapter to discover devices connected to a specific bluetooth profile. I used the code below to discover a device by its name:
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile.ServiceListener() {
public void onServiceConnected(int profile, BluetoothProfile proxy) {
if (profile == BluetoothProfile.A2DP) {
boolean deviceConnected = false;
BluetoothA2dp btA2dp = (BluetoothA2dp) proxy;
List<BluetoothDevice> a2dpConnectedDevices = btA2dp.getConnectedDevices();
if (a2dpConnectedDevices.size() != 0) {
for (BluetoothDevice device : a2dpConnectedDevices) {
if (device.getName().contains("DEVICE_NAME")) {
deviceConnected = true;
}
}
}
if (!deviceConnected) {
Toast.makeText(getActivity(), "DEVICE NOT CONNECTED", Toast.LENGTH_SHORT).show();
}
mBluetoothAdapter.closeProfileProxy(BluetoothProfile.A2DP, btA2dp);
}
}
public void onServiceDisconnected(int profile) {
// TODO
}
};
mBluetoothAdapter.getProfileProxy(context, mProfileListener, BluetoothProfile.A2DP);
You can do that for every bluetooth profile. Take a look at Working with profiles in Android's guide.
However, as written in other answers, you can register a BroadcastReceiver to listen to connection events (like when you're working on android < 3.0).
You cannot get the list of connected devices by calling any API.
You need instead to listen to the intents ACTION_ACL_CONNECTED, ACTION_ACL_DISCONNECTED that notifies about devices being connected or disconnected.
No way to get the initial list of connected devices.
I had this problem in my app and the way I handle it (didn't find better...) is to bounce off/on the Bluetooth at application start to be sure to start with an empty list of connected devices, and then listen to the above intents.
muslidrikk's answer is broadly correct; however you can alternatively use fetchUUIDsWithSDP() and see what you get back... it's a bit of a hack though -- you'd have to know what UUIDs (capabilities) you could expect from the device, if it were turned on. And that might be difficult to guarantee.
For BluetoothHeadset specifically, you can call getConnectedDevices() to get connected devices for this specific profile.
Reference: http://developer.android.com/reference/android/bluetooth/BluetoothHeadset.html
Other cases you need to register a receiver for that.
In your activity, define broadcast receiver...
// Create a BroadcastReceiver for ACTION_FOUND
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show in a ListView
mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
};
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy