- Nearby Wi-Fi Access Permission in Android 13
- Conclusion
- permission for accessing WIFI in android 6
- Android WiFi with Examples
- Android Set Wi-Fi Permissions
- Android WifiManager Class
- Android Enable or Disable Wi-Fi
- Android List Wireless Networks
- Android Wi-fi Turn ON / OFF Example
- activity_main.xml
- MainActivity.java
- AndroidManifest.xml
- Output of Android Wi-Fi Turn ON / OFF Example
Nearby Wi-Fi Access Permission in Android 13
Android 13 is another one of Google’s larger mid-cycle improvements to the operating system. These Quarterly Platform Releases (abbreviated QPR) introduce a few well-chosen new features, Significant privacy improvements were made with the last release, and Android 13 is continuing that trend. Going forward, we see even more implications put on to us as developers by Google, seems that now we will need special permissions to access the device’s real-time Wi-Fi scanning capabilities, and thus, we need to make our app ready for utilizing this permission, and keep our work getting done, otherwise as more and more devices continue to join the party, your app will slowly start to become outdated, if it relies on the nearby information from the Wi-Fi scanners.
To solve this issue, this Geeks for Geeks article will help you write code to utilize and ask permission for scanning Wi-Fi.
Note: Now, starting from Android 13, if your app calls a Wi-Fi API without asking for permission first, then your app will crash and a security-exception would trigger.
The NEARBY WIFI DEVICES runtime permission must be requested by apps that handle Wi-Fi connections and are designed for Android 13 (API level 33) or higher. Earlier versions of Android required these apps to declare the ACCESS FINE LOCATION permission; this permission makes it simpler to explain an app’s access to adjacent Wi-Fi devices.
If your app does not rely on precise location, then declare it:
If your app does not ever obtain location data through Wi-Fi APIs, you should adamantly state such when you target Android 13 or higher. Set the usesPermissionFlags attribute in your app’s manifest file to neverForLocation to make this claim, as seen in the following code sample. When you claim that Bluetooth device information is never utilized for location, you go through a similar process
The Nearby devices permission group includes the NEARBY WIFI DEVICES permission. The permissions for Bluetooth and Ultra-wideband are also included in this group, which was added in Android 12 (API level 31). Any time you ask for more than one permission from this group, the system displays a single runtime prompt and requests the user’s approval before allowing access to adjacent devices for your program. The Nearby device’s permissions must be enabled or disabled together in the system settings; for instance, users cannot turn off Wi-Fi access while maintaining Bluetooth access for a specific app. To add this permission to your android app, simply do these steps.
Add the permission in your Android’s Manifest File:
Perhaps the first thing you will do to add the permission is to add it to your app’s Manifest file, to tell the system that your app is requesting this permission beforehand, to do it, simply:
Lookup APIs that demand authorization:
Before moving forward it will be better to know if your app requires to use the request permission or not, if your app uses any of the following Wi-Fi APIs, your app must target Android 13 or higher and declare the NEARBY WIFI DEVICES permission:
If your app is targeting any of these APIs you should immediately ask for permission otherwise your app will crash on the newer Android Version.
Location permission is necessary for older versions and some APIs:
Even though your app is designed to run on Android 13 or higher, some Wi-Fi APIs still require the ACCESS FINE LOCATION permission. The following WifiManager class methods serve as examples:
Additionally, to maintain backward compatibility in your app, you should keep any declarations for ACCESS FINE LOCATION since the NEARBY WIFI DEVICES permission is only available on Android 13 and higher. However, as seen in the following code snippet, you can set the maximum SDK version of this permission to 32 if your app doesn’t otherwise rely on exact location data.
Conclusion
This brings us to the end of this article, this is rather an important one, although the solution to it lies really short, without taking it, will lead your app to crash on the newer versions of Android (13+).
permission for accessing WIFI in android 6
I am new to android studio, i was previously working on android version 5.1 for my app and it worked fine but now in 6 i am not able to get permission or i am not sure if my method is wrong. I am making an app which uses the list of access points available for my mobile. But even though i am granted permission my app does not show me the wifi list but the same code works well for earlier versions.
Mainactivity: package com.wiferange.wifi_test; 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.WifiManager; import android.os.Build; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Gravity; import android.view.View; import android.view.Menu; import android.view.MenuItem; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import java.util.List; public class MainActivity extends AppCompatActivity < ListView lv; String lists[]=; WifiManager wifi; String wifis[]; WifiScanReceiver wifiReciever; @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); lv = (ListView)findViewById(R.id.listView); wifi=(WifiManager)getSystemService(Context.WIFI_SERVICE); wifiReciever = new WifiScanReceiver(); getPermission(); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() < @Override public void onClick(View view) < >>); > protected void onPause() < unregisterReceiver(wifiReciever); super.onPause(); >protected void onResume() < registerReceiver(wifiReciever, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)); super.onResume(); >private void getPermission() < if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.ACCESS_WIFI_STATE) != PackageManager.PERMISSION_GRANTED)< requestPermissions(new String[],0x12345); // lv.setAdapter(new ArrayAdapter(getApplicationContext(),android.R.layout.simple_list_item_1,lists)); //After this point you wait for callback in onRequestPermissionsResult(int, String[], int[]) overriden method >else < wifi.startScan(); //do scanning, permission was previously granted; or legacy device >> @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) < //funcitno executes when some permission was granted if (requestCode == 0x12345) < for (int grantResult : grantResults) < if (grantResult != PackageManager.PERMISSION_GRANTED) < //check if permission was already grnated and start scannig if yes wifi .startScan() ; return; >> getPermission(); //ask for permission if not given > > private class WifiScanReceiver extends BroadcastReceiver < public void onReceive(Context c, Intent intent) < ListwifiScanList = wifi.getScanResults(); wifis = new String[wifiScanList.size()]; for(int i = 0; i < wifiScanList.size(); i++)< wifis[i] = ((wifiScanList.get(i)).toString()); >lv.setAdapter(new ArrayAdapter(getApplicationContext(),android.R.layout.simple_list_item_1,wifis)); > > @Override public boolean onCreateOptionsMenu(Menu menu) < // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; >@Override public boolean onOptionsItemSelected(MenuItem item) < // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int //noinspection SimplifiableIfStatement if (id == R.id.action_settings) < return true; >return super.onOptionsItemSelected(item); > >
Android WiFi with Examples
In android, Wi-Fi is a wireless network protocol that allows devices to connect to the internet or connect wirelessly with other devices to exchange the data.
Generally, in android applications by using Wi-Fi API’s we can manage all aspects of WI-FI connectivity, such as a scan or search for available networks, add/save/delete Wi-Fi connections and managing the data transfer between devices within the range.
By using android Wi-Fi API’s in android applications, we can perform following functionalities.
- Scan for the available Wi-Fi networks within the range
- Allow devices to connect to the internet
- Connect to other devices through service discovery
- Manage list of configured networks.
- Manage multiple connections
Android Set Wi-Fi Permissions
To use Wi-Fi features in our android applications, we must need to add multiple permissions, such as CHANGE_WIFI_STATE, ACCESS_WIFI_STATE and INTERNET in our manifest file.
Following is the example of defining the Bluetooth permissions in android manifest file.
Android WifiManager Class
In android, we can perform Wi-Fi related activities by using WifiManager class in our applications. This class will provide required API’s to manage all aspects of Wi-Fi connectivity.
By using WifiManager class, we can perform the operations that are related to network connectivity. We can instantiate this class by using Context.getSystemService(Class) with the argument WifiManager.class or Context.getSystemService(String) with the argument Context.WIFI_SERVICE.
Following is the code snippet to initialize WifiManager class using Context.getSystemService(String) with the argument Context.WIFI_SERVICE.
WifiManager wmgr = (WifiManager)Context.getSystemService(Context. WIFI_SERVICE );
If you observe above code snippet, we used getSystemService() method to instantiate a WifiManager class.
In case if getSystemService() method returns NULL, then the device does not support Wi-Fi and we can disable all Wi-Fi features.
Android Enable or Disable Wi-Fi
If Wi-Fi is supported but disabled, then isWifiEnabled() method will return false and we can request user to enable wifi without leaving our application by using setWifiEnabled method.
Following is the code snippet to enable a Wi-Fi in android application by using setWifiEnabled() method.
WifiManager wmgr = (WifiManager)Context.getSystemService(Context. WIFI_SERVICE );
wmgr.setWifiEnabled( true );
If you observe above code snippet, we used setWifiEnabled(true) method to turn ON or Enable a Wi-Fi in our android application.
By using setWifiEnabled(false) method we can Disable or turn OFF a Wi-Fi in android applications.
Android List Wireless Networks
By using WifiManager method getScanResults(), we can get the list of available Wi-Fi network details.
Following is the code snippet to get the available Wi-Fi network details in android applications.
WifiManager wmgr = (WifiManager)getApplicationContext().getSystemService(Context. WIFI_SERVICE );
// Get List of Available Wifi Networks
List availNetworks = wmgr.getScanResults();
if (availNetworks.size() > 0 ) String wifis[] = new String[availNetworks.size()];
// Get Each network detail
for ( int i= 0 ; i
>
If you observe above code, we are getting the available Wi-Fi network details by using getScanResults() method of WifiManager object.
Now we will see how to use WifiManager object to turn ON / OFF or Enable / Disable Wi-Fin in our android applications.
Android Wi-fi Turn ON / OFF Example
Following is the example of turning on or off Wi-Fi on button click in android applications.
Create a new android application using android studio and give names as WifiExample. In case if you are not aware of creating an app in android studio check this article Android Hello World App.
Once we create an application, open activity_main.xml file from \res\layout folder path and write the code like as shown below.
activity_main.xml
< RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android"
android :layout_width= «match_parent»
android :layout_height= «match_parent»
android :paddingLeft= «10dp»
android :paddingRight= «10dp» >
< Button
android :id= «@+id/btnOn»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :text= «Wifi Turn On» android :layout_marginLeft= «70dp» android :layout_marginTop= «200dp»/>
< Button
android :id= «@+id/btnOFF»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :layout_alignBottom= «@+id/btnOn»
android :layout_toRightOf= «@+id/btnOn»
android :text= «Wifi Turn OFF»/>
Now open your main activity file MainActivity.java from \java\com.tutlane.wifiexample path and write the code like as shown below
MainActivity.java
package com.tutlane.wifiexample;
import android.content.Context;
import android.net.wifi.WifiManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity @Override
protected void onCreate(Bundle savedInstanceState) super .onCreate(savedInstanceState);
setContentView(R.layout. activity_main );
Button btntOn = (Button)findViewById(R.id. btnOn );
Button btntOff = (Button)findViewById(R.id. btnOFF );
btntOn.setOnClickListener( new View.OnClickListener() @Override
public void onClick(View v) WifiManager wmgr = (WifiManager)getApplicationContext().getSystemService(Context. WIFI_SERVICE );
wmgr.setWifiEnabled( true );
>
>);
btntOff.setOnClickListener( new View.OnClickListener() @Override
public void onClick(View v) WifiManager wmgr = (WifiManager)getApplicationContext().getSystemService(Context. WIFI_SERVICE );
wmgr.setWifiEnabled( false );
>
>);
>
>
If you observe above code, we used setWifiEnabled() method of WifiManager class to enable or disable a Wi-Fi in our application.
As discussed, we need to set Wi-Fi permissions in android manifest file (AndroidManifest.xml) to access Wi-Fi features in android applications. Now open android manifest file (AndroidManifest.xml) and write the code like as shown below
AndroidManifest.xml
If you observe above code, we added required Wi-Fi permissions in manifest file to access Wi-Fi features in android applications.
Output of Android Wi-Fi Turn ON / OFF Example
When we run the above program in the android studio we will get the result as shown below.
When we click on Turn ON button, the device Wi-Fi gets switched ON and when we click on Turn OFF button, the device Wi-Fi get switched OFF.
This is how we can turn ON or OFF Wi-Fi in android applications based on our requirements.