### Create Directory Example Source: https://github.com/jackpal/android-terminal-emulator/wiki/Frequently-Asked-Questions Illustrates the requirement for Photos/Media/Files write permission to create directories on external storage, such as '/sdcard/myNewDirectory'. ```bash mkdir /sdcard/myNewDirectory ``` -------------------------------- ### Implement TelnetSession and Usage Example Source: https://context7.com/jackpal/android-terminal-emulator/llms.txt Extends TermSession to handle Telnet protocol commands and provides a basic connection example using a Socket. ```java import jackpal.androidterm.emulatorview.TermSession; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; // TelnetSession extends TermSession to handle Telnet protocol public class TelnetSession extends TermSession { private static final int IAC = 255; // Telnet command prefix private static final int CMD_WILL = 251; // Option negotiation private static final int CMD_WONT = 252; private static final int CMD_DO = 253; private static final int CMD_DONT = 254; public TelnetSession(InputStream termIn, OutputStream termOut) { setTermIn(termIn); setTermOut(termOut); } // Override write() to handle CR -> CRLF conversion per Telnet spec @Override public void write(byte[] bytes, int offset, int count) { // Count CRs for buffer sizing int numCRs = 0; for (int i = offset; i < offset + count; ++i) { if (bytes[i] == '\r') numCRs++; } if (numCRs == 0) { super.write(bytes, offset, count); return; } // Convert CR to CRLF byte[] translated = new byte[count + numCRs]; int j = 0; for (int i = offset; i < offset + count; ++i) { if (bytes[i] == '\r') { translated[j++] = '\r'; translated[j++] = '\n'; } else { translated[j++] = bytes[i]; } } super.write(translated, 0, translated.length); } // Override processInput() to handle Telnet commands @Override protected void processInput(byte[] buffer, int offset, int count) { for (int i = offset; i < offset + count; i++) { int curByte = ((int) buffer[i]) & 0xff; if (curByte == IAC) { // Handle Telnet command sequence handleTelnetCommand(buffer, i, count - i); continue; } // Pass regular data to terminal emulator super.processInput(buffer, i, 1); } } private void handleTelnetCommand(byte[] buffer, int offset, int remaining) { // Implement Telnet protocol handling... } } // Usage: Connect to a Telnet server public class TelnetExample { public void connectToServer(String host, int port) throws Exception { Socket socket = new Socket(host, port); TelnetSession session = new TelnetSession( socket.getInputStream(), socket.getOutputStream() ); // Initialize with terminal size session.initializeEmulator(80, 24); // Attach to EmulatorView for display // emulatorView.attachSession(session); // Send commands session.write("help\r\n"); } } ``` -------------------------------- ### Run Ping Command Example Source: https://github.com/jackpal/android-terminal-emulator/wiki/Frequently-Asked-Questions Demonstrates the necessity of the Internet permission for network-related commands like 'ping'. Without this permission, such commands will fail. ```bash ping ``` -------------------------------- ### Set Terminal Session Callbacks and Initialize Source: https://context7.com/jackpal/android-terminal-emulator/llms.txt Configures callbacks for screen updates, title changes, and session termination. Also shows how to initialize the emulator with specific dimensions and start writing commands. ```java // Set update callback to be notified when screen changes session.setUpdateCallback(new UpdateCallback() { @Override public void onUpdate() { // Handle screen update - refresh your view System.out.println("Terminal screen updated"); } }); // Set title change listener session.setTitleChangedListener(new UpdateCallback() { @Override public void onUpdate() { String newTitle = session.getTitle(); System.out.println("Title changed to: " + newTitle); } }); // Set callback for when session finishes session.setFinishCallback(new TermSession.FinishCallback() { @Override public void onSessionFinish(TermSession session) { System.out.println("Terminal session ended"); } }); // Initialize emulator with terminal dimensions (columns, rows) session.initializeEmulator(80, 24); // Write data to the terminal (sends to the connected process) session.write("ls -la\n"); session.write("echo Hello, Terminal!\n".getBytes(), 0, 21); ``` -------------------------------- ### Clone Terminal Emulator for Android Repository Source: https://github.com/jackpal/android-terminal-emulator/wiki/Translating-to-Other-Languages Use this command to clone the project repository from GitHub. Ensure Git is installed before proceeding. ```bash $ git clone git://github.com/jackpal/Android-Terminal-Emulator.git ``` -------------------------------- ### Android String Array Resource Example Source: https://github.com/jackpal/android-terminal-emulator/wiki/Translating-to-Other-Languages This is an example of an Android string array resource file (arrays.xml) used for defining UI elements like status bar preferences. Localize the text within the tags. ```xml Show status bar Hide status bar ``` ```xml SHOW STATUS BAR HIDE STATUS BAR ``` -------------------------------- ### Combining Characters Example Source: https://github.com/jackpal/android-terminal-emulator/blob/master/docs/UTF-8-demo.txt This example illustrates the use of combining characters in UTF-8, such as diacritics and accents applied to base characters. Proper rendering depends on UTF-8 support. ```text STARGΛ̊TE SG-1, a = v̇ = r̈, a⃑ ⊥ b⃑ ``` -------------------------------- ### Russian Text Example Source: https://github.com/jackpal/android-terminal-emulator/blob/master/docs/UTF-8-demo.txt This example displays Russian text, illustrating UTF-8 support for Cyrillic characters. A UTF-8 compatible font is necessary for correct display. ```russian Зарегистрируйтесь сейчас на Десятую Международную Конференцию по Unicode, которая состоится 10-12 марта 1997 года в Майнце в Германии. Конференция соберет широкий круг экспертов по вопросам глобального Интернета и Unicode, локализации и интернационализации, воплощению и применению Unicode в различных операционных системах и программных приложениях, шрифтах, верстке и многоязычных компьютерных системах. ``` -------------------------------- ### Configure NDK and SDK Paths for Gradle Source: https://github.com/jackpal/android-terminal-emulator/blob/master/docs/Building.md Create a local.properties file in the project root to specify the paths to your Android NDK and SDK installations. This is required for the Gradle build tool. ```properties ndk.dir=path/to/ndk sdk.dir=path/to/sdk ``` ```properties ndk.dir=/Users/jack/code/android-ndk-r10d sdk.dir=/Users/jack/Library/Android/sdk ``` -------------------------------- ### Misleading Error Message Example Source: https://github.com/jackpal/android-terminal-emulator/wiki/Android-Shell-Command-Reference Demonstrates a common error message in the Android shell where 'permission denied' is shown for a non-existent command instead of 'not found'. ```bash $ dir dir: permission denied <---- this is a misleading error message, should say 'dir: not found' $ ls ... listing of current directory ``` -------------------------------- ### Polytonic Greek Example Source: https://github.com/jackpal/android-terminal-emulator/blob/master/docs/UTF-8-demo.txt This snippet displays Greek text in the Polytonic system, showcasing its use for ancient Greek. It requires a UTF-8 compatible font for correct rendering. ```greek Σὲ γνωρίζω ἀπὸ τὴν κόψη τοῦ σπαθιοῦ τὴν τρομερή, σὲ γνωρίζω ἀπὸ τὴν ὄψη ποὺ μὲ βία μετράει τὴ γῆ. ᾿Απ᾿ τὰ κόκκαλα βγαλμένη τῶν ῾Ελλήνων τὰ ἱερά καὶ σὰν πρῶτα ἀνδρειωμένη χαῖρε, ὦ χαῖρε, ᾿Ελευθεριά! ``` ```greek Οὐχὶ ταὐτὰ παρίσταταί μοι γιγνώσκειν, ὦ ἄνδρες ᾿Αθηναῖοι, ὅταν τ᾿ εἰς τὰ πράγματα ἀποβλέψω καὶ ὅταν πρὸς τοὺς λόγους οὓς ἀκούω· τοὺς μὲν γὰρ λόγους περὶ τοῦ τιμωρήσασθαι Φίλιππον ὁρῶ γιγνομένους, τὰ δὲ πράγματ᾿ εἰς τοῦτο προήκοντα, ὥσθ᾿ ὅπως μὴ πεισόμεθ᾿ αὐτοὶ πρότερον κακῶς σκέψασθαι δέον. οὐδέν οὖν ἄλλο μοι δοκοῦσιν οἱ τὰ τοιαῦτα λέγοντες ἢ τὴν ὑπόθεσιν, περὶ ἧς βουλεύεσθαι, οὐχὶ τὴν οὖσαν παριστάντες ὑμῖν ἁμαρτάνειν. ἐγὼ δέ, ὅτι μέν ποτ᾿ ἐξῆν τῇ πόλει καὶ τὰ αὑτῆς ἔχειν ἀσφαλῶς καὶ Φίλιππον τιμωρήσασθαι, καὶ μάλ᾿ ἀκριβῶς οἶδα· ἐπ᾿ ἐμοῦ γάρ, οὐ πάλαι γέγονεν ταῦτ᾿ ἀμφότερα· νῦν μέντοι πέπεισμαι τοῦθ᾿ ἱκανὸν προλαβεῖν ἡμῖν εἶναι τὴν πρώτην, ὅπως τοὺς συμμάχους σώσομεν. ἐὰν γὰρ τοῦτο βεβαίως ὑπάρξῃ, τότε καὶ περὶ τοῦ τίνα τιμωρήσεταί τις καὶ ὃν τρόπον ἐξέσται σκοπεῖν· πρὶν δὲ τὴν ἀρχὴν ὀρθῶς ὑποθέσθαι, μάταιον ἡγοῦμαι περὶ τῆς τελευτῆς ὁντινοῦν ποιεῖσθαι λόγον. Δημοσθένους, Γ´ ᾿Ολυνθιακὸς ``` -------------------------------- ### Test for Shellshock vulnerability Source: https://github.com/jackpal/android-terminal-emulator/wiki/Frequently-Asked-Questions Execute this command in the terminal to determine if the installed version of bash is susceptible to the Shellshock security bug. ```bash env x='() { :;}; echo vulnerable' bash -c "echo this is a test" ``` -------------------------------- ### APL Code Example Source: https://github.com/jackpal/android-terminal-emulator/blob/master/docs/UTF-8-demo.txt This snippet demonstrates APL code, a programming language known for its concise array-processing capabilities. It requires an APL interpreter to run. ```apl ((V⍳V)=⍳⍴V)/V←,V ⌷←⍳→⍴∆∇⊃‾⍎⍕⌈ ``` -------------------------------- ### Nicely Formatted Plain Text with UTF-8 Characters Source: https://github.com/jackpal/android-terminal-emulator/blob/master/docs/UTF-8-demo.txt This example shows how UTF-8 can be used to create visually appealing plain text files with various typographical elements, including different types of quotes, accents, and symbols. It is intended for display in a UTF-8 compatible environment. ```text ╔══════════════════════════════════════════╗ ║ ║ ║ • ‘single’ and “double” quotes ║ ║ ║ ║ • Curly apostrophes: “We’ve been here” ║ ║ ║ • Latin-1 apostrophe and accents: '´` ║ ║ ║ ║ • ‚deutsche‘ „Anführungszeichen“ ║ ║ ║ ║ • †, ‡, ‰, •, 3–4, —, −5/+5, ™, … ║ ║ ║ ║ • ASCII safety test: 1lI|, 0OD, 8B ║ ║ ╭─────────╮ ║ ║ • the euro symbol: │ 14.95 € │ ║ ║ ╰─────────╯ ║ ╚══════════════════════════════════════════╝ ``` -------------------------------- ### Linguistic and Dictionary UTF-8 Characters Source: https://github.com/jackpal/android-terminal-emulator/blob/master/docs/UTF-8-demo.txt This example demonstrates the use of UTF-8 for linguistic and phonetic transcriptions. It requires a UTF-8 compatible font for correct rendering. ```text ði ıntəˈnæʃənəl fəˈnɛtık əsoʊsiˈeıʃn Y [ˈʏpsilɔn], Yen [jɛn], Yoga [ˈjoːgɑ] ``` -------------------------------- ### Mathematical and Scientific UTF-8 Characters Source: https://github.com/jackpal/android-terminal-emulator/blob/master/docs/UTF-8-demo.txt This example showcases various mathematical and scientific symbols representable in UTF-8. It is intended for display in a UTF-8 compatible environment. ```text ∮ E⋅da = Q, n → ∞, ∑ f(i) = ∏ g(i), ⎧⎡⎛┌─────┐⎞⎤⎫ ⎪⎢⎜│a²+b³ ⎟⎥⎪ ∀x∈ℝ: ⌈x⌉ = −⌊−x⌋, α ∧ ¬β = ¬(¬α ∨ β), ⎪⎢⎜│───── ⎟⎥⎪ ⎪⎢⎜⎷ c₈ ⎟⎥⎪ ℕ ⊆ ℕ₀ ⊂ ℤ ⊂ ℚ ⊂ ℝ ⊂ ℂ, ⎨⎢⎜ ⎟⎥⎬ ⎪⎢⎜ ∞ ⎟⎥⎪ ⊥ < a ≠ b ≡ c ≤ d ≪ ⊤ ⇒ (⟦A⟧ ⇔ ⟪B⟫), ⎪⎢⎜ ⎲ ⎟⎥⎪ ⎪⎢⎜ ⎳aⁱ-bⁱ⎟⎥⎪ 2H₂ + O₂ ⇌ 2H₂O, R = 4.7 kΩ, ⌀ 200 mm ⎩⎣⎝i=1 ⎠⎦⎭ ``` -------------------------------- ### Georgian Text Example Source: https://github.com/jackpal/android-terminal-emulator/blob/master/docs/UTF-8-demo.txt This snippet shows Georgian text, demonstrating UTF-8's capability to handle non-Latin scripts. Proper rendering depends on a UTF-8 compatible font. ```georgian გთხოვთ ახლავე გაიაროთ რეგისტრაცია Unicode-ის მეათე საერთაშორისო კონფერენციაზე დასასწრებად, რომელიც გაიმართება 10-12 მარტს, ქ. მაინცში, გერმანიაში. კონფერენცია შეჰკრებს ერთად მსოფლიოს ექსპერტებს ისეთ დარგებში როგორიცაა ინტერნეტი და Unicode-ი, ინტერნაციონალიზაცია და ლოკალიზაცია, Unicode-ის გამოყენება ოპერაციულ სისტემებსა, და გამოყენებით პროგრამებში, შრიფტებში, ტექსტების დამუშავებასა და მრავალენოვან კომპიუტერულ სისტემებში. ``` -------------------------------- ### Thai Text Example (UCS Level 2) Source: https://github.com/jackpal/android-terminal-emulator/blob/master/docs/UTF-8-demo.txt This snippet presents Thai text from a poetry excerpt, demonstrating UTF-8's support for Level 2 UCS characters. Correct rendering requires a UTF-8 compatible font. ```thai ๏ แผ่นดินฮั่นเสื่อมโทรมแสนสังเวช พระปกเกศกองบู๊กู้ขึ้นใหม่ สิบสองกษัตริย์ก่อนหน้าแลถัดไป สององค์ไซร้โง่เขลาเบาปัญญา ทรงนับถือขันทีเป็นที่พึ่ง บ้านเมืองจึงวิปริตเป็นนักหนา โฮจิ๋นเรียกทัพทั่วหัวเมืองมา หมายจะฆ่ามดชั่วตัวสำคัญ เหมือนขับไสไล่เสือจากเคหา รับหมาป่าเข้ามาเลยอาสัญ ฝ่ายอ้องุ้นยุแยกให้แตกกัน ใช้สาวนั้นเป็นชนวนชื่นชวนใจ พลันลิฉุยกุยกีกลับก่อเหตุ ช่างอาเพศจริงหนาฟ้าร้องไห้ ต้องรบราฆ่าฟันจนบรรลัย ฤๅหาใครค้ำชูกู้บรรลังก์ ฯ ``` -------------------------------- ### Initialize and Configure EmulatorView Source: https://context7.com/jackpal/android-terminal-emulator/llms.txt Demonstrates programmatic initialization of EmulatorView, including session attachment, color scheme definition, and keyboard behavior configuration. ```java import jackpal.androidterm.emulatorview.EmulatorView; import jackpal.androidterm.emulatorview.TermSession; import jackpal.androidterm.emulatorview.ColorScheme; import android.app.Activity; import android.os.Bundle; import android.util.DisplayMetrics; import android.view.GestureDetector; import android.view.MotionEvent; public class TerminalActivity extends Activity { private EmulatorView mEmulatorView; private TermSession mSession; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Create terminal session mSession = new TermSession(); // ... configure session streams ... // Get display metrics for proper scaling DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); // Create EmulatorView programmatically mEmulatorView = new EmulatorView(this, mSession, metrics); // Or if inflated from XML, attach session separately: // mEmulatorView = (EmulatorView) findViewById(R.id.emulator_view); // mEmulatorView.attachSession(mSession); // mEmulatorView.setDensity(metrics); // Configure text size (in density-independent pixels) mEmulatorView.setTextSize(14); // Set color scheme ColorScheme colorScheme = new ColorScheme( 0xFFFFFFFF, // foreground (white) 0xFF000000, // background (black) 0xFF000000, // cursor foreground 0xFF00FF00 // cursor background (green) ); mEmulatorView.setColorScheme(colorScheme); // Configure keyboard behavior mEmulatorView.setBackKeyCharacter(0); // ESC on back key (0 = ESC) mEmulatorView.setControlKeyCode(KeyEvent.KEYCODE_VOLUME_DOWN); mEmulatorView.setFnKeyCode(KeyEvent.KEYCODE_VOLUME_UP); mEmulatorView.setAltSendsEsc(true); // Alt key sends ESC prefix // Enable mouse tracking for applications that support it mEmulatorView.setMouseTracking(true); // Set IME mode ("cooked" processes IME input, "raw" passes directly) mEmulatorView.setUseCookedIME(true); // Set terminal type for escape sequence handling mEmulatorView.setTermType("xterm"); // Add custom gesture listener mEmulatorView.setExtGestureListener(new GestureDetector.SimpleOnGestureListener() { @Override public boolean onDoubleTap(MotionEvent e) { // Handle double tap - e.g., toggle full screen return true; } }); setContentView(mEmulatorView); } @Override protected void onResume() { super.onResume(); mEmulatorView.onResume(); // Start cursor blinking, etc. } @Override protected void onPause() { super.onPause(); mEmulatorView.onPause(); // Stop cursor blinking } // Text selection and clipboard public void toggleTextSelection() { mEmulatorView.toggleSelectingText(); if (!mEmulatorView.getSelectingText()) { String selectedText = mEmulatorView.getSelectedText(); // Use selected text... } } // Scrolling public void scrollUp() { mEmulatorView.page(-1); // Scroll up one page } public void scrollDown() { mEmulatorView.page(1); // Scroll down one page } // Get URL at touch position public String getLinkAt(float x, float y) { return mEmulatorView.getURLat(x, y); } // Send special keys public void sendCtrl() { mEmulatorView.sendControlKey(); } public void sendFn() { mEmulatorView.sendFnKey(); } // Get terminal dimensions public void getTerminalSize() { int rows = mEmulatorView.getVisibleRows(); int cols = mEmulatorView.getVisibleColumns(); int width = mEmulatorView.getVisibleWidth(); int height = mEmulatorView.getVisibleHeight(); } } ``` -------------------------------- ### Build Project from Command Line Source: https://context7.com/jackpal/android-terminal-emulator/llms.txt Commands for configuring the local environment and building the project using Gradle or provided shell scripts. ```bash # Create local.properties in project root echo "ndk.dir=/path/to/android-ndk" > local.properties echo "sdk.dir=/path/to/android-sdk" >> local.properties # Build debug APK from command line ./gradlew assembleDebug # Or use the provided scripts ./tools/build-debug # Install and run on connected device ./tools/push-and-run-debug # Build all modules ./gradlew build ``` -------------------------------- ### Build TEA from Command Line Source: https://github.com/jackpal/android-terminal-emulator/blob/master/docs/Building.md Use the provided build scripts to compile the TEA project from the command line. Ensure local.properties is configured. ```bash $ ./tools/build-debug ``` -------------------------------- ### Create and Configure a Basic Terminal Session Source: https://context7.com/jackpal/android-terminal-emulator/llms.txt Demonstrates the creation of a TermSession, setting up input/output streams, configuring UTF-8 mode, and applying a color scheme. Use this to initialize a new terminal session with custom settings. ```java import jackpal.androidterm.emulatorview.TermSession; import jackpal.androidterm.emulatorview.ColorScheme; import java.io.InputStream; import java.io.OutputStream; // Create a basic terminal session TermSession session = new TermSession(); // Configure input/output streams (e.g., from a socket or process) InputStream processOutput = /* your input stream */; OutputStream processInput = /* your output stream */; session.setTermIn(processOutput); session.setTermOut(processInput); // Enable UTF-8 mode for international character support session.setDefaultUTF8Mode(true); // Set a custom color scheme (foreground, background as ARGB) ColorScheme scheme = new ColorScheme(0xFFFFFFFF, 0xFF000000); // White on black session.setColorScheme(scheme); ``` -------------------------------- ### Listing Directory Contents with Root Access Source: https://github.com/jackpal/android-terminal-emulator/wiki/Android-Shell-Command-Reference Demonstrates how to gain root access using 'su' and then list the contents of '/sbin', showing available daemon programs. ```bash $ su # ls /sbin ueventd adbd ``` -------------------------------- ### Open project wiki Source: https://github.com/jackpal/android-terminal-emulator/blob/master/docs/releaseChecklist.md Opens the wiki page for recent updates. ```bash open https://github.com/jackpal/Android-Terminal-Emulator/wiki/Recent-Updates ``` -------------------------------- ### Listing Directory Contents (No Such File) Source: https://github.com/jackpal/android-terminal-emulator/wiki/Android-Shell-Command-Reference Attempts to list the contents of '/data/local/bin' which does not exist by default, resulting in a 'No such file or directory' message. ```bash $ ls /data/local/bin /data/local/bin: No such file or directory ``` -------------------------------- ### Listing Directory Contents (Permission Denied) Source: https://github.com/jackpal/android-terminal-emulator/wiki/Android-Shell-Command-Reference Attempts to list the contents of '/sbin' without root access, resulting in a 'Permission denied' error. ```bash $ ls /sbin opendir failed, Permission denied ``` -------------------------------- ### Listing Vendor Bin Directory Source: https://github.com/jackpal/android-terminal-emulator/wiki/Android-Shell-Command-Reference Lists the contents of the '/vendor/bin' directory, which contains device-specific executables. ```bash $ ls /vendor/bin gpsd pvrsrvinit ``` -------------------------------- ### Build release APK Source: https://github.com/jackpal/android-terminal-emulator/blob/master/docs/releaseChecklist.md Generates the release APK; requires signing keys. ```bash tools/build-release ``` -------------------------------- ### Open Google Play Console Source: https://github.com/jackpal/android-terminal-emulator/blob/master/docs/releaseChecklist.md Opens the Google Play publishing dashboard. ```bash open https://play.google.com/apps/publish ``` -------------------------------- ### Push and Run Debug Build Source: https://github.com/jackpal/android-terminal-emulator/blob/master/docs/Building.md Copy the built debug executable to a connected Android device and run it using the provided script. ```bash $ ./tools/push-and-run-debug ``` -------------------------------- ### RUN_SCRIPT Intent Source: https://github.com/jackpal/android-terminal-emulator/wiki/Launching Terminal Emulator for Android from another App This intent opens a new terminal window and executes a specified initial command. It requires the RUN_SCRIPT permission. ```APIDOC ## POST /intent/jackpal.androidterm.RUN_SCRIPT ### Description Opens a new window and runs the script specified in the jackpal.androidterm.iInitialCommand extra. Applications using this intent must have the jackpal.androidterm.permission.RUN_SCRIPT permission. ### Method POST ### Endpoint Intent Action: "jackpal.androidterm.RUN_SCRIPT" ### Parameters #### Request Body - **jackpal.androidterm.iInitialCommand** (string) - Required - The initial command to be executed in the terminal. ### Request Example ```java Intent i = new Intent("jackpal.androidterm.RUN_SCRIPT"); i.addCategory(Intent.CATEGORY_DEFAULT); i.putExtra("jackpal.androidterm.iInitialCommand", "echo 'Hi there!'"); startActivity(i); ``` ### Response #### Success Response (200) Launches the terminal emulator in a new window and executes the provided command. #### Response Example (No specific response body, launches an activity) ``` -------------------------------- ### Listing System Bin Directory Source: https://github.com/jackpal/android-terminal-emulator/wiki/Android-Shell-Command-Reference Lists the contents of the '/system/bin' directory, which includes core Android command-line utilities like 'am'. ```bash $ ls /system/bin am ``` -------------------------------- ### Bind to ITerminal Service Source: https://context7.com/jackpal/android-terminal-emulator/llms.txt Demonstrates how to connect to the terminal service and initiate a session using the ITerminal AIDL interface. ```java // ITerminal.aidl interface (v1) // Package: jackpal.androidterm.libtermexec.v1 // Client application example import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentSender; import android.content.ServiceConnection; import android.os.IBinder; import android.os.ParcelFileDescriptor; import android.os.ResultReceiver; import jackpal.androidterm.libtermexec.v1.ITerminal; import java.io.File; public class TerminalServiceClient { private ITerminal mTerminalService; private ServiceConnection mConnection; public void bindToTerminalService(Context context) { mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { mTerminalService = ITerminal.Stub.asInterface(service); startTerminalSession(); } @Override public void onServiceDisconnected(ComponentName name) { mTerminalService = null; } }; Intent intent = new Intent("jackpal.androidterm.action.START_TERM.v1"); context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE); } private void startTerminalSession() { try { // Open PTY master device ParcelFileDescriptor ptmx = ParcelFileDescriptor.open( new File("/dev/ptmx"), ParcelFileDescriptor.MODE_READ_WRITE ); // Create callback for session events ResultReceiver callback = new ResultReceiver(null) { @Override protected void onReceiveResult(int resultCode, Bundle resultData) { if (resultCode == 0) { // Session ended System.out.println("Terminal session ended"); } } }; // Start session and get IntentSender for launching activity IntentSender sender = mTerminalService.startSession(ptmx, callback); // Launch the terminal activity // startIntentSender(sender, null, 0, 0, 0); } catch (Exception e) { e.printStackTrace(); } } public void unbind(Context context) { if (mConnection != null) { context.unbindService(mConnection); } } } ``` -------------------------------- ### Retrieve Transcript, Reset, and Finish Session Source: https://context7.com/jackpal/android-terminal-emulator/llms.txt Shows how to retrieve the full terminal transcript, reset the terminal's state, and properly finish/clean up the session when it's no longer needed. ```java // Get the full transcript (screen + scrollback buffer) String transcript = session.getTranscriptText(); // Reset terminal state session.reset(); // Clean up when done session.finish(); ``` -------------------------------- ### Run Script Intent with Initial Command Source: https://github.com/jackpal/android-terminal-emulator/wiki/Launching Terminal Emulator for Android from another App Launches a new terminal window and executes a specified command. Requires the 'jackpal.androidterm.permission.RUN_SCRIPT' permission declared in the application manifest. ```java Intent i = new Intent("jackpal.androidterm.RUN_SCRIPT"); i.addCategory(Intent.CATEGORY_DEFAULT); i.putExtra("jackpal.androidterm.iInitialCommand", "echo 'Hi there!'"); startActivity(i); ``` -------------------------------- ### Verify 256 Color Support Source: https://github.com/jackpal/android-terminal-emulator/wiki/Troubleshooting-Lack-of-Color-in-Vi Test the terminal's 256-color support by downloading and displaying a specific control sequence file. This helps confirm if the terminal emulator is rendering colors as expected. ```bash cat 256color.txt ``` -------------------------------- ### Enable ProGuard in project.properties Source: https://github.com/jackpal/android-terminal-emulator/blob/master/tests/emulatorview-test/proguard-project.txt To enable ProGuard, edit `project.properties` to define the `proguard.config` property. This file allows you to add project-specific ProGuard rules. ```properties # To enable ProGuard in your project, edit project.properties # to define the proguard.config property as described in that file. # # Add project specific ProGuard rules here. # By default, the flags in this file are appended to flags specified # in ${sdk.dir}/tools/proguard/proguard-android.txt # You can edit the include path and order by changing the ProGuard # include property in project.properties. # # For more details, see # http://developer.android.com/guide/developing/tools/proguard.html # Add any project specific keep options here: # If your project uses WebView with JS, uncomment the following # and specify the fully qualified class name to the JavaScript interface # class: #-keepclassmembers class fqcn.of.javascript.interface.for.webview { # public *; #} ``` -------------------------------- ### OPEN_NEW_WINDOW Intent Source: https://github.com/jackpal/android-terminal-emulator/wiki/Launching Terminal Emulator for Android from another App This intent opens a new terminal window without executing any commands or requiring special permissions. ```APIDOC ## POST /intent/jackpal.androidterm.OPEN_NEW_WINDOW ### Description Opens a new terminal window. No script execution is allowed, and no permissions are required to use this action. ### Method POST ### Endpoint Intent Action: "jackpal.androidterm.OPEN_NEW_WINDOW" ### Parameters None ### Request Example ```java Intent i = new Intent("jackpal.androidterm.OPEN_NEW_WINDOW"); i.addCategory(Intent.CATEGORY_DEFAULT); startActivity(i); ``` ### Response #### Success Response (200) Launches the terminal emulator in a new window. #### Response Example (No specific response body, launches an activity) ``` -------------------------------- ### Check CLICOLOR Environment Variable Source: https://github.com/jackpal/android-terminal-emulator/wiki/Troubleshooting-Lack-of-Color-in-Vi Verify if the CLICOLOR environment variable is set to enable colors. Set CLICOLOR=1 to enable. ```bash $ echo $CLICOLOR ``` -------------------------------- ### Displaying the PATH Variable Source: https://github.com/jackpal/android-terminal-emulator/wiki/Android-Shell-Command-Reference Shows how to use the 'echo' command to display the current value of the PATH environment variable in the Android shell. ```bash $ echo $PATH /data/local/bin:/sbin:/vendor/bin:/system/sbin:/system/bin:/system/xbin ``` -------------------------------- ### Tag release version Source: https://github.com/jackpal/android-terminal-emulator/blob/master/docs/releaseChecklist.md Applies a git tag to the current branch for the new version. ```bash git tag v1.0.xx ``` -------------------------------- ### Open New Terminal Window Intent Source: https://github.com/jackpal/android-terminal-emulator/wiki/Launching Terminal Emulator for Android from another App Use this intent to open a new terminal window. No special permissions are required. ```java Intent i = new Intent("jackpal.androidterm.OPEN_NEW_WINDOW"); i.addCategory(Intent.CATEGORY_DEFAULT); startActivity(i); ``` -------------------------------- ### Launch Terminal via Intents Source: https://context7.com/jackpal/android-terminal-emulator/llms.txt Uses Android Intents to open new terminal windows or execute scripts. The RUN_SCRIPT action requires the jackpal.androidterm.permission.RUN_SCRIPT permission. ```java import android.app.Activity; import android.content.Intent; import android.os.Bundle; public class LaunchTerminalExample extends Activity { private static final int REQUEST_WINDOW_HANDLE = 1; private String mWindowHandle; // Open a new terminal window (no permissions required) public void openNewTerminal() { Intent intent = new Intent("jackpal.androidterm.OPEN_NEW_WINDOW"); intent.addCategory(Intent.CATEGORY_DEFAULT); startActivity(intent); } // Run a script in a new terminal window // Requires: public void runScript(String command) { Intent intent = new Intent("jackpal.androidterm.RUN_SCRIPT"); intent.addCategory(Intent.CATEGORY_DEFAULT); intent.putExtra("jackpal.androidterm.iInitialCommand", command); startActivity(intent); } // Run script in existing window (reuse window handle) public void runScriptInExistingWindow(String command) { Intent intent = new Intent("jackpal.androidterm.RUN_SCRIPT"); intent.addCategory(Intent.CATEGORY_DEFAULT); intent.putExtra("jackpal.androidterm.iInitialCommand", command); if (mWindowHandle != null) { // Reuse existing window if available intent.putExtra("jackpal.androidterm.window_handle", mWindowHandle); } // Get the window handle back via onActivityResult startActivityForResult(intent, REQUEST_WINDOW_HANDLE); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode != RESULT_OK || data == null) return; if (requestCode == REQUEST_WINDOW_HANDLE) { // Save window handle for future reuse mWindowHandle = data.getStringExtra("jackpal.androidterm.window_handle"); } } // Example usage public void demonstrateIntents() { // Simple command runScript("echo 'Hello from another app!'"); // Multiple commands runScript("cd /sdcard && ls -la && echo 'Done!'"); // Interactive session runScript("top"); } } // Required AndroidManifest.xml permission for RUN_SCRIPT: // ``` -------------------------------- ### Publish pre-compiled APK Source: https://github.com/jackpal/android-terminal-emulator/blob/master/docs/releaseChecklist.md Updates the gh-pages branch with the new APK and index file. ```bash cp ./term/build/outputs/apk/Term.apk /tmp git checkout gh-pages mv /tmp/Term.apk downloads/Term.apk git add downloads/Term.apk subl index.html # Update version save index.html git add index.html git commit -m "Update to version v1.0.xx" git push git checkout master ``` -------------------------------- ### Registering for PATH Broadcasts in Android Terminal Emulator Source: https://context7.com/jackpal/android-terminal-emulator/llms.txt Implement a BroadcastReceiver to receive APPEND_TO_PATH or PREPEND_TO_PATH actions. Declare necessary permissions and the receiver in AndroidManifest.xml. Use APPEND_TO_PATH for utilities that should not override system commands and PREPEND_TO_PATH for utilities that should override system commands. ```java import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import java.io.File; // Declare in AndroidManifest.xml: // // // // // // // // // public class PathReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); String packageName = context.getPackageName(); // Set up your bin directory with executables File binDir = new File(context.getApplicationInfo().dataDir, "bin"); if (!binDir.exists()) { binDir.mkdir(); // Copy your executables to binDir... } // APPEND_TO_PATH: Add directory to end of PATH // Use for utilities that shouldn't override system commands if ("jackpal.androidterm.broadcast.APPEND_TO_PATH".equals(action)) { Bundle result = getResultExtras(true); result.putString(packageName, binDir.getAbsolutePath()); setResultCode(Activity.RESULT_OK); } // PREPEND_TO_PATH: Add directory to beginning of PATH // Use for utilities that should override system commands (like BusyBox) if ("jackpal.androidterm.broadcast.PREPEND_TO_PATH".equals(action)) { File sbinDir = new File(context.getApplicationInfo().dataDir, "sbin"); if (!sbinDir.exists()) { sbinDir.mkdir(); } Bundle result = getResultExtras(true); // Prefix with number to control ordering: "00-" = highest priority result.putString("00-" + packageName, sbinDir.getAbsolutePath()); setResultCode(Activity.RESULT_OK); } } } ``` -------------------------------- ### Configure Terminal ColorScheme Source: https://context7.com/jackpal/android-terminal-emulator/llms.txt Defines terminal foreground, background, and cursor colors using ARGB hex values. Cursor colors are automatically calculated if omitted. ```java import jackpal.androidterm.emulatorview.ColorScheme; // Simple scheme with just foreground and background // Cursor colors will be automatically selected ColorScheme simpleScheme = new ColorScheme( 0xFFFFFFFF, // foreground: white 0xFF000000 // background: black ); // Full scheme with custom cursor colors ColorScheme fullScheme = new ColorScheme( 0xFF00FF00, // foreground: green 0xFF000000, // background: black 0xFF000000, // cursor foreground: black 0xFF00FF00 // cursor background: green ); // Create from array (2 or 4 elements) int[] schemeArray = { 0xFFE0E0E0, 0xFF1A1A1A }; // Light gray on dark gray ColorScheme arrayScheme = new ColorScheme(schemeArray); int[] fullArray = { 0xFFFFFFFF, 0xFF000000, 0xFF000000, 0xFFFFFF00 }; ColorScheme fullArrayScheme = new ColorScheme(fullArray); // Access color values int foreground = fullScheme.getForeColor(); int background = fullScheme.getBackColor(); int cursorFore = fullScheme.getCursorForeColor(); int cursorBack = fullScheme.getCursorBackColor(); // Apply to session and view session.setColorScheme(fullScheme); emulatorView.setColorScheme(fullScheme); // Use null for default scheme session.setColorScheme(null); // Revert to defaults ``` -------------------------------- ### Push changes to repository Source: https://github.com/jackpal/android-terminal-emulator/blob/master/docs/releaseChecklist.md Pushes commits and tags to the remote repository. ```bash git push git push --tags ```