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

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

Related

Broadcast action for WIFI change

In my application I have to get notified whenever the device connects or disconnects from a WIFI network. For this I have to use a BroadcastReceiver but after reading through different articles and questions here on SO I'm a bit confused which Broadcast action I should use for this. In my opinion I have three choices:
SUPPLICANT_CONNECTION_CHANGE_ACTION
NETWORK_STATE_CHANGED_ACTION
CONNECTIVITY_ACTION
To reduce resources I really only want to get notified whenever the device is CONNECTED to a WIFI network (and it has received an IP address) or when the device has DISCONNECTED from one. I do not care about the other states like CONNECTING etc.
So what do you think is the best Broadcast action I should use for this? And do I have to manully filter the events (because I receieve more then CONNECTED and DISCONNECTED) in onReceive?
EDIT: As I pointed out in a comment below I think SUPPLICANT_CONNECTION_CHANGE_ACTION would be the best choice for me but it is never fired or received by my application. Others have the same problem with this broadcast but a real solution for this is never proposed (in fact other broadcasts are used). Any ideas for this?
You can go for WifiManager.NETWORK_STATE_CHANGED_ACTION works.
Register receiver with WifiManager.NETWORK_STATE_CHANGED_ACTION Action, either in Manifest or Fragment or Activity, which ever suited for you.
Override receiver :
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if(action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)){
NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
boolean connected = info.isConnected();
if (connected)
//call your method
}
}
Please try
#Override
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
filter.addAction("android.net.wifi.STATE_CHANGE");
registerReceiver(networkChangeReceiver, filter);
}
#Override
protected void onDestroy() {
unregisterReceiver(networkChangeReceiver);
super.onDestroy();
}
and
BroadcastReceiver networkChangeReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (!AppUtils.hasNetworkConnection(context)) {
showSnackBarToast(getNetworkErrorMessage());
}
}
};
I am using this and it is working for me. Hope it will help you out.

Search available wifi networks in sleep mode in android

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?

To check whether the wifi scan is complete

I'm writing a code for getting the information of all the access points in the range continuously.
Here is my code:
myRunnable = new Runnable() {
#Override public void run() {
while(){
wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.startScan();
List<ScanResult>results= wifi.getScanResults();
try{
//data Logging
}
}
}
};
myThread = new Thread(myRunnable);
myThread.start();
As the scanning and logging of data continuous repeatedly, i want to check whether the scan is complete before logging data.
Is there any flag or function which checks for wifi.startScan() is complete or not , before logging the data.
Could you please help me out with a code.
i want to check whether the scan is complete before logging data. Is
there any flag or function which checks for wifi.startScan() is
complete or not , before logging the data. Could you please help me
out with a code.
Yes, there is mechanizm designated for this purpose. To reach your goal you need to implement BroadcastReceiver that will listen for WiFi scans.
All what you need is to create BroadcastReceiver with appropriate IntentFilter. So you need this action for filter:
WifiManager.SCAN_RESULTS_AVAILABLE_ACTION
This action means that an access point scan has completed, and results are available. And then just create BroadcastReceiver (statically or dynamically, it's doesn't matter).
If you don't know how to start, look at this tutorial:
Android BroadcastReceiver Tutorial
To build up on the answers above, I just wanted to add the related code to give an example.
1. Registering for the event
// don't forget to set permission to manifest
wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
context.registerReceiver(this,new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
//check if WIFI is enabled and whether scanning launched
if(!wifiManager.isWifiEnabled() || !wifiManager.startScan())
{
throw new Exception("WIFI is not enabled");
}
2. Receiving the result
To receive, the object registered (in this case this) needs to extend BroadcastReceiver and implement the following method:
public void onReceive(Context context, Intent intent) {
List<ScanResult> result = wifiManager.getScanResults();
}
You need to implement a BroadcastReceiver listening for the scan results returned from WifiManager.startScan(). onReceive() allows you to access the scan results directly. It takes about 1 second for the scan to complete and trigger onReceive()...

Active wifi monitor in 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.

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