How do I connect to a user-selected SSID?

0

I'm doing my thesis and I'm developing an Android app to set up home devices Iot (wifi). In this case, the devices are being simulated using a Rspberry Pi 3, which creates an access point (captive portal, without a password) with a known name, that is, AutoDevAP-NameOfDevice. My application is showing the existing SSID in the scope of the smartphone and allows the user to select one of the SSIDs and connect (in this case, the application is only implemented to connect with this type of SSID.)

The problem is: after the user selects the SSID to connect (AutoDevAP-SmartSwitch) I start another activity to connect to this ssid, however I am stuck because the smartphone never connects to it and I am using the same logic I have Used to develop an application to always connect to the same SSID without password, but it will not work. Initially I taught that the problem was in the listener adapter, but I debugged the code and it's not that problem.

My code: MainACtivity.java

    import android.app.Activity;
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.net.wifi.ScanResult;
    import android.net.wifi.WifiConfiguration;
    import android.net.wifi.WifiManager;
    import android.os.Handler;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.ArrayAdapter;
    import android.widget.ListView;
    import android.widget.Toast;
    import android.widget.ToggleButton;
    
    import java.util.List;
    
    public class MainActivity extends Activity {
    
    
        WifiManager wifiManager;
        private BroadcastReceiver wifiReciever;
        private ArrayAdapter adapter;
        ListView listview ;
        private String nameOfDev;
        private Handler mainHandler;
        private Thread connectAPThread;
        static String info = null;
        static String ssidInfo;
        static String devName;
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            listview= (ListView) findViewById(R.id.listView);
            adapter = new ArrayAdapter
                    (this,android.R.layout.simple_list_item_1);
    
            listview.setAdapter(adapter);
    
            wifiManager = (WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            mainHandler = new Handler(this.getMainLooper());
    
    
            wifiReciever = new WiFiScanReceiver();
            listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
    
                    String s = listview.getItemAtPosition(i).toString();
                    info =s;
                    Toast.makeText(getApplicationContext(), info, Toast.LENGTH_LONG).show();
                    ssidInfo= getSSIDInfo(info);
                    Toast.makeText(getApplicationContext(), ssidInfo, Toast.LENGTH_SHORT).show();
                    devName=getDeviceName(info);
                    Toast.makeText(getApplicationContext(), devName, Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(MainActivity.this,ConnectWifiActivity.class);
                    intent.putExtra("ssid",ssidInfo);
                    intent.putExtra("devName",devName);
                    startActivity(intent);
    
                }
            });
        }
    
    
        public String getSSIDInfo(String s){
            String[] things = s.split(",");
            String[] cenas = things[0].split(":");
            String ssid = cenas[1];
    //        Toast.makeText(getApplicationContext(), ssid, Toast.LENGTH_LONG).show();
    
           // Toast.makeText(getApplicationContext(), nameOfDev, Toast.LENGTH_LONG).show();
           return ssid;
    
        }
    
        public String getDeviceName(String s){
            String[] things = s.split(",");
            String[] cenas = things[0].split(":");
            String ssid = cenas[1];
    //        Toast.makeText(getApplicationContext(), ssid, Toast.LENGTH_LONG).show();
            String[] outras = ssid.split("-");
            String nameOfDev = outras[1];
            // Toast.makeText(getApplicationContext(), nameOfDev, Toast.LENGTH_LONG).show();
            return nameOfDev;
    
        }
        public void onToggleClicked(View view) {
    
            adapter.clear();
    
            ToggleButton toggleButton = (ToggleButton) view;
    
            if (wifiManager == null) {
                // Device does not support Wi-Fi
                Toast.makeText(getApplicationContext(), "Oop! Your device does not support Wi-Fi",
                        Toast.LENGTH_SHORT).show();
                toggleButton.setChecked(false);
    
            } else {
                if (toggleButton.isChecked()) { // To turn on Wi-Fi
    
    
                        Toast.makeText(getApplicationContext(), "Wi-Fi is turning on." +
                                        "\n" + "Scanning for access points...",
                                Toast.LENGTH_SHORT).show();
    
                        wifiManager.setWifiEnabled(true);
    
                        Toast.makeText(getApplicationContext(), "Wi-Fi is already turned on." +
                                        "\n" + "Scanning for access points...",
                                Toast.LENGTH_SHORT).show();
                     wifiManager.startScan();
    
                } else { // To turn off Wi-Fi
                    Toast.makeText(getApplicationContext(), "Wi-Fi is turned off.",
                            Toast.LENGTH_SHORT).show();
                    wifiManager.setWifiEnabled(false);
                }
            }
        }
    
   
    protected void onResume() {
        super.onResume();
        // Register the BroadcastReceiver for SCAN_RESULTS_AVAILABLE_ACTION
        IntentFilter filter = new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
        registerReceiver(wifiReciever, filter);
    }
    
        @Override
        protected void onPause() {
            super.onPause();
            unregisterReceiver(wifiReciever);
        }
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.wi_fi, menu);
            return true;
        }
    
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();
            if (id == R.id.action_settings) {
                return true;
            }
            return super.onOptionsItemSelected(item);
        }
    
   
    
        class WiFiScanReceiver extends BroadcastReceiver {
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action)) {
                    List<ScanResult> wifiScanResultList = wifiManager.getScanResults();
                    for(int i = 0; i < wifiScanResultList.size(); i++){
                        String hotspot = (wifiScanResultList.get(i)).toString();
                        adapter.add(hotspot);
    
                    }
                }
            }
        }
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    tools:context="bernardo.autodevconfiguration.MainActivity">

    <ToggleButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/toggleButton"
        android:textOn="Wi-Fi On"
        android:textOff="Wi-Fi Off"
        android:onClick="onToggleClicked"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/listView"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/toggleButton" />

</RelativeLayout>

ConnectWifiACtivity.java

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;

import java.util.List;

/**
 * Created by bernardo on 19-03-2017.
 */

public class ConnectWifiActivity extends Activity {


    private WifiManager wifiManager;
    private Handler mainHandler;

    private String ssid;
    private String devName;
    private Button connectButton;

    private Thread wifiThread;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_connctwifi);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);


        Intent intent = getIntent();
        ssid= intent.getStringExtra("ssid");
        devName=intent.getStringExtra("devName");
        connectButton = (Button)findViewById(R.id.connect);

        connectButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                //connectToAP();
                wifiThread = new Thread(runnable, "turn-on wifi");
                wifiThread.start();


            }
        });
        mainHandler = new Handler(this.getMainLooper());

    }


    Runnable runnable = new Runnable() {





        @Override
        public void run() {
            while (true) {
                wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
                if (wifiManager.isWifiEnabled()) {
                    Log.d("State", "wifi-on");
                    WifiConfiguration wfc = new WifiConfiguration();

                    wfc.SSID = "\"".concat(ssid).concat("\"");
                    wfc.status = WifiConfiguration.Status.DISABLED;
                    wfc.priority = 40;
                    wfc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                    wfc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
                    wfc.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
                    wfc.allowedAuthAlgorithms.clear();
                    wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
                    wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
                    wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
                    wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
                    wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
                    wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);


                    int networkId = wifiManager.addNetwork(wfc);
                    if (networkId != -1) {
                        // success, can call wfMgr.enableNetwork(networkId, true) to connect
                        wifiManager.enableNetwork(networkId, true);
                    }
                } else {
                    Log.d("not connected", "trying to connect");
                    Log.d("State", "set wifi on");

                    wifiManager.setWifiEnabled(true);
                    WifiConfiguration wfc = new WifiConfiguration();

                    wfc.SSID = "\"".concat(ssid).concat("\"");
                    wfc.status = WifiConfiguration.Status.DISABLED;
                    wfc.priority = 40;
                    wfc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                    wfc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
                    wfc.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
                    wfc.allowedAuthAlgorithms.clear();
                    wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
                    wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
                    wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
                    wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
                    wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
                    wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);


                    int networkId = wifiManager.addNetwork(wfc);
                    if (networkId != -1) {
                        // success, can call wfMgr.enableNetwork(networkId, true) to connect
                        wifiManager.enableNetwork(networkId, true);
                    }
                }
            }
        }
    };


}

activity_connctwifi.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    tools:context="bernardo.autodevconfiguration.ConnectWifiActivity">

    <Button
        android:text="Connect to your device"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/connect"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="109dp"
        android:onClick="selfDestruct"/>
    </RelativeLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="bernardo.autodevconfiguration">
    <uses-permission android:name="android.permission.INTERNET" />

    <uses-permission android:name="android.permission.CHANGE_CONFIGURATION" />

    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />



    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
                <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
                <!--<action android:name="android.net.wifi.STATE_CHANGE" />-->


                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>


        </activity>
        <activity
            android:name="bernardo.autodevconfiguration.ConnectWifiActivity">

            </activity>
    </application>

</manifest>
    
asked by anonymous 19.03.2017 / 17:57

0 answers