Use Android volume control from Fission

Read the actual Android media volume before offering a deliberate adjustment. Display the level the host returns, not an assumed local percentage.
Android

What you will build

Inspect and adjust the shared media stream while respecting Android's quantised levels, mute state and changes made outside the app.
Represent the initial media level as unknown until the provider replies
Serialize reads and deliberate small adjustments through effects
Decode and display the returned level rather than calculate an unconfirmed result
Treat the stored level as a snapshot and leave other streams and notification policy alone

Treat system volume as a shared setting

System volume is not an application preference. Changing it can affect another app, and another app or the hardware buttons can change it again. That means a value in component state is only a snapshot, not the authority for the device's current audio level.
Here, the user first reads the media stream, then explicitly chooses a small adjustment. The screen displays the level returned by Android rather than calculating a result and pretending the system accepted it. It does not play audio, change notification policy or force a muted device to become audible.
Start from a new project (optional)

Create the Android project

cargo install cargo-fission
fission init android-use-android-volume-control-from-fission
cd android-use-android-volume-control-from-fission
fission add-target android --project-dir .
fission add-capability volume-control --project-dir .
cargo add serde_yaml
Keep the generated src/main.rs. The shared library below replaces the starter app on native targets as well as Web. It uses the default host, not an in-memory volume provider.

Run the finished example

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

1. Read the actual stream before showing a level

The initial value is unknown. Do not display zero or a made-up percentage whilst waiting for the device. The reducer marks the operation pending, requests GET_VOLUME_LEVEL, and its callback reads the typed response from the reducer context.
Both read and adjust helpers are defined here so the result and error handling have one authority. This first screen exposes only the read operation.
{"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 Pending { Read, Adjust }

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VolumeIssue { Unsupported, Denied, Failed }

impl VolumeIssue {
    pub fn key(self) -> &'static str {
        match self {
            Self::Unsupported => "volume.unsupported",
            Self::Denied => "volume.denied",
            Self::Failed => "volume.failed",
        }
    }
}

#[derive(Debug, Default)]
pub struct VolumeState {
    pub confirmed: Option<VolumeLevel>,
    pub pending: Option<Pending>,
    pub issue: Option<VolumeIssue>,
}

impl GlobalState for VolumeState {}

pub fn read_level(state: &mut VolumeState, ctx: &mut ReducerContext<VolumeState>) {
    if state.pending.is_some() { return; }
    state.pending = Some(Pending::Read);
    state.issue = None;
    let ok = ctx.effects.bind(VolumeRead, reduce_with!(volume_read));
    let err = ctx.effects.bind(VolumeFailed, reduce_with!(volume_failed));
    ctx.effects.volume().get_level(VolumeStream::Media).on_ok(ok).on_err(err);
}

pub fn adjust_level(
    state: &mut VolumeState,
    ctx: &mut ReducerContext<VolumeState>,
    direction: VolumeAdjustDirection,
) {
    if state.pending.is_some() || state.confirmed.is_none() { return; }
    state.pending = Some(Pending::Adjust);
    state.issue = None;
    let ok = ctx.effects.bind(VolumeAdjusted, reduce_with!(volume_adjusted));
    let err = ctx.effects.bind(VolumeFailed, reduce_with!(volume_failed));
    ctx.effects.volume().adjust_level(VolumeAdjustRequest {
        stream: VolumeStream::Media,
        direction,
        step: 5,
    }).on_ok(ok).on_err(err);
}

fn accept_level(state: &mut VolumeState, response: Option<VolumeLevel>) {
    match response {
        Some(level) if level.stream == VolumeStream::Media && level.level <= 100 => {
            state.confirmed = Some(level);
            state.issue = None;
        }
        _ => state.issue = Some(VolumeIssue::Failed),
    }
}

#[fission_reducer(VolumeRead)]
fn volume_read(state: &mut VolumeState, ctx: &mut ReducerContext<VolumeState>) {
    if state.pending != Some(Pending::Read) { return; }
    state.pending = None;
    accept_level(state, ctx.input.capability_ok(GET_VOLUME_LEVEL));
}

#[fission_reducer(VolumeAdjusted)]
fn volume_adjusted(state: &mut VolumeState, ctx: &mut ReducerContext<VolumeState>) {
    if state.pending != Some(Pending::Adjust) { return; }
    state.pending = None;
    accept_level(state, ctx.input.capability_ok(ADJUST_VOLUME_LEVEL));
}

#[fission_reducer(VolumeFailed)]
fn volume_failed(state: &mut VolumeState, ctx: &mut ReducerContext<VolumeState>) {
    let code = match state.pending.take() {
        Some(Pending::Read) => ctx.input.capability_error(GET_VOLUME_LEVEL).map(|error| error.code),
        Some(Pending::Adjust) => ctx.input.capability_error(ADJUST_VOLUME_LEVEL).map(|error| error.code),
        None => return,
    };
    state.issue = Some(match code.as_deref() {
        Some("unsupported") => VolumeIssue::Unsupported,
        Some("permission_denied") => VolumeIssue::Denied,
        _ => VolumeIssue::Failed,
    });
}

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

    #[test]
    fn invalid_response_does_not_replace_the_last_confirmed_media_level() {
        let mut state = VolumeState::default();
        accept_level(&mut state, Some(VolumeLevel {
            stream: VolumeStream::Media, level: 40, muted: false,
        }));
        accept_level(&mut state, Some(VolumeLevel {
            stream: VolumeStream::Alarm, level: 80, muted: false,
        }));
        assert_eq!(state.confirmed.as_ref().unwrap().level, 40);
        assert_eq!(state.issue, Some(VolumeIssue::Failed));
        accept_level(&mut state, None);
        assert_eq!(state.confirmed.as_ref().unwrap().level, 40);
    }
}
{"id":"fission-tabs-1","index":1,"label":"src/app.rs","value":"src-app-rs"}
use fission::prelude::*;
use crate::state::{self, VolumeState};

fission_component! {
    pub VolumeScreen<VolumeState> {}
    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("volume.title")).size(tokens.typography.heading2_size),
                    Text(cx.tr("volume.context")),
                    Button(
                        child: Text(cx.tr("volume.read")),
                        key: "read-media-volume",
                        disabled: state.pending.is_some(),
                        on_press: reduce { state::read_level(state, cx); },
                    ).semantics_identifier("volume.read"),
                    if let Some(level) = &state.confirmed {
                        Column(gap: tokens.spacing.s, children: [
                            Text(cx.tr("volume.last_confirmed").replace("{level}", &level.level.to_string())),
                            Text(cx.tr(if level.muted { "volume.muted" } else { "volume.not_muted" })),
                            Text(cx.tr("volume.snapshot_help")),
                        ])
                    } else {
                        Text(cx.tr("volume.not_read"))
                    },
                    if let Some(pending) = state.pending {
                        Spinner(
                            motion: Some(SpinnerMotion::Default),
                            label: cx.tr(match pending {
                                state::Pending::Read => "volume.reading",
                                state::Pending::Adjust => "volume.adjusting",
                            }),
                        )
                    },
                    if let Some(issue) = state.issue {
                        Text(cx.tr(issue.key())).color(tokens.colors.error)
                    },
                ]),
            ).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"}
volume.title: "Media volume"
volume.context: "Read the device's media volume before choosing whether to change it. This screen does not play audio."
volume.read: "Read current media volume"
volume.not_read: "No device volume has been read."
volume.last_confirmed: "Last confirmed media volume: {level}%"
volume.muted: "The last response reported this stream muted."
volume.not_muted: "The last response reported this stream not muted."
volume.snapshot_help: "Other apps and the hardware buttons can change volume. Read it again to refresh this snapshot."
volume.change_warning: "These actions change the device's shared media volume, not just this app's playback."
volume.lower: "Lower media volume"
volume.raise: "Raise media volume"
volume.reading: "Reading media volume…"
volume.adjusting: "Changing media volume…"
volume.unsupported: "This host does not support system volume control. Use the device's own volume controls."
volume.denied: "The system did not allow the operation. Use the device's own controls or check its policy."
volume.failed: "The operation failed. Any displayed level is the last confirmed value; read it again before relying on it."
{"id":"fission-tabs-1","index":4,"label":"i18n/es-ES.yaml","value":"i18n-es-es-yaml"}
volume.title: "Volumen multimedia"
volume.context: "Lee el volumen multimedia del dispositivo antes de decidir si lo cambias. Esta pantalla no reproduce audio."
volume.read: "Leer el volumen multimedia actual"
volume.not_read: "Todavía no se ha leído el volumen del dispositivo."
volume.last_confirmed: "Último volumen multimedia confirmado: {level}%"
volume.muted: "La última respuesta indicó que este canal estaba silenciado."
volume.not_muted: "La última respuesta indicó que este canal no estaba silenciado."
volume.snapshot_help: "Otras aplicaciones y los botones físicos pueden cambiar el volumen. Léelo otra vez para actualizar este valor."
volume.change_warning: "Estas acciones cambian el volumen multimedia compartido del dispositivo, no solo el de esta aplicación."
volume.lower: "Bajar el volumen multimedia"
volume.raise: "Subir el volumen multimedia"
volume.reading: "Leyendo el volumen multimedia…"
volume.adjusting: "Cambiando el volumen multimedia…"
volume.unsupported: "Este host no admite el control del volumen del sistema. Usa los controles del dispositivo."
volume.denied: "El sistema no permitió la operación. Usa los controles del dispositivo o revisa su política."
volume.failed: "La operación falló. El nivel mostrado es el último confirmado; vuelve a leerlo antes de confiar en él."
{"id":"fission-tabs-1","index":5,"label":"src/lib.rs","value":"src-lib-rs"}
pub mod app;
mod state;
mod translations;

use app::VolumeScreen;
use state::VolumeState;
use fission::prelude::*;

#[cfg(not(any(target_arch = "wasm32", target_os = "android", target_os = "ios")))]
pub fn run_desktop() -> anyhow::Result<()> {
    DesktopApp::<VolumeState, _>::new(VolumeScreen)
        .with_env(translations::create_env())
        .run()
}
#[cfg(any(target_os = "android", target_os = "ios"))]
fn mobile_app() -> MobileApp<VolumeState, VolumeScreen> {
    let app = MobileApp::<VolumeState, _>::new(VolumeScreen)
        .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::<VolumeState, _>::new(VolumeScreen)
        .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::VolumeState, _>::new(app::VolumeScreen)
        .with_env(translations::create_env())
        .mount("#fission-web-mount")
        .run()
        .map_err(|error| JsValue::from_str(&error.to_string()))
}
{"id":"fission-tabs-1"}
Choose Read current media volume. On Android, compare the response with the device's media control, including its muted state. In the default Web host, unsupported volume control is an expected visible result; the preview does not invent a browser or system volume level.
The callback also rejects a missing response or the wrong stream. The previous confirmed value remains available as a labelled snapshot, not a new successful reading.
Show the app preview
Hide the app preview

2. Apply a deliberate change and display the returned value

A local slider that immediately displays its requested position can imply success before the system has done anything. For this shared device setting, use explicit actions and update the confirmed value only from the host's result.
The request below asks for a five-percentage-point adjustment to the media stream. Android exposes discrete hardware steps, so the returned percentage may differ from that request or remain unchanged. Repeatedly adding five to the displayed value would hide that difference.
{"id":"fission-tabs-1","tabs":[{"index":0,"label":"src/app.rs","value":"src-app-rs"}]}
{"id":"fission-tabs-1","index":0,"label":"src/app.rs","value":"src-app-rs"}
use fission::prelude::*;
use crate::state::{self, VolumeState};

fission_component! {
    pub VolumeScreen<VolumeState> {}
    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("volume.title")).size(tokens.typography.heading2_size),
                    Text(cx.tr("volume.context")),
                    Button(
                        child: Text(cx.tr("volume.read")),
                        key: "read-media-volume",
                        disabled: state.pending.is_some(),
                        on_press: reduce { state::read_level(state, cx); },
                    ).semantics_identifier("volume.read"),
                    if let Some(level) = &state.confirmed {
                        Column(gap: tokens.spacing.s, children: [
                            Text(cx.tr("volume.last_confirmed").replace("{level}", &level.level.to_string())),
                            Text(cx.tr(if level.muted { "volume.muted" } else { "volume.not_muted" })),
                            Text(cx.tr("volume.snapshot_help")),
                        ])
                    } else {
                        Text(cx.tr("volume.not_read"))
                    },
                    Text(cx.tr("volume.change_warning")),
                    Wrap(spacing: tokens.spacing.s, children: [
                        Button(
                            child: Text(cx.tr("volume.lower")),
                            key: "lower-media-volume",
                            disabled: state.pending.is_some()
                                || state.confirmed.as_ref().map(|level| level.level == 0).unwrap_or(true),
                            on_press: reduce {
                                state::adjust_level(state, cx, VolumeAdjustDirection::Down);
                            },
                        ).semantics_identifier("volume.lower"),
                        Button(
                            child: Text(cx.tr("volume.raise")),
                            key: "raise-media-volume",
                            disabled: state.pending.is_some()
                                || state.confirmed.as_ref().map(|level| level.level == 100).unwrap_or(true),
                            on_press: reduce {
                                state::adjust_level(state, cx, VolumeAdjustDirection::Up);
                            },
                        ).semantics_identifier("volume.raise"),
                    ]),
                    if let Some(pending) = state.pending {
                        Spinner(
                            motion: Some(SpinnerMotion::Default),
                            label: cx.tr(match pending {
                                state::Pending::Read => "volume.reading",
                                state::Pending::Adjust => "volume.adjusting",
                            }),
                        )
                    },
                    if let Some(issue) = state.issue {
                        Text(cx.tr(issue.key())).color(tokens.colors.error)
                    },
                ]),
            ).padding_all(tokens.spacing.l),
        ),
    )
}
{"id":"fission-tabs-1"}
Read the level, then lower it once and inspect the returned value. Raise it again only if you intend to change the shared setting. At the bounds, the corresponding action should be unavailable.
Change volume with the hardware buttons and then choose Read again. The new response should replace the earlier snapshot. The screen does not claim to subscribe to system volume changes.
Show the app preview
Hide the app preview

3. Check the device's limits and recovery path

cargo test
fission doctor android --project-dir .
fission run --target android --project-dir .
fission test --target android --project-dir .
fission build --target android --project-dir . --release
adb devices -l
fission run --target android --device <adb-serial> --project-dir .
Use a phone for the final checks. Read before and after one adjustment, test a bound, and observe mute and audio-route changes. Restore the user's intended level with the normal device controls; do not automatically restore a stale snapshot when the app closes, since the user may have changed it elsewhere.
An unsupported or failed operation should preserve the last confirmed display and offer the device controls as the recovery path. A failed request is not proof that the system setting stayed unchanged: part of a host operation may have completed before an error was reported.
cargo test checks the response-validation rule. fission test checks host startup, and the release build checks packaging. None of those checks establishes actual device volume behaviour or audibility.
The app now separates requested work from confirmed host state. Reading is explicit, adjustment is explicit, pending work is visible, and the same shared screen handles unsupported hosts honestly.

Current references