Android permission change wifi state

How to enable/disable WiFi from an application?

You also need to request the permission in your AndroidManifest.xml :

@Codii, I know this is old, but I am trying to do this within a dialogfragment. However, it says «Cannot resolve method ‘getSystemService(java.lang.String)’ I am not sure on what I need to do. And I have those permissions

To enable/disable WiFi in your application you need to use WiFiManager class. Create an Object of WiFiManager class to get the services of WiFi.

WifiManager wifi; wifi=(WifiManager)getSystemService(Context.WIFI_SERVICE); wifi.setWifiEnabled(false);//Turn off Wifi wifi.setWifiEnabled(true);//Turn on Wifi 

And you have to put the following permissions in AndroidManifest.xml

To get the whole sample code of enable/disable Wifi in android with UI visit this website

when i do it in my project, but when these code is executed, the system will give a prompt says the app is trying to use wlan whether allows it. and it appears every time! can i enable wlan without the prompt window .

 Intent gpsOptionsIntent = new Intent( android.provider.Settings.ACTION_WIFI_SETTINGS); startActivityForResult(gpsOptionsIntent,0); 

To enable/disable wifi from an app in Android Q (Android 10) use Settings Panel:

val panelIntent = Intent(Settings.Panel.ACTION_INTERNET_CONNECTIVITY) startActivityForResult(panelIntent, 0) 

On previous versions of Android this should work (appropriate permissions should be added to AndroidManifest file, see answers above):

(context?.getSystemService(Context.WIFI_SERVICE) as? WifiManager)?.apply < isWifiEnabled = true /*or false*/ >

Resulting code might look something like this:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) < val panelIntent = Intent(Settings.Panel.ACTION_INTERNET_CONNECTIVITY) startActivityForResult(panelIntent, 0) >else < (context?.getSystemService(Context.WIFI_SERVICE) as? WifiManager)?.apply < isWifiEnabled = true /*or false*/ >> 

Where context is a reference to android.content.Context object.

Источник

WIFI_STATE_CHANGED_ACTION intent not received upon connection to WiFi access point?

Part of my app’s functionality is to scan and display a list of WiFi access points, and then connect to the one chosen by the user. I have this functionality working. Now, I also wish to be notified when the connection «goes through». This should be fairly simple, but I find myself stumbling. I have read through various posts here at SO, and they all mention registering for WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION or WifiManager.WIFI_STATE_CHANGED_ACTION . However, neither of these works for me. Can anyone spot any mistake in this code? (I am leaving out the parts which do the scan and stuff) Expected behavior: As soon as the connection is successful (i.e, when I see the «connected» icon on the notification bar), the broadcast should be received and I should see the toast. Observed behavior: The broadcast is received when the app first starts, and whenever I switch back to it (i.e, whenever onResume() is called; or I suspect, whenever I register for the intent)

public class WifiScanActivity extends Activity < WifiManager mainWifi; WifiReceiver mWifiReceiver; IntentFilter mIntentFilter; private final static String TAG = "WifiScanActivity"; public static final String INTENT_FOR_WIFI_CONNECTED = WifiManager.WIFI_STATE_CHANGED_ACTION; // public static final String INTENT_FOR_WIFI_CONNECTED = // WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION; public void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.main); mainWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE); mWifiReceiver = new WifiReceiver(); mIntentFilter = new IntentFilter(); mIntentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION); mIntentFilter.addAction(INTENT_FOR_WIFI_CONNECTED); registerReceiver(mWifiReceiver, mIntentFilter); mainWifi.startScan(); >protected void onPause() < unregisterReceiver(mWifiReceiver); super.onPause(); >protected void onResume() < registerReceiver(mWifiReceiver, mIntentFilter); super.onResume(); >class WifiReceiver extends BroadcastReceiver < public void onReceive(Context c, Intent intent) < Log.d(TAG, "In WifiReceiver: Broadcast Received = " + intent.getAction()); if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(intent .getAction())) < // Display the ListView and connect to the selected AP >else if (INTENT_FOR_WIFI_CONNECTED.equals(intent.getAction())) < if (WifiManager.WIFI_STATE_ENABLED == intent.getIntExtra( WifiManager.EXTRA_WIFI_STATE, 0)) < displayNetworkInfo(); >/*if(true == intent.getBooleanExtra( * WifiManager.EXTRA_SUPPLICANT_CONNECTED, false))< * displayNetworkInfo(); >*/ > > > private void displayNetworkInfo() < WifiInfo wifiInfo = mainWifi.getConnectionInfo(); String ssid = wifiInfo.getSSID(); int ip = wifiInfo.getIpAddress(); String message = "Connection established.\nSSID = " + ssid + "; IP Address mt24 mb12">
    androidandroid-wifi
)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this question" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="question" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="1" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f3.0%2f" data-se-share-sheet-license-name="CC BY-SA 3.0" data-s-popover-placement="bottom-start">Share
)">edited Nov 13, 2013 at 22:41
Mr_and_Mrs_D
32k38 gold badges178 silver badges359 bronze badges
asked Jul 6, 2011 at 11:37
Add a comment|

3 Answers 3

Reset to default
23

Ok, I figured it out. It turns out I was registering for the wrong intent. I should be using WifiManager.NETWORK_STATE_CHANGED_ACTION.

Here are the snippets of relevant portions of code:

mIntentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION) ; mIntentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION); public void onReceive(Context c, Intent intent) < if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent.getAction())) < NetworkInfo nwInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO); if(NetworkInfo.State.CONNECTED.equals(nwInfo.getState()))>

Источник

Cheesy bits and bobs

A blog about cross-platform mobile app development and other programming related things. Written by Mastodon.

Microsoft MVP

Planet Xamarin Featured Blog

Xamarin Certified Mobile Developer

Connecting to WiFi in Android 10

Android 10 was recently released and it introduces a bunch of changes in terms of Privacy. This means that access to /proc/net from the Linux sub-system has been restricted, which requires you to use NetworkStatsManager and ConnectivityManager to get VPN information.

It adds restrictions to who is allowed to enable/disable WiFi. We could previously use WifiManager.SetWifiEnabled() , but not anymore, this method will return false . You will need to show one of the new Settings Panels, which shows a slice of the Android Settings within your App.

What this post will focus on is the restrictions to access to configured networks and connecting to networks. A bunch of the network API has changed, so let us look a bit into what we have available now.

Suggesting networks

Something new to Android 10 is suggesting networks to connect to. These are just hints to the platform that the networks you provide it, can be connected to and it might decide to chose one of them. When any of these networks are detected nearby, Android will show a notification to the user the first time, which is how they allow connecting to a suggested network.

This could be useful for an Enterprise App, which can allow Access to networks depending on the logged in user or suggest a separate network for guests.

You can suggest networks like so.

var guestUsers = new WifiNetworkSuggestion.Builder() .SetSsid("GuestNetwork") .SetWpa2Passphrase("hunter2") .Build(); var secretEnterpriseNetwork = new WifiNetworkSuggestion.Builder() .SetSsid("Cyberdyne") .SetWpa2Passphrase(":D/-) .Build(); var suggestions = new[]  guestUsers, secretEnterpriseNetwork >; var wifiManager = this.GetSystemService(Context.WifiService) as WifiManager; var status = wifiManager.AddNetworkSuggestions(suggestions); if (status == NetworkStatus.SuggestionsSuccess)  // We added suggestions! > 

The suggestions you provide can only be added once. If you try add the same suggestion again, the status from AddNetworkSuggestion will return SuggestionsErrorAddDuplicate . If you need to modify a suggestion, you need to remove it first with RemoveNetworkSuggestion , then add the modified version of it again. Additionally, in order to add these suggestions you will need to add the CHANGE_WIFI_STATE permission to your AndroidManifest.xml.

 android:name="android.permission.CHANGE_WIFI_STATE" /> 

Note: Some of the options on a WifiNetworkSuggestion requires you to request Fine Location permission in order to work. Make sure to consult the Android documentation to be sure.

After you run AddNetworkSuggestion don’t expect something to happen immediately. There will eventually be a notification in the notification drawer. Which looks like something in the image below. Choosing “Yes” on the notification, won’t necessarily automatically connect to the network. However, going to Wifi Settings on your device, it should now know how to connect to that network.

suggestion notificationsuggestion wifi settings

Connecting to Specific Networks

Prior to Android 10, we could explicitly tell Android to connect to a specific Network and it would simply do it. This was done using WifiManager.AddNetwork() where you provided a WifiConfiguration . Now this API has been deprecated and replaced with ConnectivityManager.RequestNetwork , where you build a Network Request with a Wifi Specification, similar to the suggestions I showed you above. However, it also allows you to specify, whether the connection requires Internet, cannot be VPN, has to be WiFi and more.

You will also need to provide a ConnectivityManager.NetworkCallback , which will let you know whether connection to the network was successful or not. The idea here is that you are awaiting the requested network to connect and only when that is successful you can continue with your execution.

This is excellent for scenarios, where you need to be on a specific network to do some specific operations. One thing to note is that you will only be able to connect to this network while the App is open. As soon as the App is closed, it disconnects the network.

Note: this connection will not have any Internet connectivity according to the Google docs. See the notes in the Android documentation about WiFi Bootstrapping. For Internet connectivity Google suggests to use the Network Suggestions described above.

var specifier = new WifiNetworkSpecifier.Builder() .SetSsid("cyberdyne") .SetWpa2Passphrase("ill be back") .Build(); var request = new NetworkRequest.Builder() .AddTransportType(TransportType.Wifi) // we want WiFi .RemoveCapability(NetCapability.Internet) // Internet not required .SetNetworkSpecifier(specifier) // we want _our_ network .Build(); var connectivityManager = this.GetSystemService(Context.ConnectivityService) as ConnectivityManager; connectivityManager.RequestNetwork(request, callback); 

Here is an example of wanting to connect to the network with SSID “cyberdyne” and passphrase “ill be back”. The transport type specifies what kind of network you want to connect to. In this case it is a WiFi network. We do not require any Internet capability on the network. Per default it requests Internet, Not VPN and Trusted capabilities.

The callback looks something like this.

private class NetworkCallback : ConnectivityManager.NetworkCallback  public ActionNetwork> NetworkAvailable  get; set; > public override void OnAvailable(Network network)  base.OnAvailable(network); NetworkAvailable?.Invoke(network); > > var callback = new NetworkCallback  NetworkAvailable = network =>  // we are connected! > >; 

You can also use OnUnavailable to detect that we could not connect to the network in particular, or the user pressed cancel.

Connect to Device Request

If you connect once to a network request, any subsequent requests will automatically connect if you are in range of the network and the user will not have accept it again. Also, while the App is open and you want to disconnect from the requested network, you simply call ConnectivityManager.UnregisterNetworkCallback() on the callback.

This hopefully gives you an idea about how to connect to WiFi Networks with Android 10.

You can check out the code from my Android 10 WiFi Repository on GitHub and have a go at playing with it yourself.

Источник

Читайте также:  Pax d200 подключить wifi
Оцените статью
Adblock
detector