Broadcast Receiver get notified when connecting to another wifi network - android

I'm trying to get notified when my phone connects to a new Wifi network.
This is my BroadcastReceiver's logic:
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Bundle extras = intent.getExtras();
if (extras != null) {
for (String key : extras.keySet()) {
if(key.equals("networkInfo")){
NetworkInfo info = (NetworkInfo) extras.get(key);
if(info.getType() == ConnectivityManager.TYPE_WIFI){
if(info.getState().toString().equals("CONNECTED")){
//do stuff
}
}
}
}
}
}
}
This works fine when I turn on my Wifi and connect to a new network. But my problem is that when I'm already connected to a Wifi network and then connect to another one then nothing happens.
What is the right Actoin that I should add to my IntentFilter in order to achieve that?
EDIT
This code works fine. The problem was that the WifiReceiver was being unregistered.

Please try this solution,
BroadcastReceiver broadcastReceiver = new WifiBroadcastReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
context.registerReceiver(broadcastReceiver, intentFilter);
You need to check the MAC addresses of the routers to check if there is a change in the Wifi connection.
public class WifiBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WifiManager.SUPPLICANT_STATE_CHANGED_ACTION .equals(action)) {
SupplicantState state = intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE);
if (SupplicantState.isValidState(state)
&& state == SupplicantState.COMPLETED) {
boolean changed = checkWifiChanged();
}
}
}
/** Detect if WiFi is changed. */
private boolean checkWifiChanged() {
boolean changed = false;
// You can store the previous MAC address in Shared Preferences and fetch it here
String previousMacAddress = getPreviousMacAddress();
WifiManager wifiManager =
(WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifi = wifiManager.getConnectionInfo();
if (wifi != null) {
// Get current router MAC address
String bssid = wifi.getBSSID();
changed = !previousMacAddress.equals(bssid);
}
return changed;
}
}
You can store the previous MAC address in a database or Shared Preference and check the new connected MAC address with the previous one. If they are different, then the WiFi connection has changed otherwise not.

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

Android WIFI How To Detect When Specific WIFI Connection is Available

I need to detect when I have network connectivity to a SPECIFIC WIFI network.
For example: As soon as you walk into your house, and your phone picks up your home WiFi network, I would like a notification that says "You are not at your home network, would you like to connect to you Home?" But I would like that to only happen when I am at my specific house.
What should I listen for and what tests should I do to make sure it is my specific home network, and not another network?
You can use BroadcastReceiver to find out that wifi network has changed:
BroadcastReceiver broadcastReceiver = new WifiBroadcastReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
context.registerReceiver(broadcastReceiver, intentFilter);
The BroadcastReceiver may look like this.
And to check for specific MAC address see the checkConnectedToDesiredWifi() method bellow.
public class WifiBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WifiManager.SUPPLICANT_STATE_CHANGED_ACTION .equals(action)) {
SupplicantState state = intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE);
if (SupplicantState.isValidState(state)
&& state == SupplicantState.COMPLETED) {
boolean connected = checkConnectedToDesiredWifi();
}
}
}
/** Detect you are connected to a specific network. */
private boolean checkConnectedToDesiredWifi() {
boolean connected = false;
String desiredMacAddress = "router mac address";
WifiManager wifiManager =
(WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifi = wifiManager.getConnectionInfo();
if (wifi != null) {
// get current router Mac address
String bssid = wifi.getBSSID();
connected = desiredMacAddress.equals(bssid);
}
return connected;
}
}
As long, as we are nothing like code as you need, for free service, I can only recommend you, to read everything possible about Android and its Network/Wifi possibilities, when creating such app.
Sources you should read up and study
http://developer.android.com/reference/android/net/wifi/package-summary.html
how to see if wifi is connected in android
How to get my wifi hotspot ssid in my current android system
How to get name of wifi-network out of android using android API?
Get Wifi Interface name on Android
Permissions you should ask for when creating application manifest
AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
(the last one, only if you want it to detect your location, to prevent unnecessary calls)
You should also declare, that your application needs wifi to be available in device, to work properly:
AndroidManifest.xml
<uses-feature android:name="android.hardware.wifi" />
Use the standard code to list all available networks:
start the scan
String connectivity_context = Context.WIFI_SERVICE;
final WifiManager wifi = (WifiManager) getSystemService(connectivity_context);
if (wifi.isWifiEnabled()) {
wifi.startScan();
}
register a receiver for the data
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) {
//use r.SSID or r.BSSID to identify your home network and take action
a.setText(r.SSID + "" + r.level + "\r\n");
}
}
};
registerReceiver(receiver, i);
In the FOR block work your magic and take action when you identify your network by SSID or BSSID
I had exactly the same problem for a project of mine and it took a while to find a solution.
First of all, "connecting to a WiFi" is something very abstract, and it turns out rightly so. In practice, people usually mean all of the following:
authenticated with a WiFi access point
associated with the access point
got an ip address from the network
All these stages (and several more) are associated with different Andoid events. So, without further ado, here is my (slightly modified) code:
public class MyService extends Activity { // or Service
//... Other stuff
BroadcastReceiver awaitIPAddress = null;
private final BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION)) {
if (intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE) == SupplicantState.COMPLETED) {
//WiFi is associated
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wi = wifiManager.getConnectionInfo();
if (wi != null) {
// Wifi info available (should be, we are associated)
if (wi.getIpAddress() != 0) {
// Lucky us, we already have an ip address.
// This happens when a connection is complete, e.g. after rekeying
if (wi.getBSSID().equals("c0:ff:ee:c0:ff:ee")) {
// ... Do your stuff here
// ...
// ...
}
} else {
// No ip address yet, we need to wait...
// Battery friendly method, using events
if (awaitIPAddress == null) {
awaitIPAddress = new BroadcastReceiver() {
#Override
public void onReceive(Context ctx, Intent in) {
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wi = wifiManager.getConnectionInfo();
if (wi != null) {
if (wi.getIpAddress() != 0) {
if (wi.getBSSID().equals("c0:ff:ee:c0:ff:ee")) {
// ... Do your stuff here
// ...
// ...
}
}
} else {
ctx.unregisterReceiver(this);
awaitIPAddress = null;
}
}
};
// We register a new receiver for connectivity events
// (getting a new IP address for example)
context.registerReceiver(awaitIPAddress, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
}
}
} else {
// wifi connection not complete, release ip address receiver if registered
if (awaitIPAddress != null) {
context.unregisterReceiver(awaitIPAddress);
awaitIPAddress = null;
}
}
}
}
};
//... Other stuff
#Override
public void onCreate() {
super.onCreate();
//... Other stuff
IntentFilter filter = new IntentFilter();
filter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
registerReceiver(receiver, filter);
//... Other stuff
}
//... Other stuff
}
Also, don't neglect the appropriate permissions to the manifest:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
And I strongly suspect you will also need:
<uses-permission android:name="android.permission.INTERNET"/>

How to use SUPPLICANT_STATE_CHANGED_ACTION WiFi BroadcastReceiver - android

I want to show the connection process on the screen when my device is connecting to the wifi network. SUPPLICANT_STATE_CHANGED_ACTION is provided by WifiManager but i don't know how to use it. Can anyone help me please?
You can indeed use the broadcasted intents for SUPPLICANT_STATE_CHANGED_ACTION:
The app needs the permission in its Manifest file:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Then register for the system broadcast:
MyWifiStateReceiver handler = new MyWifiStateReceiver();
context.registerReceiver(handler, new IntentFilter(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION));
the registerReceiver() needs an instance of a class implementing BroadcastReceiver as its first argument. In that code you can act on the Wifi state changes by overriding the onReceive method. For example
public class MyWifiStateReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
if (intent.getAction().equals(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION))
{
SupplicantState state = (SupplicantState) intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE);
switch(state)
{
case COMPLETED:
case DISCONNECTED:
...
}
}
}
}
For the possible Wifi state values, see http://developer.android.com/reference/android/net/wifi/SupplicantState.html
I don't know of a callback method that lets you know when the wifi status has changed. I polled the information using a Handler running in the background.
Add the handler to your class.
private WifiStatusHandler wifiStatusHandler = new WifiStatusHandler();
Start it by calling
wifiStatusHandler.start();
The code I used is below.
/**
* Checks for wifi status updates.
*/
private class WifiStatusHandler extends Handler {
private boolean running = false;
public void handleMessage(Message message) {
if (running) {
//check wifi status here
WifiManager wifiMgr = (WifiManager) getSystemService(Context.WIFI_SERVICE);
int curWifiState = wifiMgr.getWifiState();
SupplicantState info = wifiMgr.getConnectionInfo().getSupplicantState();
WifiInfo curWifi = wifiMgr.getConnectionInfo();
Log.i(TAG,"WIFI STATE = " + info.toString());
//update the TextView etc.
sleep();
}
}
private void sleep() {
removeMessages(0);
sendMessageDelayed(obtainMessage(0), REFRESH_DELAY);
}
public synchronized void start() {
running = true;
removeMessages(0);
sendMessageDelayed(obtainMessage(0), 0);
}
public synchronized void stop() {
running = false;
}
}

How to detect when WIFI Connection has been established in Android?

I need to detect when I have network connectivity over WIFI. What broadcast is sent to establish that a valid network connection has been made. I need to validate that a valid network connection for HTTP exists. What should I listen for and what additional tests do I need to make to know that a valid connection exists.
You can register a BroadcastReceiver to be notified when a WiFi connection is established (or if the connection changed).
Register the BroadcastReceiver:
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
registerReceiver(broadcastReceiver, intentFilter);
And then in your BroadcastReceiver do something like this:
#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)) {
//do stuff
} else {
// wifi connection was lost
}
}
}
For more info, see the documentation for BroadcastReceiver and WifiManager
Of course you should check whether the device is already connected to WiFi before this.
EDIT:
Thanks to ban-geoengineering, here's a method to check whether the device is already connected:
private boolean isConnectedViaWifi() {
ConnectivityManager connectivityManager = (ConnectivityManager) appObj.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
return mWifi.isConnected();
}
The best that worked for me:
AndroidManifest
<receiver android:name="com.AEDesign.communication.WifiReceiver" >
<intent-filter android:priority="100">
<action android:name="android.net.wifi.STATE_CHANGE" />
</intent-filter>
</receiver>
BroadcastReceiver class
public class WifiReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if(info != null && info.isConnected()) {
// Do your work.
// e.g. To check the Network Name or other info:
WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
String ssid = wifiInfo.getSSID();
}
}
}
Permissions
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
For me only WifiManager.NETWORK_STATE_CHANGED_ACTION works.
Register a broadcast receiver:
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
registerReceiver(broadcastReceiver, intentFilter);
and receive:
#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();
//call your method
}
}
You can start a wifi connection if you give the user a choice to override the normal behavior of asking each time.
I choose to use three methods...
public boolean isOnline()
{
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
return (networkInfo != null && networkInfo.isConnected());
}
This is quick check if there is an internet connect either Wifi or CellData. From here you can choose what action you want to take. Is it in Airplane mode needs to be checked also.
On a separate thread.
I set a variable IpAddress to = " "
And poll until I have a valid an ip address.
WifiManager wifi;
wifi = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifi.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();
String ip = null;
ip = String.format("%d.%d.%d.%d",
(ipAddress & 0xff),
(ipAddress >> 8 & 0xff),
(ipAddress >> 16 & 0xff),
(ipAddress >> 24 & 0xff));
Log.e(" >>IP number Begin ",ip);
Another code snippet... If its not on turn it on (with users prior permission)
if(wifi.isWifiEnabled()!=true)wifi.setWifiEnabled(true);
Answer given by user #JPM and #usman are really very useful. It works fine but in my case it come in onReceive multiple time in my case 4 times so my code execute multiple time.
I do some modification and make as per my requirement and now it comes only 1 time
Here is java class for Broadcast.
public class WifiReceiver extends BroadcastReceiver {
String TAG = getClass().getSimpleName();
private Context mContext;
#Override
public void onReceive(Context context, Intent intent) {
mContext = context;
if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI &&
networkInfo.isConnected()) {
// Wifi is connected
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
String ssid = wifiInfo.getSSID();
Log.e(TAG, " -- Wifi connected --- " + " SSID " + ssid );
}
}
else if (intent.getAction().equalsIgnoreCase(WifiManager.WIFI_STATE_CHANGED_ACTION))
{
int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN);
if (wifiState == WifiManager.WIFI_STATE_DISABLED)
{
Log.e(TAG, " ----- Wifi Disconnected ----- ");
}
}
}
}
In AndroidManifest
<receiver android:name=".util.WifiReceiver" android:enabled="true">
<intent-filter>
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
To detect WIFI connection state, I have used CONNECTIVITY_ACTION from ConnectivityManager class so:
IntentFilter filter=new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(receiver, filter);
and from your BroadCastReceiver:
if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action)) {
int networkType = intent.getIntExtra(
android.net.ConnectivityManager.EXTRA_NETWORK_TYPE, -1);
if (ConnectivityManager.TYPE_WIFI == networkType) {
NetworkInfo networkInfo = (NetworkInfo) intent
.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if (networkInfo != null) {
if (networkInfo.isConnected()) {
// TODO: wifi is connected
} else {
// TODO: wifi is not connected
}
}
}
}
ps:works fine for me:)
This code does not require permission at all. It is restricted only to Wi-Fi network connectivity state changes (any other network is not taken into account). The receiver is statically published in the AndroidManifest.xml file and does not need to be exported as it will be invoked by the system protected broadcast, NETWORK_STATE_CHANGED_ACTION, at every network connectivity state change.
AndroidManifest:
<receiver
android:name=".WifiReceiver"
android:enabled="true"
android:exported="false">
<intent-filter>
<!--protected-broadcast: Special broadcast that only the system can send-->
<!--Corresponds to: android.net.wifi.WifiManager.NETWORK_STATE_CHANGED_ACTION-->
<action android:name="android.net.wifi.STATE_CHANGE" />
</intent-filter>
</receiver>
BroadcastReceiver class:
public class WifiReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
/*
Tested (I didn't test with the WPS "Wi-Fi Protected Setup" standard):
In API15 (ICE_CREAM_SANDWICH) this method is called when the new Wi-Fi network state is:
DISCONNECTED, OBTAINING_IPADDR, CONNECTED or SCANNING
In API19 (KITKAT) this method is called when the new Wi-Fi network state is:
DISCONNECTED (twice), OBTAINING_IPADDR, VERIFYING_POOR_LINK, CAPTIVE_PORTAL_CHECK
or CONNECTED
(Those states can be obtained as NetworkInfo.DetailedState objects by calling
the NetworkInfo object method: "networkInfo.getDetailedState()")
*/
/*
* NetworkInfo object associated with the Wi-Fi network.
* It won't be null when "android.net.wifi.STATE_CHANGE" action intent arrives.
*/
NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if (networkInfo != null && networkInfo.isConnected()) {
// TODO: Place the work here, like retrieving the access point's SSID
/*
* WifiInfo object giving information about the access point we are connected to.
* It shouldn't be null when the new Wi-Fi network state is CONNECTED, but it got
* null sometimes when connecting to a "virtualized Wi-Fi router" in API15.
*/
WifiInfo wifiInfo = intent.getParcelableExtra(WifiManager.EXTRA_WIFI_INFO);
String ssid = wifiInfo.getSSID();
}
}
}
Permissions:
None
Android O removed the possibility to receive the implicit broadcasts for a wifi state change. So if your app is closed, you'll not be able to receive them. The new WorkManager has the ability to run when your app is closed, so I've experimented a bit with it and it seems to work quite well:
Add this to your dependencies:
implementation "android.arch.work:work-runtime:1.0.0-alpha08"
WifiConnectWorker.kt
class WifiConnectWorker : Worker() {
override fun doWork(): Result {
Log.i(TAG, "I think we connected to a wifi")
return Result.SUCCESS
}
}
MainActivity.kt
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main_activity)
val workManager = WorkManager.getInstance()
// Add constraint to start the worker when connecting to WiFi
val request = OneTimeWorkRequest.Builder(WifiConnectWorker::class.java)
.setConstraints(Constraints.Builder()
.setRequiredNetworkType(UNMETERED)
.build())
.build()
// The worker should be started, even if your app is closed
workManager.beginUniqueWork("watch_wifi", REPLACE, request).enqueue()
}
}
Keep in mind that this was just a quick test for a one-time notification. There is more work to do to always get notified when WiFi is turned on and off.
PS: When the app is force quit, the worker is not started, it seems WorkManager is canceling the requests then.
November 2020:
I have dealt too much with items deprecated by Google. Finally I found a solution to my particular requirement using "registerNetworkCallback" as Google currently suggests.
What I needed was a simple way to detect that my device has an IPv4 assigned in WIFI.
(I haven't tried other cases, my requirement was very specific, but maybe this method, without deprecated elements, will serve as a basis for other cases).
Tested on APIs 23, 24 and 26 (physical devices) and APIs 28 and 29 (emulated devices).
ConnectivityManager cm
= (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkRequest.Builder builder = new NetworkRequest.Builder();
cm.registerNetworkCallback
(
builder.build(),
new ConnectivityManager.NetworkCallback()
{
#Override
public void onAvailable(Network network)
{
//Actions to take with Wifi available.
}
#Override
public void onLost(Network network)
{
//Actions to take with lost Wifi.
}
}
);
(Implemented inside "MainActivity.Oncreate")
Note: In manifest needs "android.permission.ACCESS_NETWORK_STATE"
Here is an example of my code, that takes into account the users preference of only allowing comms when connected to Wifi.
I am calling this code from inside an IntentService before I attempt to download stuff.
Note that NetworkInfo will be null if there is no network connection of any kind.
private boolean canConnect()
{
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
boolean canConnect = false;
boolean wifiOnly = SharedPreferencesUtils.wifiOnly();
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if(networkInfo != null)
{
if(networkInfo.isConnected())
{
if((networkInfo.getType() == ConnectivityManager.TYPE_WIFI) ||
(networkInfo.getType() != ConnectivityManager.TYPE_WIFI && !wifiOnly))
{
canConnect = true;
}
}
}
return canConnect;
}
I have two methods to detect WIFI connection receiving the application context:
1)my old method
public boolean isConnectedWifi1(Context context) {
try {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null) {
NetworkInfo[] netInfo = connectivityManager.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if ((ni.getTypeName().equalsIgnoreCase("WIFI"))
&& ni.isConnected()) {
return true;
}
}
}
return false;
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
return false;
}
2)my New method (I´m currently using this method):
public boolean isConnectedWifi(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
return networkInfo.isConnected();
}
1) I tried Broadcast Receiver approach as well even though I know CONNECTIVITY_ACTION/CONNECTIVITY_CHANGE is deprecated in API 28 and not recommended. Also bound to using explicit register, it listens as long as app is running.
2) I also tried Firebase Dispatcher which works but not beyond app killed.
3) Recommended way found is WorkManager to guarantee execution beyond process killed and internally using registerNetworkRequest()
The biggest evidence in favor of #3 approach is referred by Android doc itself. Especially for apps in the background.
Also here
In Android 7.0 we're removing three commonly-used implicit broadcasts — CONNECTIVITY_ACTION, ACTION_NEW_PICTURE, and ACTION_NEW_VIDEO — since those can wake the background processes of multiple apps at once and strain memory and battery. If your app is receiving these, take advantage of the Android 7.0 to migrate to JobScheduler and related APIs instead.
So far it works fine for us using Periodic WorkManager request.
Update: I ended up writing 2 series medium post about it.
I used this code:
public class MainActivity extends Activity
{
.
.
.
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
.
.
.
}
#Override
protected void onResume()
{
super.onResume();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
registerReceiver(broadcastReceiver, intentFilter);
}
#Override
protected void onPause()
{
super.onPause();
unregisterReceiver(broadcastReceiver);
}
private final BroadcastReceiver broadcastReceiver = 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))
{
// wifi is enabled
}
else
{
// wifi is disabled
}
}
}
};
}
For all those who enjoying CONNECTIVITY_CHANGE broadcast, please note this is no more fired when app is in background in Android O.
https://developer.android.com/about/versions/o/background.html
You Can use Broadcast With Filter
<receiver
android:name=".receivers.ConnectionType"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
</intent-filter>
</receiver>
after that, you can listen to the value returned like that
#Override
public void onReceive(Context context, Intent intent) {
int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN);
if(wifiState==WifiManager.WIFI_STATE_ENABLED){
Toast.makeText(context, "WIFI on", Toast.LENGTH_SHORT).show();
}else if(wifiState==WifiManager.WIFI_STATE_DISABLED) {
Toast.makeText(context, "WIFI OFF", Toast.LENGTH_SHORT).show();
}
}
it will fire every time WIFI enabled or disabled

How can I programmatically tell if a Bluetooth device is connected?

I understand how to get a list of paired devices, but how can I tell if they are connected?
It must be possible since I see them listed in my phone's Bluetooth device list and it states their connection status.
Add the Bluetooth permission to your AndroidManifest,
<uses-permission android:name="android.permission.BLUETOOTH" />
Then use intent filters to listen to the ACTION_ACL_CONNECTED, ACTION_ACL_DISCONNECT_REQUESTED, and ACTION_ACL_DISCONNECTED broadcasts:
public void onCreate() {
...
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
this.registerReceiver(mReceiver, filter);
}
//The BroadcastReceiver that listens for bluetooth broadcasts
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
... //Device found
}
else if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
... //Device is now connected
}
else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
... //Done searching
}
else if (BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED.equals(action)) {
... //Device is about to disconnect
}
else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
... //Device has disconnected
}
}
};
A few notes:
There is no way to retrieve a list of connected devices at application startup. The Bluetooth API does not allow you to query, instead it allows you to listen to changes.
A hoaky workaround to the above problem would be to retrieve the list of all known/paired devices... then trying to connect to each one (to determine if you're connected).
Alternatively, you could have a background service watch the Bluetooth API and write the device states to disk for your application to use at a later date.
In my use case I only wanted to see if a Bluetooth headset is connected for a VoIP app. The following solution worked for me.
Kotlin:
fun isBluetoothHeadsetConnected(): Boolean {
val mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
return (mBluetoothAdapter != null && mBluetoothAdapter.isEnabled
&& mBluetoothAdapter.getProfileConnectionState(BluetoothHeadset.HEADSET) == BluetoothHeadset.STATE_CONNECTED)
}
Java:
public static boolean isBluetoothHeadsetConnected() {
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
return mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()
&& mBluetoothAdapter.getProfileConnectionState(BluetoothHeadset.HEADSET) == BluetoothHeadset.STATE_CONNECTED;
}
Of course you'll need the Bluetooth permission:
<uses-permission android:name="android.permission.BLUETOOTH" />
There is an isConnected function in the BluetoothDevice system API in https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/bluetooth/BluetoothDevice.java.
If you want to know if a bounded (paired) device is currently connected or not, the following function works fine for me:
public static boolean isConnected(BluetoothDevice device) {
try {
Method m = device.getClass().getMethod("isConnected", (Class[]) null);
boolean connected = (boolean) m.invoke(device, (Object[]) null);
return connected;
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
For some reason, BluetoothAdapter.ACTION_ACL_CONNECTED could not be resolved by Android Studio. Perhaps it was deprecated in Android 4.2.2?
Here is a modification of Skylarsutton's code (Big thanks to Skylarsutton for his answer.) . The registration code is the same; the receiver code differs slightly. I use this in a service which updates a Bluetooth-connected flag that other parts of the app reference.
public void onCreate() {
//...
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
this.registerReceiver(BTReceiver, filter);
}
//The BroadcastReceiver that listens for bluetooth broadcasts
private final BroadcastReceiver BTReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
//Do something if connected
Toast.makeText(getApplicationContext(), "BT Connected", Toast.LENGTH_SHORT).show();
}
else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
//Do something if disconnected
Toast.makeText(getApplicationContext(), "BT Disconnected", Toast.LENGTH_SHORT).show();
}
//else if...
}
};
This code is for the headset profiles, and probably it will work for other profiles too.
First you need to provide a profile listener (Kotlin code):
private val mProfileListener = object : BluetoothProfile.ServiceListener {
override fun onServiceConnected(profile: Int, proxy: BluetoothProfile) {
if (profile == BluetoothProfile.HEADSET)
mBluetoothHeadset = proxy as BluetoothHeadset
}
override fun onServiceDisconnected(profile: Int) {
if (profile == BluetoothProfile.HEADSET) {
mBluetoothHeadset = null
}
}
}
Then while checking Bluetooth:
mBluetoothAdapter.getProfileProxy(context, mProfileListener, BluetoothProfile.HEADSET)
if (!mBluetoothAdapter.isEnabled) {
return Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
}
It takes a bit of time until onSeviceConnected is called. After that you may get the list of the connected headset devices from:
mBluetoothHeadset!!.connectedDevices
BluetoothAdapter.getDefaultAdapter().isEnabled ->
returns true when Bluetooth is open.
val audioManager = this.getSystemService(Context.AUDIO_SERVICE) as AudioManager
audioManager.isBluetoothScoOn ->
returns true when a device connected
I was really looking for a way to fetch the connection status of a device, not listen to connection events. Here's what worked for me:
BluetoothManager bm = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
List<BluetoothDevice> devices = bm.getConnectedDevices(BluetoothProfile.GATT);
int status = -1;
for (BluetoothDevice device : devices) {
status = bm.getConnectionState(device, BLuetoothGatt.GATT);
// compare status to:
// BluetoothProfile.STATE_CONNECTED
// BluetoothProfile.STATE_CONNECTING
// BluetoothProfile.STATE_DISCONNECTED
// BluetoothProfile.STATE_DISCONNECTING
}

Categories

Resources