feat(app): 优化应用初始化和权限请求逻辑

- 重构了 MainActivity 中的 onCreate 方法,优化了应用初始化流程
- 添加了请求存储权限的独立方法 requestStoragePermission
- 实现了只在工作不存在时调度周期性工作的逻辑 schedulePeriodicWorkIfNotExists
- 优化了按钮点击事件的处理,提高了代码可读性和健壮性
- 新增了部署配置文件 deployment.xml,用于腾讯云服务器配置
This commit is contained in:
yjj38 2025-07-10 17:13:42 +08:00
parent 9acc35fa7b
commit d7774c2ac6
3 changed files with 106 additions and 65 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" remoteFilesAllowedToDisappearOnAutoupload="false">
<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"> <project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" /> <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="21" project-jdk-type="JavaSDK"> <component name="ProjectRootManager" version="2" languageLevel="JDK_21" default="true" project-jdk-name="21" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/build/classes" /> <output url="file://$PROJECT_DIR$/build/classes" />
</component> </component>

View File

@ -25,6 +25,7 @@ import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat; import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AppCompatActivity;
import androidx.work.ExistingPeriodicWorkPolicy;
import androidx.work.PeriodicWorkRequest; import androidx.work.PeriodicWorkRequest;
import androidx.work.WorkManager; import androidx.work.WorkManager;
@ -38,6 +39,7 @@ import com.example.retention.proxy.ClashUtil;
import com.example.retention.service.MyAccessibilityService; import com.example.retention.service.MyAccessibilityService;
import com.example.retention.task.TaskUtil; import com.example.retention.task.TaskUtil;
import com.example.retention.utils.LogFileUtil; import com.example.retention.utils.LogFileUtil;
import com.example.retention.utils.ShellUtils;
import com.example.retention.worker.CheckAccessibilityWorker; import com.example.retention.worker.CheckAccessibilityWorker;
import com.example.retention.worker.LoadDeviceWorker; import com.example.retention.worker.LoadDeviceWorker;
@ -92,87 +94,108 @@ public class MainActivity extends AppCompatActivity {
@Override @Override
protected void onCreate(@Nullable Bundle savedInstanceState) { protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
LogFileUtil.initialize(this); LogFileUtil.initialize(this);
setContentView(R.layout.activity_main); setContentView(R.layout.activity_main);
logInfo("onCreate: Initializing application"); logInfo("onCreate: Initializing application");
initializeExecutorService(); initializeExecutorService();
System.setProperty("java.library.path", getApplicationInfo().nativeLibraryDir); System.setProperty("java.library.path", getApplicationInfo().nativeLibraryDir);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) { != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions( requestStoragePermission();
this, }
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, } else {
REQUEST_CODE_STORAGE_PERMISSION if (!Environment.isExternalStorageManager()) {
); Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
intent.setData(Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, ALLOW_ALL_FILES_ACCESS_PERMISSION_CODE);
}
} }
} else {
if (!Environment.isExternalStorageManager()) { if (!isNetworkAvailable(this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION); showToast("网络不可用");
intent.setData(Uri.parse("package:" + getPackageName())); logError("Network not available, closing app.");
startActivityForResult(intent, ALLOW_ALL_FILES_ACCESS_PERMISSION_CODE); finish();
return;
} }
}
if (!isNetworkAvailable(this)) { logInfo("onCreate: Setting up work manager");
showToast("网络不可用"); schedulePeriodicWorkIfNotExists();
logError("Network not available, closing app.");
finish();
return;
}
logInfo("onCreate: Setting up work manager"); logInfo("onCreate: Setting up UI components");
PeriodicWorkRequest workRequest = new PeriodicWorkRequest.Builder(CheckAccessibilityWorker.class, 15, TimeUnit.MINUTES)
.build();
WorkManager.getInstance(this).enqueue(workRequest);
logInfo("onCreate: Setting up UI components"); setupButton(R.id.run_script_button, v -> {
try {
setupButton(R.id.run_script_button, v -> AutoJsUtil.runAutojsScript(this)); AutoJsUtil.runAutojsScript(this);
setupButton(R.id.connectVpnButton, v -> startProxyVpn(this)); } catch (Exception e) {
setupButton(R.id.disconnectVpnButton, v -> ClashUtil.stopProxy(this)); LogFileUtil.logAndWrite(Log.ERROR, "MainActivity", "runAutojsScript: " + e.getMessage(), e);
setupButton(R.id.switchVpnButton, v -> ClashUtil.switchProxyGroup("GLOBAL", "us", "http://127.0.0.1:6170")); showToast("执行脚本失败");
}
armClient = new ArmCloudApiClient();
setupButton(R.id.modifyDeviceInfoButton, v -> ChangeDeviceInfoUtil.changeDeviceInfo(getPackageName(), this, armClient));
setupButton(R.id.resetDeviceInfoButton, v -> ChangeDeviceInfoUtil.resetChangedDeviceInfo(getPackageName(), this));
Button executeButton = findViewById(R.id.execute_button);
Button stopExecuteButton = findViewById(R.id.stop_execute_button);
if (executeButton != null) {
executeButton.setOnClickListener(v -> {
executeButton.setEnabled(false);
startLoadWork();
}); });
} setupButton(R.id.connectVpnButton, v -> startProxyVpn(this));
setupButton(R.id.disconnectVpnButton, v -> ClashUtil.stopProxy(this));
setupButton(R.id.switchVpnButton, v -> ClashUtil.switchProxyGroup("GLOBAL", "us", "http://127.0.0.1:6170"));
if (stopExecuteButton != null) { armClient = new ArmCloudApiClient();
stopExecuteButton.setOnClickListener(v -> {
WorkManager.getInstance(this).cancelAllWorkByTag(WORK_TAG); String currentPackage = getPackageName();
executeButton.setEnabled(true); ShellUtils.execRootCmdAndGetResult("pm grant " + currentPackage + " android.permission.INTERACT_ACROSS_USERS");
ShellUtils.execRootCmdAndGetResult("pm grant " + currentPackage + " android.permission.WRITE_SECURE_SETTINGS");
setupButton(R.id.modifyDeviceInfoButton, v -> ChangeDeviceInfoUtil.changeDeviceInfo(currentPackage, this, armClient));
setupButton(R.id.resetDeviceInfoButton, v -> ChangeDeviceInfoUtil.resetChangedDeviceInfo(currentPackage, this));
setupButton(R.id.execute_button, v -> {
((Button) v).setEnabled(false);
startLoadWork();
}); });
} else {
showToast("Stop button not found"); setupButton(R.id.stop_execute_button, v -> {
} WorkManager.getInstance(this).cancelAllWorkByTag(WORK_TAG);
Button executeButton = findViewById(R.id.execute_button);
if (executeButton != null) {
executeButton.setEnabled(true);
}
});
}
private void requestStoragePermission() {
ActivityCompat.requestPermissions(
this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_CODE_STORAGE_PERMISSION
);
}
private void schedulePeriodicWorkIfNotExists() {
WorkManager.getInstance(this).getWorkInfosForUniqueWorkLiveData("CheckAccessibilityWorker")
.observe(this, workInfos -> {
if (workInfos == null || workInfos.isEmpty()) {
PeriodicWorkRequest workRequest = new PeriodicWorkRequest.Builder(CheckAccessibilityWorker.class, 15, TimeUnit.MINUTES)
.addTag("CheckAccessibilityWorker")
.build();
WorkManager.getInstance(this).enqueueUniquePeriodicWork(
"CheckAccessibilityWorker",
ExistingPeriodicWorkPolicy.REPLACE,
workRequest
);
}
});
} }
private void setupButton(int resId, View.OnClickListener listener) { private void setupButton(int resId, View.OnClickListener listener) {
Button button = findViewById(resId); Button button = findViewById(resId);
if (button != null) { if (button != null) {
button.setOnClickListener(listener); button.setOnClickListener(listener);
} else { } else {
String msg = getResources().getResourceEntryName(resId) + " not found"; logInfo("Button not found: " + resId);
logWarn(msg); }
showToast(msg);
}
} }
private static String WORK_TAG = "LOAD_WORK"; private static String WORK_TAG = "LOAD_WORK";