use liveactivity::{
Accessibility, ActivityState, Alert, AndroidContent, AndroidOptions, AndroidPlacement,
AndroidPresentation, AndroidVisibility, Bound, EndInput, EndPolicy, Event, FeatureSupport,
Layout, LayoutEndInput, LayoutPush, LayoutSnapshot, LayoutStartInput, LayoutUpdateInput,
LiveActivity, LiveActivityBackend, NotificationAction, PermissionKind, PermissionState,
PresentationStyle, ProgressSegment, ProgressStyle, PublicVersion, Result, StartInput,
TimerStyle, Transition, UpdateInput,
activitykit::{
layout::{button, link, progress, text, vstack},
values,
},
android::LiveUpdateBackend,
liveupdate::{Driver, NextCheck, Timer},
};
fn connect(backend: impl LiveActivityBackend) -> Result<LiveActivity> {
LiveActivity::builder()
.backend(backend) .event_sink(|event: Event| {
if let Some(id) = over(&event) {
println!("{id} is over");
}
match event {
Event::Action(tap) => println!("tapped {} on {}", tap.action_id, tap.activity_id),
Event::State(change) => println!("{} is {:?}", change.activity_id, change.state),
Event::PushToken(token) => println!("send {} to the server", token.token),
_ => {}
}
})
.build()
}
fn over(event: &Event) -> Option<&str> {
match event {
Event::State(change)
if matches!(
change.state,
ActivityState::Ended | ActivityState::Dismissed
) =>
{
Some(&change.activity_id)
}
_ => None,
}
}
async fn progress_and_timer(live: &LiveActivity) -> Result<()> {
let order = live
.start(StartInput::progress(
"order:42",
"Order 42",
"Preparing",
0.1,
))
.await?;
live.update(UpdateInput::progress(
&order.id,
1,
"Order 42",
"On the way",
0.6,
))
.await?;
live.end(EndInput::new(&order.id)).await?;
let (started_at, ends_at) = (1_800_000_000_000, 1_800_000_180_000);
let tea = live
.start(StartInput::timer(
"tea:1", "Tea", "Steeping", started_at, ends_at,
))
.await?;
live.end(EndInput::immediate(&tea.id)).await?;
Ok(())
}
async fn layout(live: &LiveActivity) -> Result<String> {
let layout = Layout {
lock_screen: vstack([
text(Bound::key("title")),
progress("done"),
button("track", text("Track")),
]),
island: None,
background: None,
keyline: None,
url: None,
};
let values = values! { "title" => "Delivery 7", "done" => 0.4 }.into_inner();
let start = LayoutStartInput::new("delivery:7", layout, LayoutSnapshot::new(0, values));
let record = live.start_layout(start).await?;
let values = values! { "title" => "Delivery 7", "done" => 0.9 }.into_inner();
let update = LayoutUpdateInput::new(&record.id, LayoutSnapshot::new(1, values));
live.update_layout(update).await?;
Ok(record.id)
}
async fn links_accessibility_and_motion(live: &LiveActivity) -> Result<()> {
let layout = Layout {
lock_screen: vstack([
progress("done").accessibility(
Accessibility::new()
.label("Delivery progress")
.value(Bound::key("percent")),
),
text(Bound::key("address")).sensitive(),
text("At the door")
.when("arrived")
.transition(Transition::MoveTop),
link("myapp://delivery/9/map", text("Map")),
]),
island: None,
background: None,
keyline: None,
url: Some("myapp://delivery/9".into()),
};
let values = values! {
"done" => 0.4, "percent" => "40 percent", "address" => "12 Hill Street", "arrived" => false,
}
.into_inner();
let start = LayoutStartInput::new("delivery:9", layout, LayoutSnapshot::new(0, values));
let record = live.start_layout(start).await?;
println!("left out: {:?}", record.degraded_features);
Ok(())
}
async fn alert_and_relevance(live: &LiveActivity, id: &str) -> Result<()> {
let values = values! { "title" => "Delivery 7", "done" => 1.0 }.into_inner();
let mut snapshot = LayoutSnapshot::new(2, values);
snapshot.relevance = Some(90.0);
let mut update = LayoutUpdateInput::new(id, snapshot);
update.alert = Some(Alert::new("Delivery arrived", "Your parcel is at the door"));
let record = live.update_layout(update).await?;
if record.degraded_features.iter().any(|left| left == "alert") {
println!("this platform updated without the alert");
}
Ok(())
}
async fn android_content(live: &LiveActivity, id: &str) -> Result<()> {
let styles = live.capabilities().await?.android_presentation;
let segmented = styles.is_some_and(|styles| styles.progress_style);
let values = values! { "title" => "Delivery 7", "done" => 0.6 }.into_inner();
let mut snapshot = LayoutSnapshot::new(3, values);
snapshot.android = Some(AndroidContent {
title: "Delivery 7".into(),
status: "2 stops away".into(),
presentation: AndroidPresentation {
short_critical_text: Some("8 min".into()),
..AndroidPresentation::new(PresentationStyle::Progress(ProgressStyle {
progress: 60,
indeterminate: false,
styled_by_progress: true,
segments: if segmented {
vec![segment(60, Some(0xFF00_7F00)), segment(40, None)]
} else {
vec![segment(100, None)]
},
points: Vec::new(),
start_icon: None,
end_icon: None,
tracker_icon: None,
}))
},
});
live.update_layout(LayoutUpdateInput::new(id, snapshot))
.await?;
Ok(())
}
async fn android_links_and_extras(live: &LiveActivity, id: &str, ends_at: u64) -> Result<()> {
let capabilities = live.capabilities().await?;
let offered = capabilities.android_presentation.unwrap_or_default();
let values = values! { "title" => "Delivery 7", "done" => 0.8 }.into_inner();
let mut snapshot = LayoutSnapshot::new(4, values);
snapshot.android = Some(AndroidContent {
title: "Delivery 7".into(),
status: "At the door in 4 minutes".into(),
presentation: AndroidPresentation {
open_url: offered.links.then(|| "myapp://delivery/7".into()),
actions: if offered.links {
vec![NotificationAction {
open_url: Some("myapp://delivery/7/map".into()),
..NotificationAction::new("map", "Map")
}]
} else {
Vec::new()
},
chronometer: offered.chronometer.then(|| TimerStyle {
timer: Timer {
started_at: ends_at - 240_000,
ends_at,
},
counts_down: true,
}),
public_version: offered.public_version.then(|| PublicVersion {
title: "Delivery".into(),
status: "On the way".into(),
}),
sub_text: offered.branding.then(|| "Mochi Express".into()),
..AndroidPresentation::new(PresentationStyle::Standard)
},
});
live.update_layout(LayoutUpdateInput::new(id, snapshot))
.await?;
Ok(())
}
async fn android_options(live: &LiveActivity, mut start: LayoutStartInput) -> Result<()> {
let capabilities = live.capabilities().await?;
let offered = capabilities.android_presentation.unwrap_or_default();
let mut options = AndroidOptions::new(AndroidVisibility::Private);
options.public_version = Some(PublicVersion {
title: "Delivery".into(),
status: "On the way".into(),
});
if offered.foreground_placement {
options.placement = Some(AndroidPlacement::Foreground);
}
start.android = Some(options);
let record = live.start_layout(start).await?;
if record
.degraded_features
.iter()
.any(|left| left == "publicVersion")
{
println!("this device shows no public version");
}
Ok(())
}
fn segment(length: u32, color: Option<u32>) -> ProgressSegment {
ProgressSegment {
length,
id: None,
color,
semantic_style: None,
}
}
async fn image(live: &LiveActivity, png: &[u8]) -> Result<()> {
live.write_image("badge.png", png).await
}
async fn pushes(live: &LiveActivity, mut start: LayoutStartInput) -> Result<()> {
start.push = Some(LayoutPush::Token);
live.start_layout(start).await?;
for held in live.push_tokens().await?.activities {
println!("{} has the token {}", held.activity_id, held.token);
}
Ok(())
}
async fn capabilities_and_permissions(live: &LiveActivity) -> Result<()> {
let capabilities = live.capabilities().await?;
if capabilities.layout != FeatureSupport::Supported {
println!(
"{}: progress and timer activities only",
capabilities.platform
);
}
let permissions = live.permissions().await?;
if permissions.notifications == PermissionState::Prompt {
live.request_permissions(PermissionKind::Notifications)
.await?;
}
Ok(())
}
#[allow(dead_code)]
fn when_to_ask_again<D: Driver + 'static>(backend: &LiveUpdateBackend<D>) -> Result<()> {
match backend.next_check()? {
NextCheck::Now => {
backend.pump_events()?;
}
NextCheck::Soon => {}
NextCheck::At(_time) => {}
NextCheck::Never => {}
}
Ok(())
}
async fn end_and_sync(live: &LiveActivity, id: &str) -> Result<()> {
live.end_layout(LayoutEndInput::new(id)).await?;
live.sync_events().await
}
async fn end_with_a_last_content(live: &LiveActivity, id: &str, until: u64) -> Result<()> {
let values = values! { "title" => "Delivered", "done" => 1.0 }.into_inner();
let mut end = LayoutEndInput::new(id);
end.policy = EndPolicy::After { at: until };
end.snapshot = Some(LayoutSnapshot::new(5, values));
live.end_layout(end).await?;
Ok(())
}
fn code<T>(result: Result<T>) -> String {
result.map_or_else(|error| error.code, |_| "ok".to_owned())
}
fn main() -> Result<()> {
let memory = std::sync::Arc::new(liveactivity::testkit::MemoryBackend::new());
let live = connect(memory.clone())?;
liveactivity::wait(async {
println!(
"progress and timer: {}",
code(progress_and_timer(&live).await)
);
let order = live
.start(StartInput::progress(
"order:43",
"Order 43",
"Preparing",
0.2,
))
.await?;
memory.tap(&order.id, "track")?;
println!(
"capabilities: {}",
code(capabilities_and_permissions(&live).await)
);
println!("layout: {}", code(layout(&live).await));
println!(
"links, accessibility and motion: {}",
code(links_accessibility_and_motion(&live).await)
);
println!(
"alert and relevance: {}",
code(alert_and_relevance(&live, "id").await)
);
println!(
"android content: {}",
code(android_content(&live, "id").await)
);
let in_four_minutes = 1_800_000_240_000;
println!(
"android links and extras: {}",
code(android_links_and_extras(&live, "id", in_four_minutes).await)
);
println!("image: {}", code(image(&live, b"not a png").await));
let start = LayoutStartInput::new(
"delivery:8",
Layout {
lock_screen: text("Delivery 8"),
island: None,
background: None,
keyline: None,
url: None,
},
LayoutSnapshot::new(0, Default::default()),
);
println!(
"android options: {}",
code(android_options(&live, start.clone()).await)
);
println!("pushes: {}", code(pushes(&live, start).await));
println!("end and sync: {}", code(end_and_sync(&live, "id").await));
println!(
"end with a last content: {}",
code(end_with_a_last_content(&live, "id", in_four_minutes).await)
);
Ok(())
})
}