Active wifi monitor in Android - android

I am developing an Android app that should connect to a network and monitor the signal strength. I have achieved to connect and see the strength, but I donĀ“t know how to actively "hear" and display the strength. This is my method for monitoring:
public void search(View v) {
// Turn on wifi
if (!wifi.isWifiEnabled()) {
if (wifi.getWifiState() != WifiManager.WIFI_STATE_ENABLING) {
wifi.setWifiEnabled(true);
}
}
// Register the desired network
int nId = wifi.addNetwork(netConfig);
// create the BroadcastReciever
if (wifiReciever == null) {
wifiReciever = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action
.equals(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION)) {
if (intent.getBooleanExtra(
WifiManager.EXTRA_SUPPLICANT_CONNECTED, false)) {
message.setText("Connected: "
+ wifi.getConnectionInfo().getRssi());
} else {
message.setText("Disconnected...");
}
} else if (action.equals(WifiManager.RSSI_CHANGED_ACTION)) {
message.setText("Connected: "
+ wifi.getConnectionInfo().getRssi());
}
}
};
}
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
intentFilter.addAction(WifiManager.RSSI_CHANGED_ACTION);
registerReceiver(wifiReciever, intentFilter);
// intentamos conectarnos
wifi.enableNetwork(nId, true);
}
This code works sometimes, but it does not update the strength very often. Is there a API or any other methods/hidden apis for doing what I want to do?
Any help would be great!

Wifi signal strength (like current network activity, or CPU usage) is not a quantity that can be listened for without polling the sensor. Other wifi monitor apps simply poll at a user-defined interval. There is a substantial amount of noise and volatility in the wifi signal measurement, so you can't just wait for it to change. As far as I can tell, that intent is only broadcast when there is a substantial change in signal strength, and thus is not suitable for a live monitor.

Related

Is there a way to detect internet connectivity change when phone is connected to wifi over hotspot?

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

How to make the android Bluetooth keep scanning

Hi this is my first time posting.
Im making an android application that only discover Bluetooth device by using the friendly name and the mac address . Not pairing.
The problem im facing is my device fail to detect new device that enter the range after is start the scan about 10 to 12 second.
final BroadcastReceiver bReceiver = 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 the MAC address of the object to the arrayAdapter
// System.out.println(device.getAddress());
for(int i=0;i<listmac.size();i++)
{
if(listmac.get(i).equals(device.getAddress())){
System.out.println(listname.get(i));
myListView.setItemChecked(i, true);
}
}
}
}
};
public void find(View view) {
if (myBluetoothAdapter.isDiscovering()) {
// the button is pressed when it discovers, so cancel the discovery
myBluetoothAdapter.cancelDiscovery();
}
else {
myBluetoothAdapter.startDiscovery();
registerReceiver(bReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
isBreceiverRegisted = true;
}
}
public void off(){
myBluetoothAdapter.disable();
Toast.makeText(getApplicationContext(),"Bluetooth turned off",
Toast.LENGTH_LONG).show();
}
Sorry for my broke english
Simply because the discovery task has a timeout to prevent endless searched.
To be able to detect that discovery ended you need add this intent
if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
// When discovery is finished , start discovery again
myBluetoothAdapter.startDiscovery();
}
}
Be very careful in general about accidentally leaving your device in discovery-mode. Performing device discovery is a heavy procedure for the Bluetooth adapter and will consume a lot of its resources.

Android: Continuously seek for a specific WIFI Connection since boot completed

How can I check if a specific wifi connection is availible say for example SSID: Saaram01 is available. Whenever it is available I get notified.
I have done all this work through a button, like if you click the button it notifies if Saaram01 is available overwise does nothing.
The problem or the question basically is how can I check for this SSID availability everything 24/7.. Obviously for this I cant use a background service.. So is there anyother possible way to do it ?? Like using broadcast reciever or anything else ?
Any help will be highly appreciated !
Thank You.
IntentFilter i = new IntentFilter();
i.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent i) {
// TODO Auto-generated method stub
ScanWiFiActivity a = ScanWiFiActivity.instance();
WifiManager w = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
List<ScanResult> l = w.getScanResults();
a.Clear();
for (ScanResult r : l) {
if(r.SSID.equals("saaram01") {
//Perform your logic here
}
}
}
};
registerReceiver(receiver, i);
n the FOR block work your magic and take action when you identify your network by SSID or BSSID

Is there any other way to discover Bluetooth apart from using BroadcastReceiver?

I have created a BroadcastReceiver for BluetoothDevice.ACTION_FOUND in a Service to scan and Log the Bluetooth Device available. Part of this Service is to keep on checking every 30 seconds if the any of the previously found bluetooth devices is still available or not. Currently it throws me an error for Leaked IntendReceiver, I can fix that error, however I am just not convinced this is the right way to do this.
I am creating a new thread to handle bluetooth scanning, creating a while loop which runs every 30 seconds and inside that loop registering the BroadcastReceiver, putting thread on sleep, by the time sleep time is over the onReceive gives me results of the current scan, then I unregister BroadcastReceiver and repeat the loop.
I am unregistering the BroadcastReceiver after every single completion of while loop because the next scan gives me list of currently available devices and then I compare that with previous scan's data.
It is fulfilling my requirement however I have a strong feeling that its not the correct design. Could you please advice me on an alternate approach? Thanks..
Below is the relevant code from the Service-
class ScanBT extends Thread
{
static final long DELAYBT = 30000;
#Override
public void run()
{
isBTRunning = true;
Looper.prepare();
BluetoothAdapter mBluetoothAdapter =BluetoothAdapter.getDefaultAdapter();
try {
Log.d(TAG, "BT Scanning started");
while(isBTRunning)
{
if (!mBluetoothAdapter.isEnabled())
{
mBluetoothAdapter.enable();
Thread.sleep(15000);
}
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
mBluetoothAdapter.startDiscovery();
Log.d(TAG,"Inside while loop for BT");
Thread.sleep(DELAYBT);
unregisterReceiver(mReceiver);
}
Looper.loop();
}
catch (InterruptedException e) {
Log.d(TAG, "BT Scanning stopped");
Looper.myLooper().quit();
}
}
}
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);
BTDevice = device.getName();
BTAddress = device.getAddress();
Log.d(TAG,"BT Found name: " + BTDevice);
Log.d(TAG,"BT Found address: " + BTAddress);
//Code to compare with previous scan results
}
}
};
Figured it out. There is no other way to achieve this. To keep the performance under control, I am now registering the receiver only once and then starting the discovery inside a loop with a sleep interval of 60 seconds.

How to detect if bluetooth device is connected

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

Categories

Resources