feat(MyTermuxActivity): 添加桌面快捷方式及指纹验证功能

- 列表项长按菜单新增"创建桌面快捷方式"
- 支持 ShortcutManager(API 26+) 和 INSTALL_SHORTCUT 广播两种方式
- TermuxCommandExecutor 所有命令执行前增加指纹验证
- 自定义AlertDialog显示命令信息(名称蓝色粗体),通过后启动BiometricPrompt
- 列表项名称蓝色粗体显示
- 新增 EXTRA_SESSION_ACTION 确保每次创建新终端会话
- MyTermuxActivity 添加 shortcut 意图处理(onCreate/onNewIntent)
This commit is contained in:
2026-06-02 19:32:01 +08:00
parent ac8b789bcb
commit 756cf88b55
6 changed files with 300 additions and 20 deletions

View File

@@ -103,6 +103,9 @@ dependencies {
implementation 'com.termux:terminal-emulator:0.118.0' implementation 'com.termux:terminal-emulator:0.118.0'
implementation 'com.termux:terminal-view:0.118.0' implementation 'com.termux:terminal-view:0.118.0'
implementation 'com.termux:termux-shared:0.118.0' implementation 'com.termux:termux-shared:0.118.0'
// Biometric (指纹识别)
implementation 'androidx.biometric:biometric:1.1.0'
// WinBoLL库 nexus.winboll.cc 地址 // WinBoLL库 nexus.winboll.cc 地址
//api 'cc.winboll.studio:libappbase:15.20.22' //api 'cc.winboll.studio:libappbase:15.20.22'

View File

@@ -11,6 +11,9 @@
<!-- 发送持久广播 --> <!-- 发送持久广播 -->
<uses-permission android:name="android.permission.BROADCAST_STICKY"/> <uses-permission android:name="android.permission.BROADCAST_STICKY"/>
<!-- 创建桌面快捷方式Android 8.0 以下兼容) -->
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/>
<!-- 对正在运行的应用重新排序 --> <!-- 对正在运行的应用重新排序 -->
<uses-permission android:name="android.permission.REORDER_TASKS"/> <uses-permission android:name="android.permission.REORDER_TASKS"/>
@@ -332,7 +335,18 @@
<activity android:name="cc.winboll.studio.winboll.termux.MyTermuxActivity" <activity android:name="cc.winboll.studio.winboll.termux.MyTermuxActivity"
android:label="@string/my_termux_activity" android:label="@string/my_termux_activity"
android:exported="true"/> android:exported="true"
android:launchMode="singleTask">
<intent-filter>
<action android:name="cc.winboll.studio.winboll.action.EXECUTE_TERMUX_BUTTON"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
</application> </application>

View File

@@ -2,7 +2,17 @@ package cc.winboll.studio.winboll.termux;
import android.app.AlertDialog; import android.app.AlertDialog;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ShortcutManager;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Icon;
import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.AdapterView; import android.widget.AdapterView;
@@ -25,6 +35,9 @@ import java.util.ArrayList;
public class MyTermuxActivity extends AppCompatActivity { public class MyTermuxActivity extends AppCompatActivity {
public static final String TAG = "MyTermuxActivity"; public static final String TAG = "MyTermuxActivity";
public static final String EXTRA_BUTTON_NAME = "extra_button_name";
public static final String ACTION_EXECUTE_SHORTCUT =
"cc.winboll.studio.winboll.action.EXECUTE_TERMUX_BUTTON";
private Toolbar mToolbar; private Toolbar mToolbar;
private ListView mListView; private ListView mListView;
@@ -41,6 +54,41 @@ public class MyTermuxActivity extends AppCompatActivity {
initListView(); initListView();
initAddButton(); initAddButton();
refreshList(); refreshList();
handleShortcutIntent();
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
handleShortcutIntent();
}
private void handleShortcutIntent() {
Intent intent = getIntent();
if (intent != null && ACTION_EXECUTE_SHORTCUT.equals(intent.getAction())) {
String buttonName = intent.getStringExtra(EXTRA_BUTTON_NAME);
if (buttonName != null && buttonName.length() > 0) {
TermuxButtonModel model = findButtonByName(buttonName);
if (model != null) {
TermuxCommandExecutor.openTermuxBash(this,
model.getButtonName(), model.getExeCommand(),
model.getWorkDir(), true);
} else {
Toast.makeText(this, R.string.toast_shortcut_not_found,
Toast.LENGTH_SHORT).show();
}
}
}
}
private TermuxButtonModel findButtonByName(String name) {
for (int i = 0; i < mButtonList.size(); i++) {
if (name.equals(mButtonList.get(i).getButtonName())) {
return mButtonList.get(i);
}
}
return null;
} }
private void initToolbar() { private void initToolbar() {
@@ -68,7 +116,8 @@ public class MyTermuxActivity extends AppCompatActivity {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) { public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TermuxButtonModel model = mButtonList.get(position); TermuxButtonModel model = mButtonList.get(position);
TermuxCommandExecutor.openTermuxBash(MyTermuxActivity.this, TermuxCommandExecutor.openTermuxBash(MyTermuxActivity.this,
model.getExeCommand(), model.getWorkDir()); model.getButtonName(), model.getExeCommand(),
model.getWorkDir(), true);
} }
}); });
@@ -102,10 +151,11 @@ public class MyTermuxActivity extends AppCompatActivity {
private void showContextMenu(final int position) { private void showContextMenu(final int position) {
final TermuxButtonModel model = mButtonList.get(position); final TermuxButtonModel model = mButtonList.get(position);
String[] items = new String[]{ final String[] items = new String[]{
getString(R.string.menu_execute), getString(R.string.menu_execute),
getString(R.string.menu_edit), getString(R.string.menu_edit),
getString(R.string.menu_delete), getString(R.string.menu_delete),
getString(R.string.menu_create_shortcut),
getString(R.string.menu_cancel) getString(R.string.menu_cancel)
}; };
new AlertDialog.Builder(this) new AlertDialog.Builder(this)
@@ -115,17 +165,70 @@ public class MyTermuxActivity extends AppCompatActivity {
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
if (which == 0) { if (which == 0) {
TermuxCommandExecutor.openTermuxBash(MyTermuxActivity.this, TermuxCommandExecutor.openTermuxBash(MyTermuxActivity.this,
model.getExeCommand(), model.getWorkDir()); model.getButtonName(), model.getExeCommand(),
model.getWorkDir(), true);
} else if (which == 1) { } else if (which == 1) {
showButtonDialog(position, model); showButtonDialog(position, model);
} else if (which == 2) { } else if (which == 2) {
showDeleteConfirmDialog(position); showDeleteConfirmDialog(position);
} else if (which == 3) {
createDesktopShortcut(model);
} }
} }
}) })
.show(); .show();
} }
private void createDesktopShortcut(TermuxButtonModel model) {
Intent shortcutIntent = new Intent(this, MyTermuxActivity.class);
shortcutIntent.setAction(ACTION_EXECUTE_SHORTCUT);
shortcutIntent.putExtra(EXTRA_BUTTON_NAME, model.getButtonName());
shortcutIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TOP);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
try {
ShortcutManager manager = getSystemService(ShortcutManager.class);
if (manager == null || !manager.isRequestPinShortcutSupported()) {
Toast.makeText(this, R.string.toast_shortcut_not_supported,
Toast.LENGTH_SHORT).show();
return;
}
String shortcutId = "termux_" + model.getButtonName();
android.content.pm.ShortcutInfo info =
new android.content.pm.ShortcutInfo.Builder(this, shortcutId)
.setShortLabel(model.getButtonName())
.setLongLabel(model.getButtonName())
.setIcon(Icon.createWithResource(this,
android.R.drawable.ic_menu_manage))
.setIntent(shortcutIntent)
.build();
manager.requestPinShortcut(info, null);
} catch (Exception e) {
LogUtils.e(TAG, "createDesktopShortcut error: " + e.getMessage());
Toast.makeText(this, R.string.toast_shortcut_failed,
Toast.LENGTH_SHORT).show();
}
} else {
try {
Intent installIntent =
new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
installIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
installIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME,
model.getButtonName());
installIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
Intent.ShortcutIconResource.fromContext(this,
android.R.drawable.ic_menu_manage));
installIntent.putExtra("duplicate", false);
sendBroadcast(installIntent);
} catch (Exception e) {
LogUtils.e(TAG, "createDesktopShortcut error: " + e.getMessage());
Toast.makeText(this, R.string.toast_shortcut_failed,
Toast.LENGTH_SHORT).show();
}
}
}
private void showDeleteConfirmDialog(final int position) { private void showDeleteConfirmDialog(final int position) {
new AlertDialog.Builder(this) new AlertDialog.Builder(this)
.setTitle(getString(R.string.dialog_delete_title)) .setTitle(getString(R.string.dialog_delete_title))
@@ -229,8 +332,15 @@ public class MyTermuxActivity extends AppCompatActivity {
} }
TermuxButtonModel model = mButtonList.get(position); TermuxButtonModel model = mButtonList.get(position);
tv.setText(model.getButtonName() + "\n" + model.getExeCommand()); String name = model.getButtonName();
tv.setTextColor(getResources().getColor(android.R.color.black)); String cmd = model.getExeCommand();
String fullText = name + "\n" + cmd;
SpannableString sp = new SpannableString(fullText);
sp.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
sp.setSpan(new ForegroundColorSpan(Color.BLUE), 0, name.length(),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
tv.setText(sp);
return tv; return tv;
} }
} }

View File

@@ -1,12 +1,27 @@
package cc.winboll.studio.winboll.termux; package cc.winboll.studio.winboll.termux;
import android.app.AlertDialog;
import android.content.Context; import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent; import android.content.Intent;
import android.content.pm.PackageManager; import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Build; import android.os.Build;
import cc.winboll.studio.libappbase.LogUtils; // 替换 Log 为 LogUtils与 Activity 一致) import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.widget.TextView;
import android.widget.Toast;
import androidx.biometric.BiometricPrompt;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
import cc.winboll.studio.libappbase.LogUtils;
import cc.winboll.studio.winboll.R;
import com.termux.shared.termux.TermuxConstants; import com.termux.shared.termux.TermuxConstants;
import com.termux.shared.shell.command.ExecutionCommand.Runner; import com.termux.shared.shell.command.ExecutionCommand.Runner;
import java.util.concurrent.Executor;
/** /**
* Termux 命令调用工具类(基于 RunCommandService 原型封装) * Termux 命令调用工具类(基于 RunCommandService 原型封装)
@@ -77,7 +92,12 @@ public class TermuxCommandExecutor {
LogUtils.d(TAG, "结果输出目录:" + resultDir); LogUtils.d(TAG, "结果输出目录:" + resultDir);
} }
// 7. 允许替换参数中的逗号替代字符 // 7. 强制创建新终端会话(而非复用已有会话),避免第二次点击直接弹出旧窗口
if (!isBackground) {
intent.putExtra("com.termux.RUN_COMMAND_SESSION_ACTION", 0);
}
// 8. 允许替换参数中的逗号替代字符
intent.putExtra(TermuxConstants.TERMUX_APP.RUN_COMMAND_SERVICE.EXTRA_REPLACE_COMMA_ALTERNATIVE_CHARS_IN_ARGUMENTS, true); intent.putExtra(TermuxConstants.TERMUX_APP.RUN_COMMAND_SERVICE.EXTRA_REPLACE_COMMA_ALTERNATIVE_CHARS_IN_ARGUMENTS, true);
// 8. 发送请求(区分 Android O 及以上的前台服务) // 8. 发送请求(区分 Android O 及以上的前台服务)
@@ -175,11 +195,23 @@ public class TermuxCommandExecutor {
return tip; return tip;
} }
public static boolean openTermuxBash(Context context, String command) { private static String pendingTargetCmd;
return openTermuxBash(context, command, "~"); private static String pendingDisplayCmd;
} private static String pendingDisplayName;
public static boolean openTermuxBash(Context context, String command, String workDir) { public static boolean openTermuxBash(Context context, String command) {
return openTermuxBash(context, null, command, "~", true);
}
public static boolean openTermuxBash(Context context, String command, String workDir) {
return openTermuxBash(context, null, command, workDir, true);
}
public static boolean openTermuxBash(Context context, String command, String workDir, boolean keepAlive) {
return openTermuxBash(context, null, command, workDir, keepAlive);
}
public static boolean openTermuxBash(Context context, String displayName, String command, String workDir, boolean keepAlive) {
LogUtils.d(TAG, "openTermuxBash() 按钮点击执行Gradle命令实时输出"); LogUtils.d(TAG, "openTermuxBash() 按钮点击执行Gradle命令实时输出");
// 1. 校验Termux是否安装 // 1. 校验Termux是否安装
@@ -189,10 +221,10 @@ public class TermuxCommandExecutor {
} }
// 2. 定义核心路径确保路径与Termux中一致 // 2. 定义核心路径确保路径与Termux中一致
String projectPath = TERMUX_HOME_PATH; String projectPath = TERMUX_HOME_PATH;
if (workDir.startsWith("~") || workDir.startsWith(".")) { if (workDir.startsWith("~") || workDir.startsWith(".")) {
projectPath = TERMUX_HOME_PATH + "/" + workDir.substring(1); projectPath = TERMUX_HOME_PATH + "/" + workDir.substring(1);
} }
// 3. 构造命令核心用stdbuf禁用缓冲实现实时输出 // 3. 构造命令核心用stdbuf禁用缓冲实现实时输出
String targetCmd = ""; String targetCmd = "";
@@ -206,12 +238,117 @@ public class TermuxCommandExecutor {
// 确保"cd ~/Sources\npwd"这类输入能分段执行 // 确保"cd ~/Sources\npwd"这类输入能分段执行
String execCommand = command.replace("\\n", "; "); String execCommand = command.replace("\\n", "; ");
// 步骤5执行设定的命令直接由外层bash解释避免stdbuf对shell内置命令无效 // 步骤5执行设定的命令直接由外层bash解释避免stdbuf对shell内置命令无效
// 步骤6命令执行完后用stdbuf启动交互式bash保持终端可见 targetCmd += execCommand;
targetCmd += execCommand + "; stdbuf -o0 -e0 -i0 bash"; // 步骤6需要保持终端可见时追加交互式bash
if (keepAlive) {
targetCmd += "; stdbuf -o0 -e0 -i0 bash";
}
// 步骤7指纹验证后执行命令
if (context instanceof FragmentActivity) {
pendingTargetCmd = targetCmd;
pendingDisplayCmd = execCommand;
pendingDisplayName = displayName;
showFingerprintAndExecute((FragmentActivity) context);
return true;
} else {
return TermuxCommandExecutor.executeTerminalCommand(context, targetCmd);
}
}
// 4. 执行命令终端会话模式唤起Termux窗口 private static void showFingerprintAndExecute(final FragmentActivity activity) {
return TermuxCommandExecutor.executeTerminalCommand(context, targetCmd); String displayName = pendingDisplayName != null
? pendingDisplayName : "";
final StringBuilder sb = new StringBuilder();
if (pendingDisplayCmd != null) {
sb.append(pendingDisplayCmd);
}
final String cmdText = sb.toString();
SpannableString message = new SpannableString(
activity.getString(R.string.biometric_description,
displayName, cmdText));
int nameIdx = message.toString().indexOf(displayName);
if (nameIdx >= 0 && displayName.length() > 0) {
message.setSpan(new StyleSpan(Typeface.BOLD), nameIdx,
nameIdx + displayName.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
message.setSpan(new ForegroundColorSpan(Color.BLUE), nameIdx,
nameIdx + displayName.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
final AlertDialog dialog = new AlertDialog.Builder(activity)
.setTitle(R.string.biometric_title)
.setMessage(message)
.setPositiveButton(R.string.biometric_start,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
startBiometricAuth(activity);
}
})
.setNegativeButton(R.string.dialog_cancel,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
clearPending();
}
})
.setCancelable(false)
.show();
TextView tv = (TextView) dialog.findViewById(android.R.id.message);
if (tv != null) {
tv.setText(message);
}
}
private static void startBiometricAuth(final FragmentActivity activity) {
Executor executor = ContextCompat.getMainExecutor(activity);
final BiometricPrompt biometricPrompt = new BiometricPrompt(activity,
executor, new BiometricPrompt.AuthenticationCallback() {
@Override
public void onAuthenticationSucceeded(
BiometricPrompt.AuthenticationResult result) {
super.onAuthenticationSucceeded(result);
executePendingCommand(activity);
}
@Override
public void onAuthenticationError(int errorCode,
CharSequence errString) {
super.onAuthenticationError(errorCode, errString);
clearPending();
Toast.makeText(activity, R.string.toast_auth_failed,
Toast.LENGTH_SHORT).show();
}
@Override
public void onAuthenticationFailed() {
super.onAuthenticationFailed();
}
});
BiometricPrompt.PromptInfo promptInfo =
new BiometricPrompt.PromptInfo.Builder()
.setTitle(activity.getString(R.string.biometric_title))
.setNegativeButtonText(activity.getString(R.string.dialog_cancel))
.setConfirmationRequired(false)
.build();
biometricPrompt.authenticate(promptInfo);
}
private static void executePendingCommand(Context context) {
if (pendingTargetCmd != null) {
String cmd = pendingTargetCmd;
clearPending();
executeTerminalCommand(context, cmd);
}
}
private static void clearPending() {
pendingTargetCmd = null;
pendingDisplayCmd = null;
} }
} }

View File

@@ -1,3 +1,11 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<resources> <resources>
<string name="menu_create_shortcut">创建桌面快捷方式</string>
<string name="toast_shortcut_not_supported">系统不支持创建桌面快捷方式</string>
<string name="toast_shortcut_failed">创建桌面快捷方式失败</string>
<string name="toast_shortcut_not_found">未找到对应的按钮请先打开MyTermuxActivity</string>
<string name="toast_auth_failed">指纹验证失败</string>
<string name="biometric_title">指纹验证</string>
<string name="biometric_description">名称:%1$s\n命令%2$s</string>
<string name="biometric_start">开始指纹验证</string>
</resources> </resources>

View File

@@ -17,6 +17,7 @@
<string name="menu_execute">执行</string> <string name="menu_execute">执行</string>
<string name="menu_edit">编辑</string> <string name="menu_edit">编辑</string>
<string name="menu_delete">删除</string> <string name="menu_delete">删除</string>
<string name="menu_create_shortcut">创建桌面快捷方式</string>
<string name="menu_cancel">取消</string> <string name="menu_cancel">取消</string>
<string name="dialog_delete_title">确认删除</string> <string name="dialog_delete_title">确认删除</string>
<string name="dialog_delete_message">确定要删除</string> <string name="dialog_delete_message">确定要删除</string>
@@ -30,4 +31,11 @@
<string name="hint_work_dir">工作目录(默认 ~</string> <string name="hint_work_dir">工作目录(默认 ~</string>
<string name="toast_deleted">已删除</string> <string name="toast_deleted">已删除</string>
<string name="toast_fields_required">按钮名称和执行命令不能为空</string> <string name="toast_fields_required">按钮名称和执行命令不能为空</string>
<string name="toast_shortcut_not_supported">系统不支持创建桌面快捷方式</string>
<string name="toast_shortcut_failed">创建桌面快捷方式失败</string>
<string name="toast_shortcut_not_found">未找到对应的按钮请先打开MyTermuxActivity</string>
<string name="toast_auth_failed">指纹验证失败</string>
<string name="biometric_title">指纹验证</string>
<string name="biometric_description">名称:%1$s\n命令%2$s</string>
<string name="biometric_start">开始指纹验证</string>
</resources> </resources>