Arman Ghaffarian
Arman Ghaffarian

Reputation: 413

Ask user to connect to a specific WiFi flutter

I need to connect the user's device to a specific WiFi. I have used some of packages like wifi_iot but According to google, In Android API Version > 29, We can not directly connect the user device to a specific WiFi. Instead google suggests that using WifiNetworkSuggestion

I have 2 options :

  1. Use MethodChannel in flutter and implement WifiNetworkSuggestion in Kotlin and use it in my project.
  2. Inform user to connect to my specific wifi manually(and of course I have to show the password to user).
    Which of these options you recommend? and I don't have any experience on implementing option 1. is It possible to implement something like this in flutter project ? And if you can come up with another option, I would be glad to share it with me.

Upvotes: 1

Views: 2913

Answers (1)

Arman Ghaffarian
Arman Ghaffarian

Reputation: 413

For anyone who want to Implement something like this in flutter : Before Android API Version 29, you can directly connect user's device to specific WiFi without any problem. but in API Version after 29 (Android >= 10), you cannot do this. you have to ask user if he/she wants to connect to your WiFi. So for example in flutter (note: you can not ask user to connect to wifi directly in dart code. so you have to write your logic in Kotlin or Java) you have to define Platform and configure channel to run kotlin or java code. (Writing custom platform-specific code

After that you can have something like this :

import io.flutter.embedding.android.FlutterActivity
import androidx.annotation.NonNull
import android.net.wifi.WifiNetworkSpecifier
import android.net.wifi.WifiConfiguration
import android.net.wifi.WifiManager
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import android.os.PatternMatcher
import android.net.NetworkRequest
import android.net.NetworkCapabilities
import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.util.Log


class MainActivity: FlutterActivity() {
    private val CHANNEL = "channelname/wifiworks"

    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler {
          call, result ->
          if (call.method == "getTest") {
            val temp = getTest(call.argument<String>("SSID").toString())
    
              result.success(temp)
          // Note: this method is invoked on the main thread.
          // TODO
          }
          if(call.method == "dc") {
              val temp = disconnect()
    
              result.success(temp)
          }
        }
    }
    private fun disconnect(): Int {
        if(android.os.Build.VERSION.SDK_INT >= 29)
        {
            val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            connectivityManager.unregisterNetworkCallback(mNetworkCallback)
        }
        return 3434;
    }
    private val mNetworkCallback = object : ConnectivityManager.NetworkCallback() {
            override fun onAvailable(network: Network) {
                //phone is connected to wifi network
                val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
                connectivityManager.bindProcessToNetwork(network)
            }
    }
    private fun getTest(ssid: String): Int {

        if(android.os.Build.VERSION.SDK_INT >= 29)
        {
            val specifier = WifiNetworkSpecifier.Builder()
            // .setSsidPattern(PatternMatcher("SSID", PatternMatcher.PATTERN_PREFIX))
            .setSsid(ssid)
            .setWpa2Passphrase("Your_Password")
            .build()
        val request = NetworkRequest.Builder()
            .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
            .setNetworkSpecifier(specifier)
            .build()

            val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        
        connectivityManager.requestNetwork(request, mNetworkCallback)

        // Release the request when done.
        //

        return 123
        }
        else {
            var networkSSID = ssid;
            var networkPass = "Your_Password";
            var conf = WifiConfiguration()
            conf.SSID = "\"" + networkSSID + "\""
            conf.preSharedKey = "\""+ networkPass +"\""
            var wifiManager = context.getSystemService(Context.WIFI_SERVICE) as WifiManager
            var netid = wifiManager.addNetwork(conf)
            wifiManager.disconnect()
            wifiManager.enableNetwork(netid, true)
            wifiManager.reconnect()
            return ssid.length
            
        }

        
    }
}

Hope this is helpful ;)

Upvotes: 2

Related Questions