Can't connect to WiFi network

℡╲_俬逩灬. 提交于 2019-12-02 04:46:06

Connection information can arrive asynchronously, so you cannot know in the code you mentioned wether the connection was successful or not. You can try to implement a BroadcastReceiver, that gets the information of the wifi connection.

public class ConnectivityChangedReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] netInf = conMgr.getAllNetworkInfo();

        for (NetworkInfo inf : netInf) {
            if (inf.getTypeName().contains("wifi")) {
                if (inf.isConnected()) {
                    Toast.makeText(context, "Connected to Wifi", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(context, "Could not connect to wifi", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }
}

Then, in your android manifest you should declare it as beeing a receiver, like this:

<receiver android:name=".YourPackageName.ConnectivityChangedReceiver" >
    <intent-filter>
        <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
        <action android:name="android.net.wifi.STATE_CHANGE" />
        </intent-filter>
</receiver>

I am just trying this on my own now, but I think that this is the correct workaround for this issue, as Wifimanager.reconnect() didn't really connected me to the configured network. Best of luck.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!