### Control Termux App with Broadcast Intents (Java) Source: https://context7.com/t-e-l/tel/llms.txt This Java code demonstrates sending various broadcast intents to control the Termux application. These intents allow for dynamic styling changes, storage symlink setup, application restarts, cache refreshing, status view updates, status line deletion, and showing the intro activity. Ensure the correct intent actions and extra data are used for each operation. ```java // Reload styling (fonts and colors) Intent reloadStyle = new Intent("com.termux.app.reload_style"); reloadStyle.putExtra("com.termux.app.reload_style", "styling"); context.sendBroadcast(reloadStyle); // Setup storage symlinks Intent storageIntent = new Intent("com.termux.app.reload_style"); storageIntent.putExtra("com.termux.app.reload_style", "storage"); context.sendBroadcast(storageIntent); // Restart application Intent restartIntent = new Intent("com.termux.app.restart"); context.sendBroadcast(restartIntent); // Refresh app list cache Intent cacheIntent = new Intent("com.termux.app.app_cache"); context.sendBroadcast(cacheIntent); // Update status view Intent statusIntent = new Intent("com.termux.app.status"); statusIntent.putExtra("text", "Status message"); statusIntent.putExtra("line", "0"); // Line number (0-indexed) context.sendBroadcast(statusIntent); // Delete status lines Intent deleteStatus = new Intent("com.termux.app.status"); deleteStatus.putExtra("delete", "true"); deleteStatus.putExtra("line", "2"); // Delete from line 2 onwards context.sendBroadcast(deleteStatus); // Show intro activity Intent introIntent = new Intent("com.termux.app.intro"); context.sendBroadcast(introIntent); ``` -------------------------------- ### Execute External Commands with RunCommandService (Java) Source: https://context7.com/t-e-l/tel/llms.txt Demonstrates how to execute commands in Termux from external applications using the RunCommandService. This requires the com.termux.permission.RUN_COMMAND permission and enabling allow-external-apps in termux.properties. It shows standard execution, path shortcut usage, and configuration. ```java // Execute command from external app with Java Intent intent = new Intent(); intent.setClassName("com.termux", "com.termux.app.RunCommandService"); intent.setAction("com.termux.RUN_COMMAND"); intent.putExtra("com.termux.RUN_COMMAND_PATH", "/data/data/com.termux/files/usr/bin/top"); intent.putExtra("com.termux.RUN_COMMAND_ARGUMENTS", new String[]{" -n", "5"}); intent.putExtra("com.termux.RUN_COMMAND_WORKDIR", "/data/data/com.termux/files/home"); intent.putExtra("com.termux.RUN_COMMAND_BACKGROUND", false); context.startService(intent); // Execute command using path shortcuts Intent shortcutIntent = new Intent(); shortcutIntent.setClassName("com.termux", "com.termux.app.RunCommandService"); shortcutIntent.setAction("com.termux.RUN_COMMAND"); shortcutIntent.putExtra("com.termux.RUN_COMMAND_PATH", "$PREFIX/bin/ls"); shortcutIntent.putExtra("com.termux.RUN_COMMAND_WORKDIR", "~/"); shortcutIntent.putExtra("com.termux.RUN_COMMAND_BACKGROUND", true); context.startService(shortcutIntent); // Enable external apps in termux.properties // File: /data/data/com.termux/files/home/.termux/termux.properties // Content: allow-external-apps=true // Execute via adb shell String command = "am startservice --user 0 -n com.termux/com.termux.app.RunCommandService " + "-a com.termux.RUN_COMMAND " + "--es com.termux.RUN_COMMAND_PATH '/data/data/com.termux/files/usr/bin/top' " + "--esa com.termux.RUN_COMMAND_ARGUMENTS '-n,5' " + "--es com.termux.RUN_COMMAND_WORKDIR '/data/data/com.termux/files/home' " + "--ez com.termux.RUN_COMMAND_BACKGROUND 'false'"; ``` -------------------------------- ### Manage Terminal Sessions with TerminalSession (Java) Source: https://context7.com/t-e-l/tel/llms.txt Provides a Java API for managing individual terminal sessions, coupling shell processes with terminal emulation. It handles I/O streams, UTF-8 encoding, and provides callbacks for session state changes like text updates, title changes, and session completion. Proper initialization and session management are crucial for correct operation. ```java // Create a terminal session String shellPath = "/data/data/com.termux/files/usr/bin/bash"; String cwd = "/data/data/com.termux/files/home"; String[] args = new String[]{" -bash"}; String[] env = BackgroundJob.buildEnvironment(false, cwd); SessionChangedCallback callback = new SessionChangedCallback() { @Override public void onTextChanged(TerminalSession session) { // Update terminal view when text changes } @Override public void onTitleChanged(TerminalSession session) { // Update session title in UI String title = session.getTitle(); } @Override public void onSessionFinished(TerminalSession session) { // Handle session exit int exitStatus = session.getExitStatus(); } @Override public void onClipboardText(TerminalSession session, String text) { // Handle OSC 52 clipboard operations } @Override public void onBell(TerminalSession session) { // Handle terminal bell } @Override public void onColorsChanged(TerminalSession session) { // Handle dynamic color changes } }; TerminalSession session = new TerminalSession(shellPath, cwd, args, env, callback); session.updateSize(80, 24); // Initialize with 80 columns, 24 rows // Write to terminal String command = "ls -la\n"; session.write(command.getBytes(StandardCharsets.UTF_8), 0, command.length()); // Write Unicode code point session.writeCodePoint(false, 0x1F4A9); // Write emoji // Check session state boolean running = session.isRunning(); int pid = session.getPid(); String currentDir = session.getCwd(); // Terminate session session.finishIfRunning(); ``` -------------------------------- ### Execute Background Job with Callback - Java Source: https://context7.com/t-e-l/tel/llms.txt Executes shell scripts or commands in the background, capturing stdout and stderr, and reporting exit codes. It supports result callbacks via PendingIntent, allowing asynchronous handling of job completion. The environment and process arguments are automatically set up for script execution. ```java // Execute background job with result callback Intent resultIntent = new Intent(context, MyResultReceiver.class); PendingIntent pendingIntent = PendingIntent.getBroadcast( context, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT); String cwd = "/data/data/com.termux/files/home"; String scriptPath = "/data/data/com.termux/files/home/my-script.sh"; String[] args = new String[]{"arg1", "arg2"}; BackgroundJob job = new BackgroundJob(cwd, scriptPath, args, termuxService, pendingIntent); // Result receiver to handle completion public class MyResultReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle result = intent.getBundleExtra("result"); String stdout = result.getString("stdout"); String stderr = result.getString("stderr"); int exitCode = result.getInt("exitCode"); Log.i("BackgroundJob", "Exit code: " + exitCode); Log.i("BackgroundJob", "Stdout: " + stdout); Log.i("BackgroundJob", "Stderr: " + stderr); } } // Build environment for script execution String[] environment = BackgroundJob.buildEnvironment(false, cwd); // Returns environment with: // - TERMUX_VERSION, TERM=xterm-256color, COLORTERM=truecolor // - HOME, PREFIX, PATH, PWD, TMPDIR // - Android system variables // Setup process arguments with shebang parsing String[] processArgs = BackgroundJob.setupProcessArgs(scriptPath, args); // Automatically handles: // - ELF binaries (executes directly) // - Scripts with #! shebang (uses specified interpreter) // - Scripts without shebang (uses $PREFIX/bin/sh) ``` -------------------------------- ### Terminal Emulator VT100/Xterm Core - Java Source: https://context7.com/t-e-l/tel/llms.txt Implements terminal emulation logic, handling ANSI escape sequences, cursor control, screen buffer management, and text rendering. It provides a complete VT100/xterm-compatible terminal emulator, allowing interaction with terminal programs. This includes features like mouse reporting and color scheme access. ```java // Terminal emulator is typically created by TerminalSession TerminalOutput output = new TerminalOutput() { @Override public void write(byte[] data, int offset, int count) { // Write to process } @Override public void titleChanged(String oldTitle, String newTitle) { // Handle title change } @Override public void clipboardText(String text) { // Handle clipboard operations } @Override public void onBell() { // Handle bell } @Override public void onColorsChanged() { // Handle color changes } }; TerminalEmulator emulator = new TerminalEmulator(output, 80, 24, 2000); // Append data from process to emulator byte[] data = "Hello, terminal!\n".getBytes(StandardCharsets.UTF_8); emulator.append(data, data.length); // Resize terminal emulator.resize(100, 30); // Reset terminal state emulator.reset(); // Get terminal title String title = emulator.getTitle(); // Access terminal screen buffer TerminalBuffer screen = emulator.getScreen(); String transcript = screen.getTranscriptTextWithFullLinesJoined(); // Mouse reporting (for terminal programs that support it) emulator.sendMouseEvent(TerminalEmulator.MOUSE_LEFT_BUTTON, 10, 5, false); // Get color scheme TerminalColors colors = emulator.mColors; int backgroundColor = colors.mCurrentColors[TextStyle.COLOR_INDEX_BACKGROUND]; int foregroundColor = colors.mCurrentColors[TextStyle.COLOR_INDEX_FOREGROUND]; ``` -------------------------------- ### Launching and Managing Terminal Sessions with TermuxActivity Source: https://context7.com/t-e-l/tel/llms.txt This snippet demonstrates how to launch the TermuxActivity, create new terminal sessions (including failsafe mode), switch between existing sessions, and trigger style reloads via intents. It interacts with the main terminal interface. ```java Intent intent = new Intent(context, TermuxActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); // Create a failsafe session via intent Intent failsafeIntent = new Intent(context, TermuxActivity.class); failsafeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); failsafeIntent.putExtra(TermuxActivity.TERMUX_FAILSAFE_SESSION_ACTION, true); context.startActivity(failsafeIntent); // Switch between sessions programmatically TerminalSession currentSession = termuxActivity.getCurrentTermSession(); termuxActivity.switchToSession(true); // forward = true to go to next session // Add a new named session termuxActivity.addNewSession(false, "MySession"); // Handle font and color customization // Place font.ttf in /data/data/com.termux/files/home/.termux/font.ttf // Place colors.properties in /data/data/com.termux/files/home/.termux/colors.properties // Trigger reload via broadcast Intent reloadIntent = new Intent("com.termux.app.reload_style"); reloadIntent.putExtra("com.termux.app.reload_style", "styling"); context.sendBroadcast(reloadIntent); ``` -------------------------------- ### Managing Terminal Sessions with TermuxService Source: https://context7.com/t-e-l/tel/llms.txt This Java code illustrates how to bind to the TermuxService, create new terminal sessions with specified working directories, retrieve all active sessions, and remove finished sessions. It also shows how to control wake locks and stop all sessions via intents sent to the service. ```java // Bind to TermuxService Intent serviceIntent = new Intent(context, TermuxService.class); context.startService(serviceIntent); context.bindService(serviceIntent, serviceConnection, 0); // ServiceConnection implementation ServiceConnection serviceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { TermuxService termuxService = ((TermuxService.LocalBinder) service).service; // Create a new terminal session String workingDir = "/data/data/com.termux/files/home"; TerminalSession session = termuxService.createTermSession( null, // executablePath - null uses default shell null, // arguments workingDir, false // failSafe mode ); // Get all active sessions List sessions = termuxService.getSessions(); // Remove a finished session int removedIndex = termuxService.removeTermSession(session); } @Override public void onServiceDisconnected(ComponentName name) { // Handle disconnection } }; // Control wake lock via intent Intent wakeLockIntent = new Intent(context, TermuxService.class); wakeLockIntent.setAction("com.termux.service_wake_lock"); context.startService(wakeLockIntent); // Stop all sessions and exit Intent stopIntent = new Intent(context, TermuxService.class); stopIntent.setAction("com.termux.service_stop"); context.startService(stopIntent); ``` -------------------------------- ### RunCommandService - External Command Execution API Source: https://context7.com/t-e-l/tel/llms.txt Allows third-party applications to execute commands in Termux. Requires the com.termux.permission.RUN_COMMAND permission and the allow-external-apps property to be enabled in termux.properties. ```APIDOC ## RunCommandService - External Command Execution API ### Description Allows third-party applications to execute commands in Termux. Requires the `com.termux.permission.RUN_COMMAND` permission and the `allow-external-apps` property to be enabled in `termux.properties`. ### Method `START_SERVICE` (via `Intent` or `am startservice`) ### Endpoint `com.termux/com.termux.app.RunCommandService` ### Parameters #### Intent Extras - **com.termux.RUN_COMMAND_PATH** (String) - Required - The absolute path to the executable command. - **com.termux.RUN_COMMAND_ARGUMENTS** (String[]) - Optional - An array of strings representing the arguments for the command. - **com.termux.RUN_COMMAND_WORKDIR** (String) - Optional - The working directory for the command. Can use shortcuts like `$PREFIX` and `~`. - **com.termux.RUN_COMMAND_BACKGROUND** (Boolean) - Optional - If `true`, the command runs in the background. Defaults to `false`. ### Request Example (Java Intent) ```java Intent intent = new Intent(); intent.setClassName("com.termux", "com.termux.app.RunCommandService"); intent.setAction("com.termux.RUN_COMMAND"); intent.putExtra("com.termux.RUN_COMMAND_PATH", "/data/data/com.termux/files/usr/bin/top"); intent.putExtra("com.termux.RUN_COMMAND_ARGUMENTS", new String[]{"-", "n", "5"}); intent.putExtra("com.termux.RUN_COMMAND_WORKDIR", "/data/data/com.termux/files/home"); intent.putExtra("com.termux.RUN_COMMAND_BACKGROUND", false); context.startService(intent); ``` ### Request Example (ADB Shell) ```bash am startservice --user 0 -n com.termux/com.termux.app.RunCommandService \ -a com.termux.RUN_COMMAND \ --es com.termux.RUN_COMMAND_PATH '/data/data/com.termux/files/usr/bin/top' \ --esa com.termux.RUN_COMMAND_ARGUMENTS '-n,5' \ --es com.termux.RUN_COMMAND_WORKDIR '/data/data/com.termux/files/home' \ --ez com.termux.RUN_COMMAND_BACKGROUND 'false' ``` ### Configuration To enable external app execution, ensure the following line is set to `true` in the file `/data/data/com.termux/files/home/.termux/termux.properties`: `allow-external-apps=true` ``` -------------------------------- ### Detect Termux Application Opening with Broadcast Receiver (Java) Source: https://context7.com/t-e-l/tel/llms.txt This Java code snippet shows how to register a BroadcastReceiver to detect when the Termux application is opened. It involves creating an IntentFilter for the 'com.termux.app.OPENED' action and registering the receiver with the provided context. The onReceive method will be invoked when the specified intent is broadcast. ```java // Detect when Termux is opened BroadcastReceiver termuxOpenedReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // Termux has been opened Log.i("Termux", "Application opened"); } }; IntentFilter filter = new IntentFilter("com.termux.app.OPENED"); context.registerReceiver(termuxOpenedReceiver, filter); ``` -------------------------------- ### TerminalSession - Process and Terminal Coupling Source: https://context7.com/t-e-l/tel/llms.txt Represents a single terminal session coupling a shell process with terminal emulation. Manages process I/O streams, handles UTF-8 encoding, and provides callbacks for terminal state changes. ```APIDOC ## TerminalSession - Process and Terminal Coupling ### Description Represents a single terminal session coupling a shell process with terminal emulation. Manages process I/O streams, handles UTF-8 encoding, and provides callbacks for terminal state changes. ### Method Constructor and instance methods. ### Endpoint N/A (This is a class within the Termux API library). ### Parameters #### Constructor Parameters - **shellPath** (String) - Required - The path to the shell executable (e.g., `/data/data/com.termux/files/usr/bin/bash`). - **cwd** (String) - Required - The current working directory for the session. - **args** (String[]) - Optional - Arguments to pass to the shell. - **env** (String[]) - Optional - Environment variables for the session. Can be built using `BackgroundJob.buildEnvironment()`. - **callback** (SessionChangedCallback) - Required - An interface to handle session state changes. #### Instance Methods - **updateSize(int columns, int rows)**: Updates the terminal dimensions. - **write(byte[] bytes, int offset, int length)**: Writes bytes to the terminal's input stream. - **writeCodePoint(boolean isCtrl, int codePoint)**: Writes a Unicode code point to the terminal. - **isRunning()**: Returns `true` if the session is currently running. - **getPid()**: Returns the process ID of the shell. - **getCwd()**: Returns the current working directory of the session. - **finishIfRunning()**: Terminates the session if it is running. ### Request Example (Java Code) ```java String shellPath = "/data/data/com.termux/files/usr/bin/bash"; String cwd = "/data/data/com.termux/files/home"; String[] args = new String[]{"-bash"}; String[] env = BackgroundJob.buildEnvironment(false, cwd); SessionChangedCallback callback = new SessionChangedCallback() { @Override public void onTextChanged(TerminalSession session) { // Update terminal view when text changes } @Override public void onTitleChanged(TerminalSession session) { // Update session title in UI String title = session.getTitle(); } @Override public void onSessionFinished(TerminalSession session) { // Handle session exit int exitStatus = session.getExitStatus(); } @Override public void onClipboardText(TerminalSession session, String text) { // Handle OSC 52 clipboard operations } @Override public void onBell(TerminalSession session) { // Handle terminal bell } @Override public void onColorsChanged(TerminalSession session) { // Handle dynamic color changes } }; TerminalSession session = new TerminalSession(shellPath, cwd, args, env, callback); session.updateSize(80, 24); // Initialize with 80 columns, 24 rows // Write to terminal String command = "ls -la\n"; session.write(command.getBytes(StandardCharsets.UTF_8), 0, command.length()); // Write Unicode code point session.writeCodePoint(false, 0x1F4A9); // Write emoji // Check session state boolean running = session.isRunning(); int pid = session.getPid(); String currentDir = session.getCwd(); // Terminate session session.finishIfRunning(); ``` ### Response N/A (This is a client-side API for managing sessions). ``` -------------------------------- ### Application Control Broadcasts Source: https://context7.com/t-e-l/tel/llms.txt This section describes various broadcast intents that can be sent to the Termux application to control its behavior and configuration dynamically. ```APIDOC ## Broadcast Receivers - Application Control The application responds to various broadcast intents for dynamic configuration and control without requiring activity restart. ### Action: `com.termux.app.reload_style` **Description**: Reloads styling (fonts and colors) or sets up storage symlinks. **Method**: `context.sendBroadcast(Intent)` **Parameters**: #### Extra Parameters - **`com.termux.app.reload_style`** (String) - Required - Value can be `"styling"` to reload styles or `"storage"` to setup storage symlinks. ### Action: `com.termux.app.restart` **Description**: Restarts the application. **Method**: `context.sendBroadcast(Intent)` ### Action: `com.termux.app.app_cache` **Description**: Refreshes the app list cache. **Method**: `context.sendBroadcast(Intent)` ### Action: `com.termux.app.status` **Description**: Updates or deletes status view lines. **Method**: `context.sendBroadcast(Intent)` **Parameters**: #### Extra Parameters - **`text`** (String) - Optional - The status message text. - **`line`** (String) - Optional - The 0-indexed line number for the status message. If `delete` is true, specifies the starting line to delete from. - **`delete`** (String) - Optional - Set to `"true"` to delete status lines. ### Action: `com.termux.app.intro` **Description**: Shows the intro activity. **Method**: `context.sendBroadcast(Intent)` ### Action: `com.termux.app.OPENED` **Description**: Broadcast receiver to detect when Termux is opened. **Method**: `context.registerReceiver(BroadcastReceiver, IntentFilter)` **Parameters**: #### Receiver - **`termuxOpenedReceiver`** (BroadcastReceiver) - The receiver to be called when the intent is sent. - **`onReceive(Context context, Intent intent)`**: Callback method for the receiver. #### Filter - **`"com.termux.app.OPENED"`** (String) - The intent action to filter for. ### Request Example (Reload Styling) ```java Intent reloadStyle = new Intent("com.termux.app.reload_style"); reloadStyle.putExtra("com.termux.app.reload_style", "styling"); context.sendBroadcast(reloadStyle); ``` ### Request Example (Update Status Line) ```java Intent statusIntent = new Intent("com.termux.app.status"); statusIntent.putExtra("text", "Status message"); statusIntent.putExtra("line", "0"); // Line number (0-indexed) context.sendBroadcast(statusIntent); ``` ### Request Example (Registering Receiver for App Opened) ```java BroadcastReceiver termuxOpenedReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // Termux has been opened Log.i("Termux", "Application opened"); } }; IntentFilter filter = new IntentFilter("com.termux.app.OPENED"); context.registerReceiver(termuxOpenedReceiver, filter); ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.