refactor(studyapp): 重构代码并添加注释

-为 MainActivity 和 StartJobService 中的关键方法添加了详细注释
- 删除了 MainActivity 中未使用的旧代码
- 新增 deployment.xml 和修改 misc.xml 以配置项目设置- 优化了 StartJobService 的执行逻辑,增加了错误处理和任务状态管理
This commit is contained in:
yjj38 2025-07-12 15:37:28 +08:00
parent 451d1ab3b5
commit 714b43f608
4 changed files with 67 additions and 100 deletions

14
.idea/deployment.xml Normal file
View File

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="PublishConfigData">
<serverData>
<paths name="腾讯云">
<serverdata>
<mappings>
<mapping local="$PROJECT_DIR$" web="/" />
</mappings>
</serverdata>
</paths>
</serverData>
</component>
</project>

View File

@ -1,5 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="FrameworkDetectionExcludesConfiguration">
<file type="web" url="file://$PROJECT_DIR$" />
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_21" default="true" project-jdk-name="jbr-21" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/build/classes" />
</component>

View File

@ -210,6 +210,12 @@ public class MainActivity extends AppCompatActivity {
});
}
/**
* 这段代码的功能是
* 初始化执行按钮和停止执行按钮
* 为执行按钮设置点击事件点击后禁用按钮显示任务执行中提示并调用执行逻辑方法
* 调用 setupStopExecutionButton 方法配置停止按钮的行为
*/
private void setupExecutionButtons(String androidId, String taskId) {
Button executeButton = findViewById(R.id.execute_button);
Button stopExecuteButton = findViewById(R.id.stop_execute_button);
@ -221,7 +227,6 @@ public class MainActivity extends AppCompatActivity {
executeLogic(androidId, taskId);
});
}
setupStopExecutionButton(stopExecuteButton, executeButton);
}
@ -240,6 +245,12 @@ public class MainActivity extends AppCompatActivity {
}
}
/**
*记录Start execution日志
* 检查设备是否有网络连接若无则直接返回
* 注册脚本结果接收器
* 触发作业服务事件
*/
private void executeLogic(String androidId, String taskId) {
LogFileUtil.logAndWrite(Log.INFO, TAG, "Start execution", null);
@ -248,104 +259,9 @@ public class MainActivity extends AppCompatActivity {
}
AutoJsUtil.registerScriptResultReceiver(this);
StartJobService.Companion.onEvent(this);
// initializeExecutorService();
// executorService.submit(() -> processMainTask(androidId, taskId));
}
private void processMainTask(String androidId, String taskId) {
try {
ShellUtils.execRootCmdAndGetResult("pm grant com.example.studyapp android.permission.INTERACT_ACROSS_USERS");
ShellUtils.execRootCmdAndGetResult("pm grant com.example.studyapp android.permission.WRITE_SECURE_SETTINGS");
ShellUtils.execRootCmdAndGetResult("pm setenforce 0");
// initializeDeviceAndRunScript();
// processScriptResults(androidId, taskId);
} catch (Exception e) {
LogFileUtil.logAndWrite(Log.ERROR, TAG, "Unexpected task error", e);
}
}
// private void initializeDeviceAndRunScript() {
// ChangeDeviceInfoUtil.getAddDeviceInfo(currentCountry.toUpperCase(), DEVICE_TYPE,
// (bigoDevice, afDevice) -> {
// startProxyVpn(this);
// UpdateUtil.INSTANCE.changeDevice(getPackageName(), bigoDevice, afDevice, new ChangeCallBack() {
// @Override
// public void changeSuccess() {
// AutoJsUtil.runAutojsScript(MainActivity.this);
// }
//
// @Override
// public void changeFailed() {
// LogFileUtil.logAndWrite(Log.ERROR, TAG, "Change device failed", null);
// }
// });
//// ChangeDeviceInfoUtil.changeDeviceInfo(getPackageName(), this,
//// bigoDevice, afDevice);
//// AutoJsUtil.runAutojsScript(this);
// });
// AutoJsUtil.registerScriptResultReceiver(this);
// }
// private void processScriptResults(String androidId, String taskId) {
// while (isRunning) {
// try {
// String currentScriptResult = scriptResultQueue.take();
// if (!isRunning) {
// break;
// }
//
// processScriptResult(androidId, taskId, currentScriptResult);
// LogFileUtil.logAndWrite(Log.DEBUG, TAG, "Script result processed: " + currentScriptResult, null);
// } catch (InterruptedException e) {
// Thread.currentThread().interrupt();
// LogFileUtil.logAndWrite(Log.ERROR, TAG, "Thread interrupted while waiting", e);
// break;
// } catch (Exception e) {
// LogFileUtil.logAndWrite(Log.ERROR, TAG, "Error processing script result", e);
// }
// }
// }
//
// private void processScriptResult(String androidId, String taskId, String result) {
//
// ChangeDeviceInfoUtil.getAddDeviceInfo(currentCountry.toUpperCase(), DEVICE_TYPE,
// (bigoDevice, afDevice) -> {
// try {
// updateDeviceAndExecuteTask(androidId, taskId, result, bigoDevice, afDevice);
// } catch (Exception e) {
// LogFileUtil.logAndWrite(Log.ERROR, TAG, "Device info change error", e);
// }
// });
// }
//
//
// private void updateDeviceAndExecuteTask(String androidId, String taskId,
// String result, JSONObject bigoDevice, JSONObject afDevice) {
// startProxyVpn(this);
// UpdateUtil.INSTANCE.changeDevice(result, bigoDevice, afDevice,new ChangeCallBack() {
// @Override
// public void changeSuccess() {
// AutoJsUtil.runAutojsScript(MainActivity.this);
//
// TaskUtil.execSaveTask(MainActivity.this, androidId, taskId, result, IpUtil.fetchGeoInfo());
// try {
// infoUpload(MainActivity.this, androidId, result);
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
// @Override
// public void changeFailed() {
// LogFileUtil.logAndWrite(Log.ERROR, TAG, "Change device failed", null);
// }
// });
// }
public static final LinkedBlockingQueue<String> scriptResultQueue = new LinkedBlockingQueue<>(1);
private volatile boolean isRunning = true; // 主线程运行状态
public static final Object taskLock = new Object(); // 任务逻辑锁
@ -450,7 +366,6 @@ public class MainActivity extends AppCompatActivity {
if (executorService != null) {
executorService.shutdown();
}
isRunning = false;
synchronized (taskLock) {
taskLock.notifyAll();
}

View File

@ -9,6 +9,7 @@ import androidx.core.app.JobIntentService
import com.example.studyapp.autoJS.AutoJsUtil
import com.example.studyapp.device.ChangeDeviceInfoUtil
import com.example.studyapp.device.LoadDeviceCallback
import com.example.studyapp.job.ScriptJobService.Companion.onEvent
import com.example.studyapp.proxy.ClashUtil
import com.example.studyapp.update.ChangeCallBack
import com.example.studyapp.update.UpdateUtil.changeDevice
@ -16,6 +17,7 @@ import com.example.studyapp.utils.CountryCode
import com.example.studyapp.utils.IpUtil
import com.example.studyapp.utils.LogFileUtil
import com.example.studyapp.utils.ShellUtils
import com.example.studyapp.utils.ShellUtils.exec
import org.json.JSONObject
import java.util.Locale
@ -25,7 +27,26 @@ import java.util.Locale
interface JobCallback {
fun onJobFailed()
}
/**
* 这段代码定义了一个继承自 JobIntentService 的后台服务类 StartJobService整体功能如下
* 使用 onHandleWork 处理后台任务防止重复执行并在失败时延迟重启任务
* exec 方法中执行以下操作
* 通过 Root 命令授予应用特殊权限
* 获取并设置设备信息包括国家设备类型等
* 根据国家切换代理配置
* 获取 IP 地理信息和时区
* 修改设备信息若成功则运行 Auto.js 脚本若失败则回调失败方法
* 使用伴生对象管理任务状态与启动逻辑
*/
class StartJobService : JobIntentService() {
/**
* 重写 onHandleWork 方法处理后台任务
* 若任务已在运行则直接返回
* 设置任务状态为运行中
* 执行任务并在任务失败时通过主线程延迟 10 秒后重新触发事件
*/
override fun onHandleWork(intent: Intent) {
if (running) {
return
@ -42,6 +63,14 @@ class StartJobService : JobIntentService() {
)
}
/**
* 执行一系列 Root 命令以授予应用特定权限
* 调用 ChangeDeviceInfoUtil 获取并设置设备信息
* 根据国家代码切换代理配置
* 获取 IP 地理信息和时区
* 调用 changeDevice 修改设备信息成功后运行 Auto.js 脚本
* 如果失败回调 onJobFailed 并结束任务
*/
protected fun exec(callback: JobCallback) {
try {
ShellUtils.execRootCmdAndGetResult("pm grant com.example.studyapp android.permission.INTERACT_ACROSS_USERS")
@ -49,7 +78,7 @@ class StartJobService : JobIntentService() {
ShellUtils.execRootCmdAndGetResult("pm setenforce 0")
ChangeDeviceInfoUtil.getAddDeviceInfo(
CountryCode.currentCountry.uppercase(Locale.getDefault()), CountryCode.DEVICE_TYPE,
object :LoadDeviceCallback{
object : LoadDeviceCallback {
override fun onLoadDeviceInfo(
bigoDevice: JSONObject?,
afDevice: JSONObject?
@ -60,7 +89,7 @@ class StartJobService : JobIntentService() {
// ClashUtil.switchProxyGroup("PROXY", "my-socks5-proxy", "http://127.0.0.1:6170")
val geoInfo: String = IpUtil.fetchGeoInfo()
val timeZone: String = IpUtil.getTimeZone(geoInfo)
changeDevice(packageName, bigoDevice, afDevice,timeZone, object : ChangeCallBack {
changeDevice(packageName, bigoDevice, afDevice, timeZone, object : ChangeCallBack {
override fun changeSuccess() {
AutoJsUtil.runAutojsScript(applicationContext)
setRunning(false)
@ -90,6 +119,11 @@ class StartJobService : JobIntentService() {
}
}
/**
* 定义伴生对象包含日志标签任务 ID 和运行状态标志
* 提供 onEvent 方法用于启动后台任务
* 提供 setRunning 方法更新任务运行状态
*/
companion object {
private const val TAG = "StartJobService"
private const val jobId = 101
@ -110,4 +144,4 @@ class StartJobService : JobIntentService() {
running = runningV
}
}
}
}