Open In App

How to Use Nearby Wi-Fi Access Permission in Android 13?

Improve
Improve
Like Article
Like
Save
Share
Report

Before Android 13 when any android application want to use any wifi related feature within the android application. We have to provide users with fine location permission along with wifi permission to use wifi-related features within the android application. In the new android 13 updates where we can use some of the Wi-Fi-related functionalities without the requirement of any Location permission. In this article, we will be building a simple application in which we will be using nearby Wi-FI access location permission to use Hotspot functionality within our android application. 

Step-By-Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.

Step 2: Updating SDK version in build.gradle file.

Navigate to Gradle Scripts>module level build.gradle file and add change compile SDK and target SDK to 33. After that simply sync your project to install it.

Step 3: Working with activity_main.xml.

Navigate to app>res>layout>activity_main.xml and add the below code to it. Comments are added in the code to get to know it in detail. 

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
  
    <!-- text view for displaying hot spot status-->
    <TextView
        android:id="@+id/idTVHotspotStatue"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_margin="5dp"
        android:gravity="center"
        android:padding="4dp"
        android:text="Hotspot"
        android:textAlignment="center"
        android:textAllCaps="false"
        android:textColor="@color/black"
        android:textStyle="bold" />
  
    <!--creating button on add quick tile settings-->
    <Button
        android:id="@+id/idBtnHotspot"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/idTVHotspotStatue"
        android:layout_centerInParent="true"
        android:layout_margin="20dp"
        android:text="Start Hotspot"
        android:textAlignment="center"
        android:textAllCaps="false"
        app:background="@color/edt_back_color"
        app:backgroundTint="@color/edt_back_color" />
</RelativeLayout>


Step 4: Working with MainActivity.kt file. 

Navigate to app>java>your app’s package name>MainActivity.kt file and add the below code to it. Comments are added in the code to get to know it in detail. 

Kotlin




import android.R.attr
import android.annotation.SuppressLint
import android.app.StatusBarManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.drawable.Icon
import android.net.Uri
import android.net.wifi.WifiManager
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import java.util.jar.Manifest
  
class MainActivity : AppCompatActivity() {
    // creating variables on below line.
    private lateinit var permissionLauncher: ActivityResultLauncher<String>
    private lateinit var startHotspotBtn: Button
    private lateinit var statusTV: TextView
  
    // on below line creating and initializing wifi manager.
    private val wifiManager: WifiManager by lazy {
        applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
    }
  
    @SuppressLint("WrongConstant")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
  
        // on below line initializing request permission launcher.
        permissionLauncher = registerForActivityResult(
            // on below line requesting permission.
            ActivityResultContracts.RequestPermission()
        ) { isGranted: Boolean ->
            if (isGranted) {
                // if permission is already granted we are starting the device hotspot.
                startHotSpot()
            } else {
                // displaying toast message if permissions are not provided.
                Toast.makeText(
                    this,
                    "Please allow the Nearby Wi-Fi Devices permission for this app",
                    Toast.LENGTH_LONG,
                ).show()
            }
        }
  
        // initializing variables on below line.
        startHotspotBtn = findViewById(R.id.idBtnHotspot)
        statusTV = findViewById(R.id.idTVHotspotStatue)
  
        // adding click listener for button on below line.
        startHotspotBtn.setOnClickListener {
            // on below line calling method to check permissions.
            checkPermissions()
        }
    }
  
    @SuppressLint("InlinedApi")
    private fun checkPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // on below line creating a variable for wifi permission.
            val permission: String = android.Manifest.permission.NEARBY_WIFI_DEVICES
            when {
                // on below line checking weather permissions are granted or not.
                ContextCompat.checkSelfPermission(
                    this, permission,
                ) == PackageManager.PERMISSION_GRANTED -> {
                    // if permission are granted starting hotspot by calling below method.
                    startHotSpot()
                }
                // below method is called when permissions are not granted .
                // below method is use to display prompt message when permissions are not provided.
                shouldShowRequestPermissionRationale(permission) -> {
                    MaterialAlertDialogBuilder(this).setMessage("This app would not work without Nearby Wi-Fi Devices permission. Do you want to give this app the permission?")
                        .setPositiveButton("Yes") { _, _ ->
                            permissionLauncher.launch(permission)
                        }.setNegativeButton("No Thanks") { _, _ ->
  
                        }.show()
                }
                else -> {
                    // on below line calling method to request permissions.
                    permissionLauncher.launch(permission)
                }
            }
        } else {
            // if device is not a android 13 device displaying below toast message.
            Toast.makeText(
                this,
                "Please use Android 13 device.",
                Toast.LENGTH_SHORT,
            ).show()
        }
    }
  
    @SuppressLint("NewApi")
    private fun startHotSpot() {
        // below method is use to start local hotspot.
        wifiManager.startLocalOnlyHotspot(
            object : WifiManager.LocalOnlyHotspotCallback() {
                override fun onStarted(reservation: WifiManager.LocalOnlyHotspotReservation?) {
                    super.onStarted(reservation)
                    // this method is called when hotspot is started.
                    // on below line disabling button and changing status text view.
                    startHotspotBtn.isEnabled = false
                    statusTV.text = "Status Local Only Hotspot: STARTED"
                }
  
                override fun onFailed(reason: Int) {
                    // this method is called when device fails to start hotspot.
                    super.onFailed(reason)
                    // displaying error toast message on below line.
                    Toast.makeText(
                        this@MainActivity,
                        "Error Local Only Hotspot: $reason",
                        Toast.LENGTH_SHORT,
                    ).show()
                }
  
                override fun onStopped() {
                    // below method is called when the app has stopped due to any reason.
                    super.onStopped()
                    startHotspotBtn.isEnabled = true
                    statusTV.text = "Status Local Only Hotspot: STOPPED"
                }
            },
            null,
        )
    }
}


Step 5: Adding permissions for using Wifi in the AndroidManifest.xml file. 

Navigate to app>AndroidManifest.xml file and add the below permissions to it. 

<uses-permission
    android:name="android.permission.NEARBY_WIFI_DEVICES"
    android:usesPermissionFlags="neverForLocation" />
<!-- permission for Hotspot -->
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />

Output:



Last Updated : 28 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads