refactor(proxy): 重构代理工具并添加地理位置检查功能

-重写 ClashUtil 类中的 switchProxyGroup 方法,使用同步调用替代异步回调
- 新增 checkCountryIsUS 方法,用于检查当前设备是否位于美国
- 修改 MainActivity 中的 startProxyVpn 方法,集成新的地理位置检查逻辑
-优化任务执行流程,确保仅在代理 VPN 启动成功且设备位于美国时执行后续操作
- 修复了一些潜在的资源泄露问题,提高了代码的健壮性
This commit is contained in:
yjj38 2025-07-03 14:12:02 +08:00
parent fec032e52b
commit 91a60683c5
3 changed files with 80 additions and 38 deletions

View File

@ -1,4 +1,3 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="ProjectRootManager" version="2" languageLevel="JDK_21" default="true" project-jdk-name="21" project-jdk-type="JavaSDK">

View File

@ -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<String> scriptResultQueue = new LinkedBlockingQueue<>();
public static final LinkedBlockingQueue<String> 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

View File

@ -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;
}
}
}