Permission to access wifi in android

Permission to access wifi in android

В этот раз мы научимся простой но нужной вещи — включать и выключать на Android устройстве Wi-Fi соединение. Процесс взаимодействия с Wi-Fi довольно простой, но тем не менее, в нем надо разобраться. Программа будет состоять из переключателя Toggle Button, нажатие по которому будет включать и выключать Wi-Fi соединение.

Для начала, создадим новый проект, выбираем Blank Activity. Первым делом нужно открыть файл AndroidManifest.xml и добавить разрешения на получение текущего статуса Wi-Fi и возможности смены статуса:

uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> 

Теперь сделаем интерфейс нашему приложению. Для этого откроем файл activity_main.xml и добавим туда картинку (для красоты) и переключатель Toggle Button:

LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:padding="5dp"> ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:src="@drawable/wifi" android:layout_gravity="center"/> ToggleButton android:id="@+id/wifi_switcher" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_marginBottom="10dp" android:checked="false" android:text="Wi-Fi Settings" android:textOff="Выкл" android:textOn="Вкл" android:layout_gravity="center"/> /LinearLayout> 

Я использовал эту картинку:

Картинка для вай фай

Ну а вы можете взять любую другую.

Теперь переходим к работе с кодом в MainActivity.java. Здесь мы объявим и инициализируем Toggle Button, установим для него слушателя изменения состояний OnCheckedChangeListener, ну и основное, опишем метод включения и выключения Wi-Fi соединения в зависимости от того, какое значение принимает переключатель Toggle Button: если он находиться в состоянии isChecked, то есть включенном, соответственно этому состоянию включаем на устройстве Wi-Fi, в противном случае — выключаем.

Доступ к управлению Wi-Fi соединением происходит через WifiManager, мы создаем экземпляр такого менеджера и с его помощью включаем или выключаем Wi-Fi, в команде setWifiEnabled () выставляя значение true для включения Wi-Fi, и false — для выключения. Код файла MainActivity.java будет следующим:

import android.net.wifi.WifiManager; import android.os.Bundle; import android.widget.CompoundButton; import android.widget.Toast; import android.app.Activity; import android.content.Context; import android.widget.ToggleButton; public class MainActivity extends Activity < @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Инициализируем элемент Toggle Button: ToggleButton toggle = (ToggleButton) findViewById(R.id.wifi_switcher); //Настраиваем слушателя изменения состояния переключателя: toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() < public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) < //Если Wi-FI включен - Toast сообщение об этом: if (isChecked) < toggleWiFi(true); Toast.makeText(getApplicationContext(), "Wi-Fi Включен!", Toast.LENGTH_SHORT).show(); > //Если Wi-FI выключен - Toast сообщение об этом: else < toggleWiFi(false); Toast.makeText(getApplicationContext(), "Wi-Fi Выключен!", Toast.LENGTH_SHORT).show(); > > >); > //Описываем сам метод включения Wi-Fi: public void toggleWiFi(boolean status) < WifiManager wifiManager = (WifiManager) this .getSystemService(Context.WIFI_SERVICE); //Статус true соответствует включенному состоянию Wi-Fi, мы включаем //его с помощью команды wifiManager.setWifiEnabled(true): if (status == true && !wifiManager.isWifiEnabled()) < wifiManager.setWifiEnabled(true); > //А статус false соответствует выключенному состоянию Wi-Fi мы выключаем // его с помощью команды wifiManager.setWifiEnabled(false): else if (status == false && wifiManager.isWifiEnabled()) < wifiManager.setWifiEnabled(false); > > > 

Попробуем теперь наше приложение на работоспособность. Запускаем и смотрим на результат:

Источник

Permission for accessing WIFI in android 6

if that was in Dangerous permission list so than you need run time permission like android M. just go though this link You are requesting the wrong runtime permission. Question: 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.

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); > > 

Kindly help me to solve this . Thanks in advance .

You are requesting the wrong runtime permission. As per the Android 6.0 changes:

To access the hardware identifiers of nearby external devices via Bluetooth and Wi-Fi scans, your app must now have the ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION permissions

You must request and be granted one of those runtime permissions to do wifi scans.

It seems in order to work well with WifiManager when scanning the Connections from Android 6.0 it needs to access your location, so that is either the fine location or the coarse location, I added the following to my Manifest file:

I think this is what you need.
Application (WiFi connections) doesn’t work anymore on Android 6.0 Marshmallow

you need to look at the permissions if that is in automatically granted permission list or in Dangerous permission list. if that was in Dangerous permission list so than you need run time permission like android M. just go though this link You are requesting the wrong runtime permission. ACCESS_WIFI_STATE permission is in automatically granted permissions no need to access it runtime.

| Android Developers, Google Play uses the elements declared in your app manifest to filter your app from devices that do not meet its hardware and software

What permission do I need to access Internet from an Android

Android Studio #3: Add Internet Access Permission to App #Andorid

AndroidManifest.xml in Android StudioAndroid Developer Tutorial #3.
Duration: 1:20

Adding Internet Permission

This video is part of an online course, Developing Android Apps. Check out the course here Duration: 0:47

How to check if android application has permission to use cellular internet?

I’m trying to find a way to retrieve information about mobile data permissions that user can set for any application. According to this article i can use ConnectivityManager.getRestrictBackgroundStatus(), but it’s all about background data, whereas i need information about full restriction.

UPDATE: added screenshot to clarify option than i meant. mobile data settings

private boolean checkPermission()

Request location permissions, If your app needs to pair a device with nearby devices over Bluetooth or Wi-Fi, consider using companion device pairing or Bluetooth permissions, instead of

Is permission needed when choosing image from gallery on android?

i’m currently making an apps that can upload choosen image from gallery to mysql database via php, but now i’m in confuse because i read on android 11 or above you need a storage access permission. So, is permission to access the storage is needed when you only need to choose image from gallery?

No you do not need any permission using ACTION_PICK, action_get_content or ACTION_OPEN_DOCUMENT.

Yes, your app must have the permission and you have to prompt the user to accept that permission to be able to pick files from gallery

Android user-permission to access Internet, Moving the uses-permission tag to before the application tag should have removed the warning. Try doing a clean on your project if you are

Источник

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); > > 

Источник

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