Android SharedPreferences Tutorial and Example

Building a terminal emulator for Android

A terminal emulator app for Android should behave like a real remote session, not merely run canned commands. It needs a pseudo-terminal, a shell, escape-sequence handling and a responsive display. The result is a compact workstation for SSH, Git, scripts and lightweight system administration.

Australian developers can see the appeal. A train trip through Melbourne can become time for reviewing a repository, while a technician near Wagga Wagga may need a log when ordinary broadband is unavailable. An Android tablet also makes touch input, resizing and patchy mobile connections essential design concerns.

Android’s sandbox sets the technical limits. Do not assume /system/bin/sh provides the GNU tools familiar from a desktop, and do not grant blanket access to shared storage. A sensible first project bundles a small shell for each ABI, keeps files in app-private storage and requests permissions only for defined features. For Australian users, “no dramas” means smooth upgrades, transparent data handling and good performance on budget as well as premium phones.

This guide covers the native-backed architecture, from spawning a shell through a PTY to drawing output and packaging a release. Keep the version focused: a shell, keyboard input, resizing, copying and bounded scrollback. Kotlin can handle the Android UI, while a small C or C++ layer supplies terminal operations the SDK does not expose.

Design the app around a genuine session

Separate the activity, session manager and renderer. The activity owns menus and lifecycle events; the manager owns the process and streams; the renderer turns terminal state into pixels. Running commands from a button handler mixes responsibilities and makes rotation or screen locking awkward.

Begin with running a shell, typing commands, resizing, copying and limited scrollback. SSH and package management can follow once their security, licensing and update requirements are understood. Follow Android conventions rather than copying a desktop: a bottom key bar, adjustable text size and a clear session notification often help more than crowded toolbars.

Treat input as untrusted. A pasted command may be destructive or contain control characters, so display it accurately and never silently reinterpret it. Avoid a fake parser built around strings such as ls; real programs rely on pipes, signals and standard input and output.

Spawn the shell through a pseudo-terminal

A normal ProcessBuilder starts a process with redirected pipes, not a terminal, so interactive programs may fail when they request a TTY. The practical solution is a native layer that opens a pseudo-terminal, starts the shell and connects its master side to the app. Verify the launch method on current Android versions; extracted assets are not automatically safe to execute under its executable-memory rules.

Use a PTY implementation suited to Android rather than assuming forkpty() is available in every NDK build. The native layer should report its descriptor, accept keyboard writes, return output bytes and handle window-size changes. Set TERM, HOME, PATH and locale explicitly, and restrict PATH to known directories so shared files cannot masquerade as programs.

A small JNI contract keeps the layers separate:

external fun openPty(command: String, env: Array<String>, cols: Int, rows: Int): Int
external fun readPty(fd: Int, buffer: ByteArray): Int
external fun writePty(fd: Int, data: ByteArray): Int
external fun resizePty(fd: Int, cols: Int, rows: Int)

Handle native failures as exceptions rather than allowing an invalid descriptor to break a later command.

Render terminal output without losing state

Terminal output is not ordinary text. Colour changes, cursor movement, line clearing and cursor addressing arrive as ANSI or VT escape sequences. A renderer must maintain a grid of characters and attributes rather than append raw bytes to a TextView. Carriage return, backspace, tabs and wrapping also need consistent handling.

For a proof of concept, a custom View drawing to a Canvas can display a grid, cursor and scrolling region. SurfaceView suits frequent redraws, while TextureView helps when transformations matter. Keep text size, line spacing and cell dimensions synchronised with the terminal’s row and column counts. Resize the PTY before redrawing the new grid.

Escape-sequence support becomes difficult quickly. libvterm handles much of the VT parsing and screen model, but your app still renders cells and connects key events. The Termux terminal-emulator library offers an Android-oriented screen and view that can be studied or adapted. Test UTF-8, combining characters and wide glyphs so later text does not drift.

Make touch input feel like a keyboard

Android delivers key events, but a terminal needs more than printable characters. Maintain modifier state for Control, Alt and Shift, translate shortcuts into bytes expected by the active terminal mode, and expose function keys through explicit controls. Some hardware keys are unavailable, so an on-screen row for Tab, Escape, arrows and Control is dependable.

Make paste a deliberate action. Preview pasted content, remove dangerous control characters where appropriate, and never execute it merely because it entered the clipboard. Copying selected output should use Android’s clipboard API, with a warning that another app may read it. Avoid placing passwords in copied text when clipboard previews could expose them.

Disable ordinary keyboard suggestions if they interfere with shell input, while preserving normal editing keys. Support larger text and TalkBack navigation around controls, with generous touch targets. These details matter on long trips, when wearing gloves, or when bright sunlight makes a compact toolbar hard to use.

Protect data and survive background work

Keep working directories, history and settings in app-private storage. Non-sensitive preferences can live in SharedPreferences, but use the Android Keystore to protect encryption keys and keep passwords out of preferences and logs. Exclude command history and downloaded keys from cloud backups unless the user explicitly opts in.

Shell processes are fragile when Android reclaims memory or backgrounds the app. Use a foreground service with an appropriate declared service type and a visible notification for a session the user expects to continue. The notification should avoid exposing secrets. Use WorkManager for scheduled scripts, not interactive terminals.

Log output sparingly because PTY traffic can contain tokens, file contents and personal details. Redact obvious secrets, cap retained history and provide a clear deletion action. Australian healthcare, education and small-business users may inspect infrastructure under a client’s data-handling policy, making careful retention especially important.

Test, package and compare rendering options

Test the session before adding decorative features. Run interactive and non-interactive commands, check exit status, pipe data between processes and verify that Ctrl+C interrupts work. Resize during a full-screen editor, rotate the device, lock the screen and return. Unit tests can cover parsing and grid updates; instrumented tests should trace keys to the PTY and output to the view.

Package native code for the ABIs you support, commonly arm64-v8a and x86_64, then test on a physical phone and an emulator. Check 16 KB memory-page alignment requirements for recent Android releases. A Google Play submission needs correctly declared native libraries, an honest data-safety form and a clear privacy policy. Australian releases can show prices in AUD, but the listing must describe the app accurately.

The main rendering choices have different costs:

Approach Advantages Trade-offs Best fit
Termux terminal-emulator An established Android-oriented screen and view Check upstream licensing and Android compatibility before redistribution Studying or adapting an Android terminal
libvterm Mature VT/xterm parsing and screen model Requires NDK/JNI integration; your app still renders the cells Apps needing broad escape-sequence behaviour
Custom Canvas renderer Few dependencies and full control of appearance You must build parsing, selection, Unicode and cursor handling A small proof of concept