Android get wifi network

How to get name of wifi-network out of android using android API?

I thought that I should use NetworkInterface::getDisplayName. I got some name, but this name is different that this name which I can see, when I choosing to which network I want to connect.

4 Answers 4

WifiManager wifiMgr = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE); WifiInfo wifiInfo = wifiMgr.getConnectionInfo(); String name = wifiInfo.getSSID(); 
public String getWifiName(Context context) < WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); if (manager.isWifiEnabled()) < WifiInfo wifiInfo = manager.getConnectionInfo(); if (wifiInfo != null) < DetailedState state = WifiInfo.getDetailedStateOf(wifiInfo.getSupplicantState()); if (state == DetailedState.CONNECTED || state == DetailedState.OBTAINING_IPADDR) < return wifiInfo.getSSID(); >> > return null; > 

This (mix and match of various answers from Marakana and others) will simultaneously get everything you want to extract from:

  1. all wifi routers in range
  2. connected wifi router
  3. all stored wifi networks (on your device)
public String getCurrentSsid(Context context) < String ssid = null; ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (networkInfo.isConnected()) < final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); final WifiInfo connectionInfo = wifiManager.getConnectionInfo(); if (connectionInfo != null && !(connectionInfo.getSSID().equals(""))) < //if (connectionInfo != null && !StringUtil.isBlank(connectionInfo.getSSID())) < ssid = connectionInfo.getSSID(); >// Get WiFi status MARAKANA WifiInfo info = wifiManager.getConnectionInfo(); String textStatus = ""; textStatus += "\n\nWiFi Status: " + info.toString(); String BSSID = info.getBSSID(); String MAC = info.getMacAddress(); List results = wifiManager.getScanResults(); ScanResult bestSignal = null; int count = 1; String etWifiList = ""; for (ScanResult result : results) < etWifiList += count++ + ". " + result.SSID + " : " + result.level + "\n" + result.BSSID + "\n" + result.capabilities +"\n" + "\n=======================\n"; >Log.v(TAG, "from SO: \n"+etWifiList); // List stored networks List configs = wifiManager.getConfiguredNetworks(); for (WifiConfiguration config : configs) < textStatus+= "\n\n" + config.toString(); >Log.v(TAG,"from marakana: \n"+textStatus); > return ssid; > 

DISCLAIMER: while this is working code, not pseudo code, its only purpose is to illustrate the methods for data extraction from wifi connections and it should be adapted (and cleaned) before use.

Источник

How to get available wifi networks and display them in a list in android

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.

Step 2 − Add the following code to res/layout/activity_main.xml.

Step 3 − Add the following code to src/MainActivity.java

package com.example.myapplication; import android.Manifest; import android.content.Context; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.net.wifi.WifiManager; import android.os.Build; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; public class MainActivity extends AppCompatActivity < private ListView wifiList; private WifiManager wifiManager; private final int MY_PERMISSIONS_ACCESS_COARSE_LOCATION = 1; WifiReceiver receiverWifi; @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); wifiList = findViewById(R.id.wifiList); Button buttonScan = findViewById(R.id.scanBtn); wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE); if (!wifiManager.isWifiEnabled()) < Toast.makeText(getApplicationContext(), "Turning WiFi ON. ", Toast.LENGTH_LONG).show(); wifiManager.setWifiEnabled(true); >buttonScan.setOnClickListener(new View.OnClickListener() < @Override public void onClick(View v) < if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) ! = PackageManager.PERMISSION_GRANTED) < ActivityCompat.requestPermissions( MainActivity.this, new String[], MY_PERMISSIONS_ACCESS_COARSE_LOCATION); > else < wifiManager.startScan(); >> >); > @Override protected void onPostResume() < super.onPostResume(); receiverWifi = new WifiReceiver(wifiManager, wifiList); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION); registerReceiver(receiverWifi, intentFilter); getWifi(); >private void getWifi() < if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) < Toast.makeText(MainActivity.this, "version>= marshmallow", Toast.LENGTH_SHORT).show(); if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) ! = PackageManager.PERMISSION_GRANTED) < Toast.makeText(MainActivity.this, "location turned off", Toast.LENGTH_SHORT).show(); ActivityCompat.requestPermissions(MainActivity.this, new String[], MY_PERMISSIONS_ACCESS_COARSE_LOCATION); > else < Toast.makeText(MainActivity.this, "location turned on", Toast.LENGTH_SHORT).show(); wifiManager.startScan(); >> else < Toast.makeText(MainActivity.this, "scanning", Toast.LENGTH_SHORT).show(); wifiManager.startScan(); >> @Override protected void onPause() < super.onPause(); unregisterReceiver(receiverWifi); >@Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) < super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) < case MY_PERMISSIONS_ACCESS_COARSE_LOCATION: if (grantResults.length >0 && grantResults[0] = = PackageManager.PERMISSION_GRANTED) < Toast.makeText(MainActivity.this, "permission granted", Toast.LENGTH_SHORT).show(); wifiManager.startScan(); >else < Toast.makeText(MainActivity.this, "permission not granted", Toast.LENGTH_SHORT).show(); return; >break; > > >

Step 4 − Add the following code to src/WifiReceiver

package com.example.myapplication; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.wifi.ScanResult; import android.net.wifi.WifiManager; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; class WifiReceiver extends BroadcastReceiver < WifiManager wifiManager; StringBuilder sb; ListView wifiDeviceList; public WifiReceiver(WifiManager wifiManager, ListView wifiDeviceList) < this.wifiManager = wifiManager; this.wifiDeviceList = wifiDeviceList; >public void onReceive(Context context, Intent intent) < String action = intent.getAction(); if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action)) < sb = new StringBuilder(); ListwifiList = wifiManager.getScanResults(); ArrayList deviceList = new ArrayList<>(); for (ScanResult scanResult : wifiList) < sb.append("
").append(scanResult.SSID).append(" - ").append(scanResult.capabilities); deviceList.add(scanResult.SSID + " - " + scanResult.capabilities); > Toast.makeText(context, sb, Toast.LENGTH_SHORT).show(); ArrayAdapter arrayAdapter = new ArrayAdapter(context, android.R.layout.simple_list_item_1, deviceList.toArray()); wifiDeviceList.setAdapter(arrayAdapter); > > >

Step 5 − Add the following code to androidManifest.xml

Let’s try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project’s activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –

Click here to download the project code

Источник

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

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

1- Android Wi-Fi

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

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

  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

    Источник

    Читайте также:  Поменять пароль от вайфая ттк
Оцените статью
Adblock
detector