Use the Android clipboard safely

Copy a validated work-order reference and inspect an explicit paste without copying the private note or echoing rejected clipboard contents.
Android

What you will build

Copy and paste only a bounded valid work-order reference while preserving private draft text and the last valid reference on failure.
Pass an owned reference snapshot into the copy effect
Read typed clipboard results through registered callbacks
Validate pasted input before replacing the current reference
Keep private notes, automatic polling and rejected clipboard payloads out of the flow

Share the intended value, not the whole screen

A clipboard is a hand-off to other applications, not private application storage. That distinction matters even when the text looks harmless: a work-order reference can reveal information about a customer or a job. Here, the user enters a reference and chooses when to copy it. A separate private note is never part of that request.
The second step adds paste. Clipboard text is external input, so the app checks its format before changing the reference. A failure preserves the existing fields instead of clearing work the user has already done. Checking the format does not prove that the work order exists or that this user may open it; those are separate application checks.

Create the project and add Android

Clipboard text access is part of Fission's shell. It does not need an additional capability declaration. Add the YAML parser used for the checked-in translations.
cargo install cargo-fission
fission init android-use-the-android-clipboard-safely
cd android-use-the-android-clipboard-safely
fission add-target android --project-dir .
cargo add serde_yaml
For SDK/NDK setup, follow the Android setup tutorial. Launch an emulator or connect an Android phone before the native checks below. Keep the generated src/main.rs; replace the shared library entrypoint so the Android app runs this screen, not the starter counter.

Run the finished example

fission run --target android --project-dir .

1. Copy one validated reference

The state owns the reference and the current clipboard operation. The private note belongs to the screen's retained local state because no other screen or effect needs it. The copy reducer takes an owned snapshot of the reference, not the component or its private note.
The pending operation also prevents two requests from overlapping. That keeps completion handling small: this example needs one outstanding clipboard operation, not a queue or a second copy of the clipboard.
{"id":"fission-tabs-1","tabs":[{"index":0,"label":"src/state.rs","value":"src-state-rs"},{"index":1,"label":"src/app.rs","value":"src-app-rs"},{"index":2,"label":"src/translations.rs","value":"src-translations-rs"},{"index":3,"label":"i18n/en-US.yaml","value":"i18n-en-us-yaml"},{"index":4,"label":"i18n/es-ES.yaml","value":"i18n-es-es-yaml"},{"index":5,"label":"src/lib.rs","value":"src-lib-rs"},{"index":6,"label":"preview/lib.rs","value":"preview-lib-rs"}]}
{"id":"fission-tabs-1","index":0,"label":"src/state.rs","value":"src-state-rs"}
use fission::prelude::*;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Operation { Copy, Paste }

#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum Notice {
    #[default]
    Ready,
    Copied,
    Pasted,
    InvalidReference,
    EmptyClipboard,
    Unsupported,
    Denied,
    Failed,
}

impl Notice {
    pub fn key(self) -> &'static str {
        match self {
            Self::Ready => "handoff.ready",
            Self::Copied => "handoff.copied",
            Self::Pasted => "handoff.pasted",
            Self::InvalidReference => "handoff.invalid",
            Self::EmptyClipboard => "handoff.empty",
            Self::Unsupported => "handoff.unsupported",
            Self::Denied => "handoff.denied",
            Self::Failed => "handoff.failed",
        }
    }
}

#[derive(Debug, Default)]
pub struct ClipboardState {
    pub reference: String,
    pub pending: Option<Operation>,
    pub notice: Notice,
}

impl GlobalState for ClipboardState {}

pub fn valid_reference(input: &str) -> bool {
    let Some(number) = input.strip_prefix("WO-") else { return false; };
    !number.is_empty()
        && number.len() <= 12
        && number.bytes().all(|byte| byte.is_ascii_digit())
}

pub fn copy_reference(state: &mut ClipboardState, ctx: &mut ReducerContext<ClipboardState>) {
    if state.pending.is_some() { return; }
    let reference = state.reference.trim().to_owned();
    if !valid_reference(&reference) {
        state.notice = Notice::InvalidReference;
        return;
    }
    state.pending = Some(Operation::Copy);
    state.notice = Notice::Ready;
    let ok = ctx.effects.bind(ReferenceCopied, reduce_with!(reference_copied));
    let err = ctx.effects.bind(ClipboardFailed, reduce_with!(clipboard_failed));
    ctx.effects.clipboard()
        .write_text(ClipboardWriteTextRequest { text: reference })
        .on_ok(ok)
        .on_err(err);
}

#[fission_reducer(ReferenceCopied)]
fn reference_copied(state: &mut ClipboardState, ctx: &mut ReducerContext<ClipboardState>) {
    if state.pending != Some(Operation::Copy) { return; }
    state.pending = None;
    state.notice = if ctx.input.capability_ok(WRITE_CLIPBOARD_TEXT).is_some() {
        Notice::Copied
    } else {
        Notice::Failed
    };
}

#[fission_reducer(ClipboardFailed)]
fn clipboard_failed(state: &mut ClipboardState, ctx: &mut ReducerContext<ClipboardState>) {
    let code = match state.pending.take() {
        Some(Operation::Copy) => ctx.input.capability_error(WRITE_CLIPBOARD_TEXT)
            .map(|error| error.code),
        Some(Operation::Paste) => ctx.input.capability_error(READ_CLIPBOARD_TEXT)
            .map(|error| error.code),
        None => return,
    };
    state.notice = match code.as_deref() {
        Some("unsupported") => Notice::Unsupported,
        Some("permission_denied") | Some("not_allowed") => Notice::Denied,
        _ => Notice::Failed,
    };
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn accepts_only_the_reference_format() {
        assert!(valid_reference("WO-1048"));
        for input in ["", "WO-", "WO-a", "WO-1\nprivate note", "WO-12", "WO-1234567890123"] {
            assert!(!valid_reference(input), "accepted invalid reference format");
        }
    }
}
{"id":"fission-tabs-1","index":1,"label":"src/app.rs","value":"src-app-rs"}
use fission::prelude::*;
use crate::state::{self, ClipboardState};

fission_component! {
    pub HandoffScreen<ClipboardState> {
        state { private_note: String = String::new() }
    }
    view(screen, state, cx) {
        let tokens = &cx.view.env().theme.tokens;
    } =>
    SafeArea(
        child: Scroll(
            child: Container(
                child: Column(gap: tokens.spacing.m, children: [
                    Text(cx.tr("handoff.title")).size(tokens.typography.heading2_size),
                    Text(cx.tr("handoff.context")),
                    TextInput(
                        label: Some(cx.tr("handoff.reference").into()),
                        helper_text: Some(cx.tr("handoff.format").into()),
                        enabled: state.pending.is_none(),
                        bind: state.reference,
                        semantics_identifier: "handoff.reference".to_string(),
                    ),
                    TextInput(
                        label: Some(cx.tr("handoff.note").into()),
                        helper_text: Some(cx.tr("handoff.note_help").into()),
                        multiline: true,
                        bind: screen.private_note,
                        semantics_identifier: "handoff.private-note".to_string(),
                    ),
                    Button(
                        child: Text(cx.tr("handoff.copy")),
                        key: "copy-reference",
                        disabled: state.pending.is_some(),
                        on_press: reduce { state::copy_reference(state, cx); },
                    ).semantics_identifier("handoff.copy"),
                    if let Some(operation) = state.pending {
                        Spinner(
                            motion: Some(SpinnerMotion::Default),
                            label: cx.tr(match operation {
                                state::Operation::Copy => "handoff.copying",
                                state::Operation::Paste => "handoff.pasting",
                            }),
                        )
                    } else {
                        Text(cx.tr(state.notice.key()))
                    },
                ]),
            ).padding_all(tokens.spacing.l),
        ),
    )
}
{"id":"fission-tabs-1","index":2,"label":"src/translations.rs","value":"src-translations-rs"}
use std::collections::HashMap;
use fission::prelude::*;

pub fn create_env() -> Env {
    let mut env = Env::default();
    env.locale = Locale::from("en-US");
    for (locale, source) in [
        ("en-US", include_str!("../i18n/en-US.yaml")),
        ("es-ES", include_str!("../i18n/es-ES.yaml")),
    ] {
        let messages: HashMap<String, String> =
            serde_yaml::from_str(source).expect("valid checked-in translations");
        env.i18n.add_bundle(TranslationBundle { locale: Locale::from(locale), messages });
    }
    env
}
{"id":"fission-tabs-1","index":3,"label":"i18n/en-US.yaml","value":"i18n-en-us-yaml"}
handoff.title: "Hand off a work-order reference"
handoff.context: "Choose the reference you intend to share. Copy excludes the private note, but the reference itself may still be sensitive."
handoff.reference: "Work-order reference"
handoff.format: "WO- followed by 1 to 12 digits."
handoff.note: "Private note"
handoff.note_help: "This note stays in this screen's memory. Copy never includes it; this example does not save or encrypt it."
handoff.copy: "Copy reference"
handoff.paste: "Paste reference"
handoff.copying: "Copying the reference…"
handoff.pasting: "Reading the clipboard…"
handoff.ready: "Clipboard access starts only when you choose an action."
handoff.copied: "Reference copied. Private note excluded."
handoff.pasted: "Reference pasted. Review it before using it."
handoff.invalid: "The reference must be WO- followed by 1 to 12 digits. Existing fields were preserved."
handoff.empty: "There is no text to paste. Existing fields were preserved."
handoff.unsupported: "This host does not support the requested clipboard operation."
handoff.denied: "Clipboard access was not allowed. Check the browser or operating-system access policy."
handoff.failed: "The clipboard operation failed. Your fields have not been cleared."
{"id":"fission-tabs-1","index":4,"label":"i18n/es-ES.yaml","value":"i18n-es-es-yaml"}
handoff.title: "Compartir una referencia de orden"
handoff.context: "Elige la referencia que quieres compartir. Copiar excluye la nota privada, pero la propia referencia también puede ser sensible."
handoff.reference: "Referencia de la orden"
handoff.format: "WO- seguido de 1 a 12 dígitos."
handoff.note: "Nota privada"
handoff.note_help: "Esta nota permanece en la memoria de esta pantalla. Copiar nunca la incluye; este ejemplo no la guarda ni la cifra."
handoff.copy: "Copiar referencia"
handoff.paste: "Pegar referencia"
handoff.copying: "Copiando la referencia…"
handoff.pasting: "Leyendo el portapapeles…"
handoff.ready: "El acceso al portapapeles solo empieza cuando eliges una acción."
handoff.copied: "Referencia copiada. Nota privada excluida."
handoff.pasted: "Referencia pegada. Revísala antes de usarla."
handoff.invalid: "La referencia debe ser WO- seguido de 1 a 12 dígitos. Se conservaron los campos."
handoff.empty: "No hay texto que pegar. Se conservaron los campos."
handoff.unsupported: "Este host no admite la operación de portapapeles solicitada."
handoff.denied: "No se permitió el acceso. Revisa la política del navegador o del sistema operativo."
handoff.failed: "La operación falló. No se han borrado tus campos."
{"id":"fission-tabs-1","index":5,"label":"src/lib.rs","value":"src-lib-rs"}
pub mod app;
mod state;
mod translations;

use app::HandoffScreen;
use state::ClipboardState;
use fission::prelude::*;

#[cfg(not(any(target_arch = "wasm32", target_os = "android", target_os = "ios")))]
pub fn run_desktop() -> anyhow::Result<()> {
    DesktopApp::<ClipboardState, _>::new(HandoffScreen::new())
        .with_env(translations::create_env())
        .run()
}
#[cfg(any(target_os = "android", target_os = "ios"))]
fn mobile_app() -> MobileApp<ClipboardState, HandoffScreen> {
    let app = MobileApp::<ClipboardState, _>::new(HandoffScreen::new())
        .with_env(translations::create_env());
    #[cfg(all(target_os = "android", debug_assertions))]
    let app = app.with_test_control_port(48761);
    app
}
#[cfg(any(target_os = "android", target_os = "ios"))]
pub fn run_mobile() -> anyhow::Result<()> { mobile_app().run() }

#[cfg(target_os = "android")]
#[no_mangle]
fn android_main(app_handle: AndroidApp) {
    let _ = mobile_app().run_with_android_app(app_handle);
}
#[cfg(target_arch = "wasm32")]
#[wasm_bindgen::prelude::wasm_bindgen(start)]
pub fn run_web() -> Result<(), wasm_bindgen::JsValue> {
    console_error_panic_hook::set_once();
    WebApp::<ClipboardState, _>::new(HandoffScreen::new())
        .with_env(translations::create_env())
        .run()
        .map_err(|error| wasm_bindgen::JsValue::from_str(&error.to_string()))
}
{"id":"fission-tabs-1","index":6,"label":"preview/lib.rs","value":"preview-lib-rs"}
mod app;
mod state;
mod translations;

use fission::prelude::*;
use wasm_bindgen::prelude::*;

#[wasm_bindgen(start)]
pub fn run() -> Result<(), JsValue> {
    console_error_panic_hook::set_once();
    WebApp::<state::ClipboardState, _>::new(app::HandoffScreen::new())
        .with_env(translations::create_env())
        .mount("#fission-web-mount")
        .run()
        .map_err(|error| JsValue::from_str(&error.to_string()))
}
{"id":"fission-tabs-1"}
Enter a reference such as WO-1048, add a different private note, then copy. Paste into a scratch text editor and check that only the reference appears. An empty or malformed reference should produce validation feedback without a host request.
The embedded app uses the browser clipboard provider, not a memory substitute. Browser policy, secure-context requirements or restrictions on an embedded page may reject access; that must produce an error, not a fabricated success.
Show the app preview
Hide the app preview

2. Paste without trusting the clipboard

Paste runs only after a deliberate user action. Do not read the clipboard during startup, on a timer or whenever a field receives focus. Apart from unnecessary access, that would replace the reference when the user had not asked for a change.
The successful callback receives ClipboardText from ctx.input. Only a matching reference reaches application state; empty text and other clipboard contents leave the current value alone. In particular, the error message does not echo rejected clipboard text, which might contain a password or another application's private data.
Replace src/state.rs with the version below. The screen adds a Paste action; native and Web entrypoints remain unchanged.
{"id":"fission-tabs-1","tabs":[{"index":0,"label":"src/state.rs","value":"src-state-rs"},{"index":1,"label":"src/app.rs","value":"src-app-rs"}]}
{"id":"fission-tabs-1","index":0,"label":"src/state.rs","value":"src-state-rs"}
use fission::prelude::*;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Operation { Copy, Paste }

#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum Notice {
    #[default]
    Ready,
    Copied,
    Pasted,
    InvalidReference,
    EmptyClipboard,
    Unsupported,
    Denied,
    Failed,
}

impl Notice {
    pub fn key(self) -> &'static str {
        match self {
            Self::Ready => "handoff.ready",
            Self::Copied => "handoff.copied",
            Self::Pasted => "handoff.pasted",
            Self::InvalidReference => "handoff.invalid",
            Self::EmptyClipboard => "handoff.empty",
            Self::Unsupported => "handoff.unsupported",
            Self::Denied => "handoff.denied",
            Self::Failed => "handoff.failed",
        }
    }
}

#[derive(Debug, Default)]
pub struct ClipboardState {
    pub reference: String,
    pub pending: Option<Operation>,
    pub notice: Notice,
}

impl GlobalState for ClipboardState {}

pub fn valid_reference(input: &str) -> bool {
    let Some(number) = input.strip_prefix("WO-") else { return false; };
    !number.is_empty()
        && number.len() <= 12
        && number.bytes().all(|byte| byte.is_ascii_digit())
}

pub fn copy_reference(state: &mut ClipboardState, ctx: &mut ReducerContext<ClipboardState>) {
    if state.pending.is_some() { return; }
    let reference = state.reference.trim().to_owned();
    if !valid_reference(&reference) {
        state.notice = Notice::InvalidReference;
        return;
    }
    state.pending = Some(Operation::Copy);
    state.notice = Notice::Ready;
    let ok = ctx.effects.bind(ReferenceCopied, reduce_with!(reference_copied));
    let err = ctx.effects.bind(ClipboardFailed, reduce_with!(clipboard_failed));
    ctx.effects.clipboard()
        .write_text(ClipboardWriteTextRequest { text: reference })
        .on_ok(ok)
        .on_err(err);
}

#[fission_reducer(ReferenceCopied)]
fn reference_copied(state: &mut ClipboardState, ctx: &mut ReducerContext<ClipboardState>) {
    if state.pending != Some(Operation::Copy) { return; }
    state.pending = None;
    state.notice = if ctx.input.capability_ok(WRITE_CLIPBOARD_TEXT).is_some() {
        Notice::Copied
    } else {
        Notice::Failed
    };
}

#[fission_reducer(ClipboardFailed)]
fn clipboard_failed(state: &mut ClipboardState, ctx: &mut ReducerContext<ClipboardState>) {
    let code = match state.pending.take() {
        Some(Operation::Copy) => ctx.input.capability_error(WRITE_CLIPBOARD_TEXT)
            .map(|error| error.code),
        Some(Operation::Paste) => ctx.input.capability_error(READ_CLIPBOARD_TEXT)
            .map(|error| error.code),
        None => return,
    };
    state.notice = match code.as_deref() {
        Some("unsupported") => Notice::Unsupported,
        Some("permission_denied") | Some("not_allowed") => Notice::Denied,
        _ => Notice::Failed,
    };
}

pub fn paste_reference(state: &mut ClipboardState, ctx: &mut ReducerContext<ClipboardState>) {
    if state.pending.is_some() { return; }
    state.pending = Some(Operation::Paste);
    state.notice = Notice::Ready;
    let ok = ctx.effects.bind(ReferencePasted, reduce_with!(reference_pasted));
    let err = ctx.effects.bind(ClipboardFailed, reduce_with!(clipboard_failed));
    ctx.effects.clipboard().read_text().on_ok(ok).on_err(err);
}

#[fission_reducer(ReferencePasted)]
fn reference_pasted(state: &mut ClipboardState, ctx: &mut ReducerContext<ClipboardState>) {
    if state.pending != Some(Operation::Paste) { return; }
    state.pending = None;
    match ctx.input.capability_ok(READ_CLIPBOARD_TEXT) {
        Some(ClipboardText { text: Some(text) }) if valid_reference(text.trim()) => {
            state.reference = text.trim().to_owned();
            state.notice = Notice::Pasted;
        }
        Some(ClipboardText { text: None }) => state.notice = Notice::EmptyClipboard,
        Some(ClipboardText { text: Some(text) }) if text.trim().is_empty() => {
            state.notice = Notice::EmptyClipboard;
        }
        Some(_) => state.notice = Notice::InvalidReference,
        None => state.notice = Notice::Failed,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn accepts_only_the_reference_format() {
        assert!(valid_reference("WO-1048"));
        for input in ["", "WO-", "WO-a", "WO-1\nprivate note", "WO-12", "WO-1234567890123"] {
            assert!(!valid_reference(input), "accepted invalid reference format");
        }
    }
}
{"id":"fission-tabs-1","index":1,"label":"src/app.rs","value":"src-app-rs"}
use fission::prelude::*;
use crate::state::{self, ClipboardState};

fission_component! {
    pub HandoffScreen<ClipboardState> {
        state { private_note: String = String::new() }
    }
    view(screen, state, cx) {
        let tokens = &cx.view.env().theme.tokens;
    } =>
    SafeArea(
        child: Scroll(
            child: Container(
                child: Column(gap: tokens.spacing.m, children: [
                    Text(cx.tr("handoff.title")).size(tokens.typography.heading2_size),
                    Text(cx.tr("handoff.context")),
                    TextInput(
                        label: Some(cx.tr("handoff.reference").into()),
                        helper_text: Some(cx.tr("handoff.format").into()),
                        enabled: state.pending.is_none(),
                        bind: state.reference,
                        semantics_identifier: "handoff.reference".to_string(),
                    ),
                    TextInput(
                        label: Some(cx.tr("handoff.note").into()),
                        helper_text: Some(cx.tr("handoff.note_help").into()),
                        multiline: true,
                        bind: screen.private_note,
                        semantics_identifier: "handoff.private-note".to_string(),
                    ),
                    Button(
                        child: Text(cx.tr("handoff.copy")),
                        key: "copy-reference",
                        disabled: state.pending.is_some(),
                        on_press: reduce { state::copy_reference(state, cx); },
                    ).semantics_identifier("handoff.copy"),
                    Button(
                        child: Text(cx.tr("handoff.paste")),
                        key: "paste-reference",
                        disabled: state.pending.is_some(),
                        on_press: reduce { state::paste_reference(state, cx); },
                    ).semantics_identifier("handoff.paste"),
                    if let Some(operation) = state.pending {
                        Spinner(
                            motion: Some(SpinnerMotion::Default),
                            label: cx.tr(match operation {
                                state::Operation::Copy => "handoff.copying",
                                state::Operation::Paste => "handoff.pasting",
                            }),
                        )
                    } else {
                        Text(cx.tr(state.notice.key()))
                    },
                ]),
            ).padding_all(tokens.spacing.l),
        ),
    )
}
{"id":"fission-tabs-1"}
Copy one reference, edit the field, then paste to restore the copied value. Next copy unrelated text in another application and paste again. The original reference and private note should remain unchanged, and the message should explain the rejected format without repeating the clipboard contents.
The copy acknowledgement says that the host accepted the write. It does not say that another application has read it, nor that the clipboard can keep it confidential.
Show the app preview
Hide the app preview

3. Check the Android host, not just the Web preview

Run the same screen on an emulator and a phone. Android and a browser have different clipboard policies; a successful browser request is not evidence for native behaviour.
cargo test
fission doctor android --project-dir .
fission devices --target android --project-dir .
fission run --target android --project-dir .
fission test --target android --project-dir .
fission build --target android --project-dir . --release
Check copy and paste with the app in the foreground, an empty clipboard, unrelated text, and the host's denied or unsupported result where available. Verify the private note never enters the copied text and remains editable after failure. Do not use real credentials or customer notes as test clipboard content.
The format test runs without a device. fission test checks the generated host can launch, but neither command proves the clipboard interaction works. Complete the manual cross-application checks before relying on the feature.
You now have explicit copy and paste actions, typed success and error handling, and a native entrypoint using the same code as the Web app. The privacy boundary is the request payload: only the chosen reference is sent. The local note is still only in memory, not saved or encrypted.

Current references