From 91a60683c57b3f6acc10c7229708d11630e76f97 Mon Sep 17 00:00:00 2001 From: yjj38 Date: Thu, 3 Jul 2025 14:12:02 +0800 Subject: [PATCH] =?UTF-8?q?refactor(proxy):=20=E9=87=8D=E6=9E=84=E4=BB=A3?= =?UTF-8?q?=E7=90=86=E5=B7=A5=E5=85=B7=E5=B9=B6=E6=B7=BB=E5=8A=A0=E5=9C=B0?= =?UTF-8?q?=E7=90=86=E4=BD=8D=E7=BD=AE=E6=A3=80=E6=9F=A5=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit -重写 ClashUtil 类中的 switchProxyGroup 方法,使用同步调用替代异步回调 - 新增 checkCountryIsUS 方法,用于检查当前设备是否位于美国 - 修改 MainActivity 中的 startProxyVpn 方法,集成新的地理位置检查逻辑 -优化任务执行流程,确保仅在代理 VPN 启动成功且设备位于美国时执行后续操作 - 修复了一些潜在的资源泄露问题,提高了代码的健壮性 --- .idea/misc.xml | 1 - .../com/example/studyapp/MainActivity.java | 39 +++++----- .../com/example/studyapp/proxy/ClashUtil.java | 78 +++++++++++++++---- 3 files changed, 80 insertions(+), 38 deletions(-) diff --git a/.idea/misc.xml b/.idea/misc.xml index cb150cf..8562ed5 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -1,4 +1,3 @@ - diff --git a/app/src/main/java/com/example/studyapp/MainActivity.java b/app/src/main/java/com/example/studyapp/MainActivity.java index 91b8c76..9e70c64 100644 --- a/app/src/main/java/com/example/studyapp/MainActivity.java +++ b/app/src/main/java/com/example/studyapp/MainActivity.java @@ -32,18 +32,12 @@ import androidx.work.WorkManager; import com.example.studyapp.autoJS.AutoJsUtil; import com.example.studyapp.device.ChangeDeviceInfoUtil; -import com.example.studyapp.device.LoadDeviceCallback; import com.example.studyapp.proxy.ClashUtil; import com.example.studyapp.service.MyAccessibilityService; import com.example.studyapp.task.TaskUtil; import com.example.studyapp.utils.LogFileUtil; -import com.example.studyapp.utils.ShellUtils; import com.example.studyapp.worker.CheckAccessibilityWorker; -import org.json.JSONObject; - -import java.io.File; -import java.io.IOException; import java.lang.ref.WeakReference; import java.util.UUID; import java.util.concurrent.ExecutorService; @@ -256,12 +250,12 @@ public class MainActivity extends AppCompatActivity { executorService.submit(() -> { try { ChangeDeviceInfoUtil.getAddDeviceInfo("US", 2, (bigoDevice, afDevice) -> { - startProxyVpn(MainActivity.this); - ChangeDeviceInfoUtil.changeDeviceInfo(getPackageName(), MainActivity.this, bigoDevice, afDevice); - AutoJsUtil.runAutojsScript(this); + if (startProxyVpn(MainActivity.this)){ + ChangeDeviceInfoUtil.changeDeviceInfo(getPackageName(), MainActivity.this, bigoDevice, afDevice); + AutoJsUtil.runAutojsScript(this); + } }); AutoJsUtil.registerScriptResultReceiver(this); - AutoJsUtil.flag = true; while (isRunning) { if (!isRunning) break; @@ -270,12 +264,13 @@ public class MainActivity extends AppCompatActivity { String currentScriptResult = scriptResultQueue.take(); ChangeDeviceInfoUtil.getAddDeviceInfo("US", 2, (bigoDevice, afDevice) -> { try { - startProxyVpn(MainActivity.this); - ChangeDeviceInfoUtil.changeDeviceInfo(getPackageName(), MainActivity.this, bigoDevice, afDevice); - AutoJsUtil.runAutojsScript(this); - if (currentScriptResult != null && !TextUtils.isEmpty(currentScriptResult)) { - TaskUtil.execSaveTask(this, androidId, taskId, currentScriptResult); - infoUpload(this, androidId, currentScriptResult); + if (startProxyVpn(MainActivity.this)){ + ChangeDeviceInfoUtil.changeDeviceInfo(getPackageName(), MainActivity.this, bigoDevice, afDevice); + AutoJsUtil.runAutojsScript(this); + if (currentScriptResult != null && !TextUtils.isEmpty(currentScriptResult)) { + TaskUtil.execSaveTask(this, androidId, taskId, currentScriptResult); + infoUpload(this, androidId, currentScriptResult); + } } } catch (Exception e) { LogFileUtil.logAndWrite(Log.ERROR, "MainActivity", "changeDeviceInfo erro", e); @@ -295,7 +290,7 @@ public class MainActivity extends AppCompatActivity { }); } - public static final LinkedBlockingQueue scriptResultQueue = new LinkedBlockingQueue<>(); + public static final LinkedBlockingQueue scriptResultQueue = new LinkedBlockingQueue<>(1); private volatile boolean isRunning = true; // 主线程运行状态 public static final Object taskLock = new Object(); // 任务逻辑锁 @@ -306,28 +301,32 @@ public class MainActivity extends AppCompatActivity { // ChangeDeviceInfoUtil.changeDeviceInfo(getPackageName(), this); /// / LogFileUtil.logAndWrite(Log.INFO, "MainActivity", "executeSingleLogic: Running AutoJs script",null); + /// + /// @return // AutoJsUtil.runAutojsScript(this); // } - private void startProxyVpn(Context context) { + private boolean startProxyVpn(Context context) { if (!isNetworkAvailable(context)) { Toast.makeText(context, "Network is not available", Toast.LENGTH_SHORT).show(); LogFileUtil.logAndWrite(Log.ERROR, "MainActivity", "startProxyVpn: Network is not available.", null); - return; + return false; } if (!(context instanceof Activity)) { Toast.makeText(context, "Context must be an Activity", Toast.LENGTH_SHORT).show(); LogFileUtil.logAndWrite(Log.ERROR, "MainActivity", "startProxyVpn: Context is not an Activity.", null); - return; + return false; } try { ClashUtil.startProxy(context); // 在主线程中调用 ClashUtil.switchProxyGroup("GLOBAL", "us", "http://127.0.0.1:6170"); + return ClashUtil.checkCountryIsUS(); } catch (Exception e) { LogFileUtil.logAndWrite(Log.ERROR, "MainActivity", "startProxyVpn: Failed to start VPN", e); Toast.makeText(context, "Failed to start VPN: " + (e.getMessage() != null ? e.getMessage() : "Unknown error"), Toast.LENGTH_SHORT).show(); } + return false; } @Override diff --git a/app/src/main/java/com/example/studyapp/proxy/ClashUtil.java b/app/src/main/java/com/example/studyapp/proxy/ClashUtil.java index 4123d11..1bdbba6 100644 --- a/app/src/main/java/com/example/studyapp/proxy/ClashUtil.java +++ b/app/src/main/java/com/example/studyapp/proxy/ClashUtil.java @@ -17,6 +17,7 @@ import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; +import okhttp3.ResponseBody; import org.json.JSONException; import org.json.JSONObject; @@ -116,26 +117,69 @@ public class ClashUtil { .put(requestBody) .build(); - client.newCall(request).enqueue(new Callback() { - @Override - public void onFailure(Call call, IOException e) { - LogFileUtil.logAndWrite(Log.ERROR, "ClashUtil", "switchProxyGroup: Failed to switch proxy", e); - System.out.println("Failed to switch proxy: " + e.getMessage()); + try { + Response response = client.newCall(request).execute(); + + if (response.isSuccessful() && response.body() != null) { + LogFileUtil.logAndWrite(Log.INFO, "ClashUtil", "switchProxyGroup: Switch proxy response", null); + } else { + LogFileUtil.logAndWrite(Log.ERROR, "ClashUtil", "switchProxyGroup: Response is not successful or body is null", null); } - @Override - public void onResponse(Call call, Response response) throws IOException { - try { - if (response.body() != null) { - LogFileUtil.logAndWrite(Log.INFO, "ClashUtil", "switchProxyGroup: Switch proxy response", null); - } else { - LogFileUtil.logAndWrite(Log.ERROR, "ClashUtil", "switchProxyGroup: Response body is null", null); - } - } finally { - response.close(); - } + response.close(); + } catch (IOException e) { + LogFileUtil.logAndWrite(Log.ERROR, "ClashUtil", "switchProxyGroup: Failed to switch proxy", e); + System.out.println("Failed to switch proxy: " + e.getMessage()); + } + } + + public static boolean checkCountryIsUS() { + Request request = new Request.Builder() + .url("http://ipinfo.io/json") + .build(); + OkHttpClient client = new OkHttpClient(); + try (Response response = client.newCall(request).execute()) { // Synchronous call + if (!response.isSuccessful()) { + // Server returned an error + Log.e("ClashUtil", "OkHttp request unsuccessful: " + response.code()); + // Consider how to handle this error synchronously. + // Maybe throw an exception or return a specific error indicator. + return false; // Or throw new IOException("Request failed with code " + response.code()); } - }); + + try (ResponseBody responseBody = response.body()) { + if (responseBody == null) { + Log.e("ClashUtil", "Response body is null"); + return false; // Or throw new IOException("Response body is null"); + } + + String jsonData = responseBody.string(); + JSONObject jsonObject = new JSONObject(jsonData); + String country = jsonObject.optString("country"); + boolean isUS = "US".equalsIgnoreCase(country); + + if (isUS) { + Log.i("ClashUtil", "Country is US. Full data: " + jsonData); + } else { + Log.i("ClashUtil", "Country is NOT US. It is: " + (country.isEmpty() ? "未知" : country) + ". Full data: " + jsonData); + } + return isUS; + + } catch (JSONException e) { + Log.e("ClashUtil", "JSON parsing error: ", e); + // Consider re-throwing or returning an error indicator + return false; + } catch (IOException e) { + Log.e("ClashUtil", "IOException reading response body: ", e); + // Consider re-throwing or returning an error indicator + return false; + } + } catch (IOException e) { + // Network request failed + Log.e("ClashUtil", "OkHttp request failed: ", e); + // Consider re-throwing or returning an error indicator + return false; + } } }