简体   繁体   中英

Android 8+ -How to connect to wifi network programmatically in android?

working with Android 8+ using Android Studio 3.6.3 with api target 29, Below code reflects the use of setting user's added wifi configuration, which establishes the connection between the two devices and keep it alive until user disconnects any one of them, below code tries to get the data input and tries to connect to the given configuration, but on running app I'm getting class java.lang.NoClassDefFoundError.

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.net.MacAddress;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiNetworkSuggestion;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Button;

import java.util.Collections;

public class MainActivity extends AppCompatActivity {
    EditText etssid, etpass;
    Button btconnect;
    String id, pass;
    Context context = this;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        etssid = findViewById(R.id.etssid);
        etpass = findViewById(R.id.etpass);
        btconnect = findViewById(R.id.btnconnect);

        btconnect.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.P)
            @Override
            public void onClick(View v) {
                id = etssid.getText().toString();
                pass = etpass.getText().toString();
                final WifiNetworkSuggestion conf = new WifiNetworkSuggestion.Builder()
                        .setBssid(MacAddress.fromString(id))
                        .setWpa2Passphrase(pass)
                        .setIsAppInteractionRequired(false)
                        .build();
                final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                final int status = wifiManager.addNetworkSuggestions(Collections.singletonList(conf));
                if(status != WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS)
                {
                    //error handling
                }
            }
        });
    }
}

On pressing connect button show following error while deb

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.client, PID: 6553
    java.lang.NoClassDefFoundError: Failed resolution of: Landroid/net/wifi/WifiNetworkSuggestion$Builder;
        at com.example.client.MainActivity$1.onClick(MainActivity.java:38)
        at android.view.View.performClick(View.java:6294)
        at android.view.View$PerformClick.run(View.java:24774)
        at android.os.Handler.handleCallback(Handler.java:790)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6518)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
     Caused by: java.lang.ClassNotFoundException: Didn't find class "android.net.wifi.WifiNetworkSuggestion$Builder" on path: DexPathList[[zip file "/data/app/com.example.client-YUhhKlGEU_94ZLx0o-xLOA==/base.apk"],nativeLibraryDirectories=[/data/app/com.example.client-YUhhKlGEU_94ZLx0o-xLOA==/lib/arm64, /system/lib64, /system/vendor/lib64]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:125)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
        at com.example.client.MainActivity$1.onClick(MainActivity.java:38) 
        at android.view.View.performClick(View.java:6294) 
        at android.view.View$PerformClick.run(View.java:24774) 
        at android.os.Handler.handleCallback(Handler.java:790) 
        at android.os.Handler.dispatchMessage(Handler.java:99) 
        at android.os.Looper.loop(Looper.java:164) 
        at android.app.ActivityThread.main(ActivityThread.java:6518) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)ugging,

It's because that API was added in SDK 29 as seen here:

https://developer.android.com/reference/android/net/wifi/WifiNetworkSuggestion

It simply doesn't exist on < 29. If you lower your SDK to target 28, it wont find your import either in the class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM