Android permission access wifi state

Unable to listen to android wi-fi manager’s state?

I am having some trouble with BroadCast receiver for checking the Wi-fi state. Could you please help? This is my manifest file.

public class MainActivity extends BroadcastReceiver < @Override public void onReceive(Context context, Intent intent) < int state = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, -1); String msg = null; switch (state) < case WifiManager.WIFI_STATE_DISABLED: msg = "it is disabled"; break; case WifiManager.WIFI_STATE_ENABLED: msg = "it is enabled"; break; case WifiManager.WIFI_STATE_DISABLING: msg = "it is switching off"; break; case WifiManager.WIFI_STATE_ENABLING: msg = "wifi is getting enabled"; break; default: msg = "not working properly"; break; >if (msg != null) < Log.d("************%%%%%%%%wifi state ", "WIFI" + msg); Toast.makeText(context, "Wifi state is" + msg, Toast.LENGTH_LONG) .show(); >> > 

I am unsure where am I making my mistake. Any input would be appreciated.
I am not getting any errors just that the log file doesn’t show the required message.

6 Answers 6

You have had not added the parameters for the intent filter, the final manifest should look like this

If you did not add the following permissions then try again after adding those.

I’ve just done as you said and my application forces shutdown. I’ve explained it in the previous comment please take a look at it and let me know where am I causing an error.

First, you should make sure you request the permission to get access to view WIFI state. Just do as Anup Rojekar said.

Second, I believe you make mistake in using a BroadcastReceiver. In your manifest.xml, you declare the MainActivity.

so the MainActivy is an Activity. Also, you declare the MainActivity as a broadcastReceiver. This is illegal. You should use a standalone broadcast to do so. Like this:

Please notice that I changed the name for the broadcastReceiver and inside the node, you should add a node like above.

Third, create a WifiBroadcastReceiver.java and copy the codes from your original MainActivity.java to it. Remember to change the class declaration to public class WifiBroadcastReceiver extends BroadcastReceiver

Hope I could help. Please tell me if it works. I don’t have a pc on hand; thus I don’ t test the codes either.

Also, you need a new MainActivity.java file. It could be generated automatically in Eclipse. This class should be declared like: public class MainActivity extends Activity .

Источник

Руководство Android Wifi Scanning

Следуйте за нами на нашей фан-странице, чтобы получать уведомления каждый раз, когда появляются новые статьи. Facebook

1- Android Wi-Fi

В Android, Wi-Fi это протокол беспроводной передачи (Wireless Network Protocol), позволяет устройствам подключиться к Internet (интернету) или подключение устройств друг к другу для обмена данных.

Точнее, Android предоставляет Wi-Fi API, приложения могут использовать данный API для управления всех аспектов связанных с подключением к Wifi, например поиск текущих сетей Wifi, добавить, сохранить, удалить сети Wifi и управлять обменявшимися данными между устройствами.

Читайте также:  Настройка вай фай cisco packet tracer

  1. Сканировать (scan) для поиска готовых сетей Wifi в диапазоне.
  2. Позволить устройству подключиться к Internet.
  3. Подключить к другим устройствам через Service Discovery (Обнаружение сервисов).
  4. Управлять списком конфигурированных сетей.
  5. Управлять многими подключениями.

Начиная с Android 10.0 (API Level 29) вы не можете использовать Wi-Fi API чтобы включить/выключить (enable/disable) Wifi системы, это значит если вы хотите включить/выключить Wifi​​​​​​​, вам нужно использовать готовые функции операционной системы.

Политика конфиденциальности для использования Wi-Fi API чтобы включить/выключить Wifi была изменена через многие версии Android. Точнее:

Android Level Политика конфиденциальности
Level 1 ==> Level 22
(Android < 6.0)
Нужно добавить android.permission.CHANGE_WIFI_STATE в AndroidManifest.xml.
Level 23 ==> Level 28
(Android 6.0 — 9.x)
Нужно добавить android.permission.CHANGE_WIFI_STATE в AndroidManifest.xml, одновременно, ваше приложение должно спросить разрешение пользователя, чтобы включить/выключить Wifi системы.
Level 29+
(Android 10.0+)
Не разрешать использовать Wi-Fi API​​​​​​​, чтобы включить/выключить Wifi системы.
 WifiManager wifiManager = (WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE); wifiManager.setWifiEnabled(true); // Enable Wifi wifiManager.setWifiEnabled(false); // Disable Wifi 

В Android 10+ (API Level 29+), метод setWifiEnabled(boolean) больше не работает.

Чтобы получить статус Wifi, вам нужно добавить android.permission.ACCESS_WIFI_STATE в 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++) < // . >> 

Политика конфиденциальности для сканирования (scan) текущих сетей так же была изменена через разные версии Android:

Android API Level Политика конфиденциальности
Level 1 ==> Level 22
(Android < 6.0)
Нужно добавить android.permission.ACCESS_COARSE_LOCATION в AndroidManifest.xml.
Level 23+
(Android 6.0+)
Нужно добавить android.permission.ACCESS_COARSE_LOCATION в AndroidManifest.xml, одновременно ваше приложение должно спросить разрешение пользователся сканировать (scan) текущие сети.

2- Пример WifiManager

В данном примере я покажу вам как использовать WifiManager​​​​​​​, чтобы получить статус Wifi, сканировать текущие сети, записать детальную информацию каждой найденной сети и подключить к определенной сети в списке.

  • 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:

    Это онлайн курс вне вебсайта o7planning, который мы представляем, он включает бесплатные курсы или курсы со скидкой.

    • 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
    • Unity Android Game Development : Build 7 2D & 3D Games
    • The Complete Android™ Material Design Course
    • 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
    • Developing High Quality Android Applications
    • Android App Development and Design
    • 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 )
    • Android Internals and Working with the source

    Источник

    What’s the difference between access network state (ACCESS_NETWORK_STATE) and WIFI state (ACCESS_WIFI_STATE) permissions?

    In Permissions tab of Android Manifest, in the drop down there are options called android.permission.ACCESS_NETWORK_STATE and android.permission.ACCESS_WIFI_STATE . What is the difference between them? Is ACCESS_NETWORK_STATE more generalized than ACCESS_WIFI_STATE ?

    3 Answers 3

    android.permission.ACCESS_NETWORK_STATE is needed for accessing ConnectivityManager (mainly for monitoring network connections in general), while android.permission.ACCESS_WIFI_STATE grants access to WifiManager (for managing all aspects of Wi-Fi connectivity in particular).

    So if I use ACCESS_NETWORK_STATE, and check connectivity: if on WiFi will it return online or offline? Do I need to check both?

    See developer.android.com/training/basics/network-ops/managing.html for a useful function (isOnline) that tells whether there is an internet connection at all.

    ACCESS_NETWORK_STATE can be used to check the general network state (i.e. connecting, connected) even if it’s Wifi by using the ConnectivityManager’s getActiveNetworkInfo() method.

    ACCESS_NETWORK_STATE is required to check if you are connected to a network, it does not matter of what type it is (Wi-Fi, GPRS, UMTS, etc.).

    ACCESS_WIFI_STATE is not required to prope for internet connections.

    To answer most of the questions, yes you don’t need the ACCESS_WIFI_STATE if merely checking for connectivity.

    Network state refers to cellular network connectivity.

    Wifi state refers to the state of the phone’s Wifi connection.

    Not exactly, see developer.android.com/training/basics/network-ops/managing.html where it uses ‘network status’ to refer to any internet connection regardless of type. It distinguishes between ConnectivityManager.TYPE_MOBILE and ConnectivityManager.TYPE_WIFI. It even gives example code for useful function (isOnline) that tells whether there is an internet connection at all.

    Источник

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