Android wifi intent filter

BroadcastReceiver when wifi or 3g network state changed

I have an app which updates the database whenever the phone is connected to WiFi. I have implemented a Service and BroadcastReceiver which will run the Service (it will tell me what network is in use), but the problem is I don’t know what to add in the manifest file to start BroadcastReceiver when the network state changes or when it connects to some kind of network

5 Answers 5

Or if you want more control over it, before registering BroadcastReceiver set these up:

final IntentFilter filters = new IntentFilter(); filters.addAction("android.net.wifi.WIFI_STATE_CHANGED"); filters.addAction("android.net.wifi.STATE_CHANGE"); super.registerReceiver(yourReceiver, filters); 

WIFI_STATE_CHANGED

Broadcast indicating that Wi-Fi has been enabled, disabled, enabling, disabling, or unknown. One extra provides this state as an int. Another extra provides the previous state, if available.

STATE_CHANGE

Broadcast indicating that the state of Wi-Fi connectivity has changed. One extra provides the new state in the form of a NetworkInfo object. If the new state is CONNECTED, additional extras may provide the BSSID and WifiInfo of the access point. as a String

Also, you’ll need to specify the right permissions inside manifest tag:

To check connectivity, you can use ConnectivityManager as it tells you what type of connection is available.

ConnectivityManager conMngr = (ConnectivityManager)this.getSystemService(this.CONNECTIVITY_SERVICE); android.net.NetworkInfo wifi = conMngr.getNetworkInfo(ConnectivityManager.TYPE_WIFI); android.net.NetworkInfo mobile = conMngr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); 

Источник

Android Wifi Scanning Tutorial with Examples

Follow us on our fanpages to receive notifications every time there are new articles. Facebook Twitter

1- Android Wi-Fi

In Android, Wi-Fi is known as a Wireless Network Protocol. It permits devices to get connected to the Internet or devices connected to each other for data exchange.

Specifically, Android provides the Wi-Fi API that applications can use the API to manage all aspects related to Wifi connectivity, such as searching for current Wifi networks, adding, saving, deleting Wifi connections, as well as managing data exchanged among devices.

In case you use the Wi-Fi API in your application, you can perform the following functions:

  1. Scan to search for available Wifi networks in a range.
  2. Allow devices to get connected to the Internet.
  3. Connect to other devices via Service Discovery.
  4. Manage a list of the configured networks.
  5. Manage multiple connections.

Since Android 10.0 (API Level 29), you cannot use the Wi-Fi API in order to enable/disable the WiFi of the system,. It means that if you want to enable/disable Wifi, you have to use the available function of the operating system.

The privacy policy for using the Wi-Fi API to enable/disable Wifi has changed a few times over different versions of Android. More spercifically:

Android Level Privacy policy
Level 1 ==> Level 22
(Android < 6.0)
Android.permission.CHANGE_WIFI_STATE needs to be added to AndroidManifest.xml.
Level 23 ==> Level 28
(Android 6.0 — 9.x)
Android.permission.CHANGE_WIFI_STATE needs to be added to AndroidManifest.xml. Simultaneously, the application must ask the user to allow it to enable/ disable the Wifi of the system.
Level 29+
(Android 10.0+)
Wi-Fi API is not permitted to enable/ disable the Wifi of the system.
 WifiManager wifiManager = (WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE); wifiManager.setWifiEnabled(true); // Enable Wifi wifiManager.setWifiEnabled(false); // Disable Wifi 

In Android 10+ (API Level 29+), setWifiEnabled(boolean) is not in use anymore.
To get the Wifi status, you need to add android.permission.ACCESS_WIFI_STATE to AndroidManifest.xml:

 WifiManager wifiManager = (WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE); int state = wifiManager.getWifiState(); String statusInfo = "Unknown"; switch (state)
 WifiManager wifiManager = (WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE); // Get List of Available Wifi Networks List availNetworks = wifiManager.getScanResults(); if (availNetworks.size() > 0) < // Get Each network detail for (int i=0; i< availNetworks.size();i++) < // . >> 

The privacy policy for scanning current networks has changed a few times to different Android versions:

Читайте также:  Настройка wake on lan wifi
Android API Level Privacy policy
Level 1 ==> Level 2 Android.permission.ACCESS_COARSE_LOCATION needs to be added to AndroidManifest.xml.
Level 23+
(Android 6.0+)
Android.permission.ACCESS_COARSE_LOCATION needs to be added to AndroidManifest.xml. And your application must ask the user for permission to scan (current) networks.

2- Example of WifiManager

In this example, I’m going to show you how to use WifiManager to retrieve the status of the Wifi, scan the current networks, write down the details of each found network, and finally, connect to a certain network in the list.

  • File > New > New Project > Empty Activity
    • Name: WifiManagerExample
    • Package name: org.o7planning.wifimanagerexample
    • Language: Java

     package org.o7planning.wifimanagerexample; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import android.Manifest; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.net.wifi.ScanResult; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiManager; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import java.util.List; public class MainActivity extends AppCompatActivity < private static final String LOG_TAG = "AndroidExample"; private static final int MY_REQUEST_CODE = 123; private WifiManager wifiManager; private Button buttonState; private Button buttonScan; private EditText editTextPassword; private LinearLayout linearLayoutScanResults; private TextView textViewScanResults; private WifiBroadcastReceiver wifiReceiver; @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); this.wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE); // Instantiate broadcast receiver this.wifiReceiver = new WifiBroadcastReceiver(); // Register the receiver registerReceiver(wifiReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)); // this.buttonState = (Button) this.findViewById(R.id.button_state); this.buttonScan = (Button) this.findViewById(R.id.button_scan); this.editTextPassword = (EditText) this.findViewById(R.id.editText_password); this.textViewScanResults = (TextView) this.findViewById(R.id.textView_scanResults); this.linearLayoutScanResults = (LinearLayout) this.findViewById(R.id.linearLayout_scanResults); this.buttonState.setOnClickListener(new View.OnClickListener()< @Override public void onClick(View v) < showWifiState(); >>); this.buttonScan.setOnClickListener(new View.OnClickListener() < @Override public void onClick(View v) < askAndStartScanWifi(); >>); > private void askAndStartScanWifi() < // With Android Level >= 23, you have to ask the user // for permission to Call. if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) < // 23 int permission1 = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION); // Check for permissions if (permission1 != PackageManager.PERMISSION_GRANTED) < Log.d(LOG_TAG, "Requesting Permissions"); // Request permissions ActivityCompat.requestPermissions(this, new String[] < Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_WIFI_STATE, Manifest.permission.ACCESS_NETWORK_STATE >, MY_REQUEST_CODE); return; > Log.d(LOG_TAG, "Permissions Already Granted"); > this.doStartScanWifi(); > private void doStartScanWifi() < this.wifiManager.startScan(); >@Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) < Log.d(LOG_TAG, "onRequestPermissionsResult"); switch (requestCode) < case MY_REQUEST_CODE: < // If request is cancelled, the result arrays are empty. if (grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) < // permission was granted Log.d(LOG_TAG, "Permission Granted: " + permissions[0]); // Start Scan Wifi. this.doStartScanWifi(); >else < // Permission denied, boo! Disable the // functionality that depends on this permission. Log.d(LOG_TAG, "Permission Denied: " + permissions[0]); >break; > // Other 'case' lines to check for other // permissions this app might request. > > private void showWifiState() < int state = this.wifiManager.getWifiState(); String statusInfo = "Unknown"; switch (state) < case WifiManager.WIFI_STATE_DISABLING: statusInfo = "Disabling"; break; case WifiManager.WIFI_STATE_DISABLED: statusInfo = "Disabled"; break; case WifiManager.WIFI_STATE_ENABLING: statusInfo = "Enabling"; break; case WifiManager.WIFI_STATE_ENABLED: statusInfo = "Enabled"; break; case WifiManager.WIFI_STATE_UNKNOWN: statusInfo = "Unknown"; break; default: statusInfo = "Unknown"; break; >Toast.makeText(this, "Wifi Status: " + statusInfo, Toast.LENGTH_LONG).show(); > @Override protected void onStop() < this.unregisterReceiver(this.wifiReceiver); super.onStop(); >// Define class to listen to broadcasts class WifiBroadcastReceiver extends BroadcastReceiver < @Override public void onReceive(Context context, Intent intent) < Log.d(LOG_TAG, "onReceive()"); Toast.makeText(MainActivity.this, "Scan Complete!", Toast.LENGTH_SHORT).show(); boolean ok = intent.getBooleanExtra(WifiManager.EXTRA_RESULTS_UPDATED, false); if (ok) < Log.d(LOG_TAG, "Scan OK"); Listlist = wifiManager.getScanResults(); MainActivity.this.showNetworks(list); MainActivity.this.showNetworksDetails(list); > else < Log.d(LOG_TAG, "Scan not OK"); >> > private void showNetworks(List results) < this.linearLayoutScanResults.removeAllViews(); for( final ScanResult result: results) < final String networkCapabilities = result.capabilities; final String networkSSID = result.SSID; // Network Name. // Button button = new Button(this ); button.setText(networkSSID + " ("+networkCapabilities+")"); this.linearLayoutScanResults.addView(button); button.setOnClickListener(new View.OnClickListener() < @Override public void onClick(View v) < String networkCapabilities = result.capabilities; connectToNetwork(networkCapabilities, networkSSID); >>); > > private void showNetworksDetails(List results) < this.textViewScanResults.setText(""); StringBuilder sb = new StringBuilder(); sb.append("Result Count: " + results.size()); for(int i = 0; i < results.size(); i++ ) < ScanResult result = results.get(i); sb.append("\n\n --------- Network " + i + "/" + results.size() + " ---------"); sb.append("\n result.capabilities: " + result.capabilities); sb.append("\n result.SSID: " + result.SSID); // Network Name. sb.append("\n result.BSSID: " + result.BSSID); sb.append("\n result.frequency: " + result.frequency); sb.append("\n result.level: " + result.level); sb.append("\n result.describeContents(): " + result.describeContents()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) < // Level 17, Android 4.2 sb.append("\n result.timestamp: " + result.timestamp); >if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) < // Level 23, Android 6.0 sb.append("\n result.centerFreq0: " + result.centerFreq0); sb.append("\n result.centerFreq1: " + result.centerFreq1); sb.append("\n result.venueName: " + result.venueName); sb.append("\n result.operatorFriendlyName: " + result.operatorFriendlyName); sb.append("\n result.channelWidth: " + result.channelWidth); sb.append("\n result.is80211mcResponder(): " + result.is80211mcResponder()); sb.append("\n result.isPasspointNetwork(): " + result.isPasspointNetwork() ); >> this.textViewScanResults.setText(sb.toString()); > private void connectToNetwork(String networkCapabilities, String networkSSID) < Toast.makeText(this, "Connecting to network: "+ networkSSID, Toast.LENGTH_SHORT).show(); String networkPass = this.editTextPassword.getText().toString(); // WifiConfiguration wifiConfig = new WifiConfiguration(); wifiConfig.SSID = "\"" + networkSSID + "\""; if(networkCapabilities.toUpperCase().contains("WEP")) < // WEP Network. Toast.makeText(this, "WEP Network", Toast.LENGTH_SHORT).show(); wifiConfig.wepKeys[0] = "\"" + networkPass + "\""; wifiConfig.wepTxKeyIndex = 0; wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); >else if(networkCapabilities.toUpperCase().contains("WPA")) < // WPA Network Toast.makeText(this, "WPA Network", Toast.LENGTH_SHORT).show(); wifiConfig.preSharedKey = "\""+ networkPass +"\""; >else < // OPEN Network. Toast.makeText(this, "OPEN Network", Toast.LENGTH_SHORT).show(); wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); >this.wifiManager.addNetwork(wifiConfig); List list = this.wifiManager.getConfiguredNetworks(); for( WifiConfiguration config : list ) < if(config.SSID != null && config.SSID.equals("\"" + networkSSID + "\"")) < this.wifiManager.disconnect(); this. wifiManager.enableNetwork(config.networkId, true); this.wifiManager.reconnect(); break; >> > > 

    View more Tutorials:

    These are online courses outside the o7planning website that we introduced, which may include free or discounted courses.

    • Android Beginners Guide To Create A Weather Forecast App
    • * * The Complete Android Oreo(8.1) , N ,M and Java Development
    • Absolute Java Basics for Android
    • Android App & Game Development :Build 6 Android Apps & Games
    • Android and iOS Apps for Your WordPress Blog
    • Unity 3d Game Development — iOS, Android, & Web — Beginners
    • Learn Android Development From Scratch
    • Ultimate Coding Course for Web App and Android Development
    • The Complete Android™ Material Design Course
    • Unity Android Game Development : Build 7 2D & 3D Games
    • Publish Games on Android, iTunes, and Google Play with UE4
    • Advance Android Programming — learning beyond basics
    • The Android Crash Course For Beginners to Advanced
    • Learning Path:Android:Application Development with Android N
    • Android development quick start for beginners
    • Android App Development and Design
    • Developing High Quality Android Applications
    • Become an iOS/Android Game Developer with Unity 2017
    • Learning Path: Android: App Development with Android N
    • The Complete Android & Java Developer Course — Build 21 Apps
    • The Complete Android App Development
    • Create Android & iOS Apps Without Coding
    • Develop Your First 2D Game With Unity3D for Android
    • Full Stack Mobile Developer course ( iOS 11, and Android O )
    • Develop Android Apps using Python: Kivy

    Источник

    ANDROID: if WiFi is enabled AND active, launch an intent

    This is what I would like to do : => IF WiFi is enabled AND active, launch an intent (in fact it’s a WebView that gets its content=>the instructions of my app on the web) => IF NOT, then I would launch another intent so that I don’t show a WebView with «Web page not available . The Web page at http://www.mywebsite.com might be temporarily down or it may have moved . » I tought initially to use if(wifi.isWifiEnabled()) but that does not say if the Wifi connection is ACTIVE or not. It says only that the user has turned the switch on. The device may or may not be connected. Is this correct ? Then I tried to use : if (wifi.getConnectionInfo().getSSID()!= null) but I noticed that it returns a string even if the connection has been lost or has been disabled . ? How should I do then ?

    wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE); Intent intent_instructions; if (wifi.getConnectionInfo().getSSID()!= null)< Log.i("Hub", "WiFi is enabled AND active !"); Log.i("Hub", "SSID = "+wifi.getConnectionInfo().getSSID()); intent_instructions = new Intent(this, Instructions.class); >else < Log.i("Hub", "NO WiFi"); intent_instructions = new Intent(this, Instructions_No_WiFi.class); >this.startActivity(intent_instructions); 

    Is there a more general way to test if the device has the connectivity to the internet just before launching an intent ? be it through Wifi, 3G, etc . Thanks in advance for your help.

    WIFI_STAT_ENABLED just means the WIFI radio is on. This doesn’t have anything to do with whether or not you are actually connected to an access point.

    Источник

    Constantly check for wireless network change [duplicate]

    I would like to constantly check whether the phone is connected to a specific wireless network. I thought of a service and the SSID of the network of course, but how?

    «Constantly check»? Do you realize how much battery that would kill? Just check it once then register a receiver to check for changes in connectivity.

    Even checking every 5 min will kill most of the battery power.. Why not to check it when you are doing HTTP communication

    ok and what would you offer as an alternative to handle a network change without exhausting the battery?

    1 Answer 1

    In your receiver tag.

    Or if you want more control over it, before registering BroadcastReceiver set these up:

    final IntentFilter filters = new IntentFilter(); filters.addAction("android.net.wifi.WIFI_STATE_CHANGED"); filters.addAction("android.net.wifi.STATE_CHANGE"); super.registerReceiver(yourReceiver, filters); 

    WIFI_STATE_CHANGED

    Broadcast intent action indicating that Wi-Fi has been enabled, disabled, enabling, disabling, or unknown. One extra provides this state as an int. Another extra provides the previous state, if available.

    STATE_CHANGE

    Broadcast intent action indicating that the state of Wi-Fi connectivity has changed. One extra provides the new state in the form of a NetworkInfo object. If the new state is CONNECTED, additional extras may provide the BSSID and WifiInfo of the access point. as a String

    Also, you’ll need to specify the right permissions:

    Whole Source Code: Download

    AndroidManifest.xml

    MainActivity.java

    package com.example.temp; import android.os.Bundle; import android.app.Activity; import android.view.Menu; public class MainActivity extends Activity < @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); >@Override public boolean onCreateOptionsMenu(Menu menu) < // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; >> 

    Broadcast Receiver:

    package com.example.temp; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.util.Log; public class MyWiFiStateListener extends BroadcastReceiver < @Override public void onReceive(Context context, Intent intent) < // TODO Auto-generated method stub String action = intent.getAction(); Log.d("TEMP", action); if(action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION))< NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO); if(info.getType() == ConnectivityManager.TYPE_WIFI)< WifiManager myWifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE); WifiInfo wifiInfo = myWifiManager.getConnectionInfo(); Log.d("TEMP","BSSID :: " + wifiInfo.getBSSID() + "SSID :: " + wifiInfo.getSSID()); >> > > 

    Источник

Оцените статью
Adblock
detector