Search code examples
androidwifi

Add WiFi network via ACTION_WIFI_ADD_NETWORKS intent


I am trying to connect to a WiFi network using the new Wifi suggest API. Specifically I want to add the network to the list, so as the documentation says I have to implement this intent.

This is what I have right now:

val suggestion = if (wifiConnection.authentication == AUTHENTICATION_NOPASS) {
    WifiNetworkSuggestion.Builder()
            .setSsid(wifiConnection.ssid)
            .build()
} else {
    WifiNetworkSuggestion.Builder()
            .setSsid(wifiConnection.ssid)
            .setWpa2Passphrase(wifiConnection.password)
            .build()
}

val intent = Intent(ACTION_WIFI_ADD_NETWORKS)
intent.putExtra(EXTRA_WIFI_NETWORK_LIST, arrayListOf(suggestion))
startActivityForResult(intent, 1002)

However when I run this code I get the following crash:

2020-10-12 16:38:48.291 17001-17001/com.my.app E/AndroidRuntime: FATAL EXCEPTION: main Process: com.my.app PID: 17001 android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.settings.WIFI_ADD_NETWORKS } at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:2076) at android.app.Instrumentation.execStartActivity(Instrumentation.java:1720) at android.app.Activity.startActivityForResult(Activity.java:5258) at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:676) at android.app.Activity.startActivityForResult(Activity.java:5203) at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:663) at com.my.app.presentation.ui.activity.ConnectActivity.connectApi29(ConnectActivity.kt:504) at com.my.app.presentation.ui.activity.ConnectActivity.connect(ConnectActivity.kt:343) at com.my.app.presentation.ui.activity.ConnectActivity.access$connect(ConnectActivity.kt:70) at com.my.app.presentation.ui.activity.ConnectActivity$setReadyState$1.onClick(ConnectActivity.kt:334) at android.view.View.performClick(View.java:7862) at android.widget.TextView.performClick(TextView.java:15004) at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:992) at android.view.View.performClickInternal(View.java:7831) at android.view.View.access$3600(View.java:879)

What is the correct way of opening the WiFi list to enable the user to chose the suggested network for addition?


Solution

  • This intent action is added in API Level 30 so if you are running this code on the device running on API Level 29 or below, it won't work. Please make sure the device or emulator is running on API Level 30.