summaryrefslogtreecommitdiff
path: root/st_android/app/src/main/java/com/example/mylauncher/WifiConnectionManager.java
blob: 8c93563ff04aaa15f2286c40decdac42653e996e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
package com.example.mylauncher;

import android.content.Context;
import android.net.wifi.WifiManager;
import android.widget.Toast;
import android.util.Log;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import android.net.wifi.ScanResult;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;

public class WifiConnectionManager {
    private static final String TAG = "WifiConnectionManager";
    private final Context context;
    private final MainActivity activity;
    private final WifiManager wifiManager;

    public WifiConnectionManager(Context context, MainActivity activity) {
        this.context = context;
        this.activity = activity;
        this.wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    }

    public List<String> getKnownNetworks() {
        try {
            Log.d(TAG, "Getting list of known networks...");
            String result = executeCommandWithOutput("cmd wifi list-networks");
            Log.d(TAG, "Raw output from list-networks command: " + result);

            List<String> knownNetworks = new ArrayList<>();


            String[] lines = result.split("\n");
            for (String line : lines) {
                Log.d(TAG, "Processing line: '" + line + "'");

                if (!line.trim().isEmpty() && !line.contains("Network") && !line.contains("Error:")) {

                    String[] parts = line.trim().split("\\s+");
                    if (parts.length >= 2) {
                        String networkName = parts[1];
                        Log.d(TAG, "Found network name: " + networkName);
                        if (!knownNetworks.contains(networkName)) {
                            knownNetworks.add(networkName);
                        }
                    }
                }
            }

            Log.d(TAG, "Final list of known networks: " + knownNetworks);
            return knownNetworks;
        } catch (Exception e) {
            Log.e(TAG, "Error getting known networks", e);
            return new ArrayList<>();
        }
    }

    public void connectToWifi(final String ssid, boolean isKnown) {
        try {
            Log.d(TAG, "Starting WiFi connection process for: " + ssid + " (Known: " + isKnown + ")");

            String wifiState = executeCommandWithOutput("cmd wifi status");
            Log.d(TAG, "Current WiFi state: " + wifiState);

            executeCommand("svc wifi enable");
            Thread.sleep(2000);

            if (!isKnown) {
                boolean isSecured = false;
                for (ScanResult result : wifiManager.getScanResults()) {
                    if (result.SSID.equals(ssid)) {
                        isSecured = result.capabilities != null &&
                                  (result.capabilities.contains("WEP") ||
                                   result.capabilities.contains("PSK") ||
                                   result.capabilities.contains("EAP"));
                        Log.d(TAG, "Network " + ssid + " security: " + result.capabilities);
                        break;
                    }
                }

                if (isSecured) {
                    Log.d(TAG, "Network is secured, prompting for password");
                    activity.runOnUiThread(() -> {
                        activity.promptForPassword(ssid);
                    });
                    return;
                }
            }

            String result = executeCommandWithOutput(
                String.format("cmd wifi connect-network %s", ssid)
            );
            Log.d(TAG, "Connect result: " + result);

            Thread.sleep(2000);
            String finalState = executeCommandWithOutput("cmd wifi status");
            Log.d(TAG, "Final state: " + finalState);

            activity.runOnUiThread(() ->
                Toast.makeText(context, "Connection attempt completed for " + ssid,
                    Toast.LENGTH_SHORT).show()
            );

        } catch (Exception e) {
            Log.e(TAG, "Error in connectToWifi", e);
            activity.runOnUiThread(() -> {
                Toast.makeText(context, "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            });
        }
    }

    public void connectToNetwork(String ssid, String password) {
        try {
            Log.d(TAG, "Attempting to connect to secured network: " + ssid);

            String connectCommand = String.format("cmd wifi connect-network %s wpa2 %s", ssid, password);
            String result = executeCommandWithOutput(connectCommand);
            Log.d(TAG, "Connect command result: " + result);

            Thread.sleep(2000);
            String finalState = executeCommandWithOutput("cmd wifi status");
            Log.d(TAG, "Final state after secured connection: " + finalState);

            activity.runOnUiThread(() ->
                Toast.makeText(context, "Connection attempt completed for " + ssid,
                    Toast.LENGTH_SHORT).show()
            );

        } catch (Exception e) {
            Log.e(TAG, "Error in connectToNetwork", e);
            activity.runOnUiThread(() -> {
                Toast.makeText(context, "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            });
        }
    }

    private void executeCommand(String command) throws Exception {
        Process process = Runtime.getRuntime().exec("su");
        DataOutputStream os = new DataOutputStream(process.getOutputStream());
        os.writeBytes(command + "\n");
        os.writeBytes("exit\n");
        os.flush();
        process.waitFor();
    }

    private String executeCommandWithOutput(String command) throws Exception {
        Process process = Runtime.getRuntime().exec("su");
        DataOutputStream os = new DataOutputStream(process.getOutputStream());
        os.writeBytes(command + "\n");
        os.writeBytes("exit\n");
        os.flush();

        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        StringBuilder output = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            output.append(line).append("\n");
        }

        reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        while ((line = reader.readLine()) != null) {
            output.append("Error: ").append(line).append("\n");
        }

        process.waitFor();
        return output.toString();
    }
}