Search code examples
javaandroidandroid-wifi

How to make a custom page to connect to Wi-Fi in Android?


I am new to android and I am working on a single-mode application for Android TV. my target SDK is 30. I am trying to create a custom page to get a list of all wifi and connect to the wifi. Is there any example to do so? because the ones I saw were either using android wifi intent or when I am trying to scan the list from the following code. it won't run even though I assigned all the permissions.

But if anyone can provide a code for creating a custom page to connect to wifi, that would be so helpful.

public class WifiActivity extends AppCompatActivity {

/*    private ListView wifiList;
private WifiManager wifiManager;
private final int MY_PERMISSIONS_ACCESS_COARSE_LOCATION = 1;
WifiChangeBroadcastReceiver receiverWifi;
@Override

private ListView wifiList;
private WifiManager wifiManager;
private final int MY_PERMISSIONS_ACCESS_COARSE_LOCATION = 1;
WifiChangeBroadcastReceiver receiverWifi;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_wifi);
    wifiList = findViewById(R.id.wifiList);
    Button buttonScan = (Button) findViewById(R.id.scanBtn);
    wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    if (!wifiManager.isWifiEnabled()) {
        Toast.makeText(getApplicationContext(), "Turning WiFi ON...", Toast.LENGTH_LONG).show();
        wifiManager.setWifiEnabled(true);
    }
    buttonScan.setOnClickListener(v -> {
        if (ActivityCompat.checkSelfPermission(WifiActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION)
        != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(
                    WifiActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSIONS_ACCESS_COARSE_LOCATION);
        } else {

            wifiManager.startScan();
        }
    });
}
@Override
protected void onPostResume() {
    super.onPostResume();
    receiverWifi = new WifiChangeBroadcastReceiver(wifiManager, wifiList);
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
    registerReceiver(receiverWifi, intentFilter);
    getWifi();
}
private void getWifi() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        Toast.makeText(this, "version> = marshmallow", Toast.LENGTH_SHORT).show();
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this, "location turned off", Toast.LENGTH_SHORT).show();
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSIONS_ACCESS_COARSE_LOCATION);
        } else {
            Toast.makeText(this, "location turned on", Toast.LENGTH_SHORT).show();
            wifiManager.startScan();
        }
    } else {
        Toast.makeText(this, "scanning", Toast.LENGTH_SHORT).show();
        wifiManager.startScan();
    }
}
@Override
protected void onPause() {
    super.onPause();
    unregisterReceiver(receiverWifi);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode) {
        case MY_PERMISSIONS_ACCESS_COARSE_LOCATION:
            if (grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this, "permission granted", Toast.LENGTH_SHORT).show();
            wifiManager.startScan();
        } else {
            Toast.makeText(this, "permission not granted", Toast.LENGTH_SHORT).show();
            return;
        }
        break;
    }
}
}

Solution

  • i did some research and solved this issue. Here is the solution if anyone wants help. in android 10+, (SDK 29+) you can use WifiNetworkSpecifier to connect to the internet.

                                        WifiNetworkSpecifier.Builder builder = null;
                                        WifiNetworkSpecifier wifiNetworkSpecifier = null;
                                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                                            builder = new WifiNetworkSpecifier.Builder();
    
                                            builder.setSsid(networkSSID);
    
                                            builder.setWpa2Passphrase(networkPass);
                                            wifiNetworkSpecifier = builder.build();
    
                                            NetworkRequest.Builder networkRequestBuilder = new NetworkRequest.Builder();
                                            networkRequestBuilder.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
                                            networkRequestBuilder.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED);
                                            networkRequestBuilder.addCapability(NetworkCapabilities.NET_CAPABILITY_TRUSTED);
                                            networkRequestBuilder.setNetworkSpecifier(wifiNetworkSpecifier);
                                            NetworkRequest networkRequest = networkRequestBuilder.build();
                                            ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                                            if (cm != null) {
    
                                                cm.requestNetwork(networkRequest, new ConnectivityManager.NetworkCallback() {
                                                    @Override
                                                    public void onAvailable(@NonNull Network network) {
    
                                                        super.onAvailable(network);
                                                    }
                                                });
                                            }
                                        }