Crates.io | tauri-plugin-app-events |
lib.rs | tauri-plugin-app-events |
version | |
source | src |
created_at | 2024-10-28 11:26:22.701467+00 |
updated_at | 2025-02-17 19:24:19.312522+00 |
description | A plugin for tauri@v2 to listen some events on iOS and Android. |
homepage | |
repository | https://github.com/wtto00/tauri-plugin-app-events.git |
max_upload_size | |
id | 1425506 |
Cargo.toml error: | TOML parse error at line 26, column 1 | 26 | autolib = false | ^^^^^^^ unknown field `autolib`, expected one of `name`, `version`, `edition`, `authors`, `description`, `readme`, `license`, `repository`, `homepage`, `documentation`, `build`, `resolver`, `links`, `default-run`, `default_dash_run`, `rust-version`, `rust_dash_version`, `rust_version`, `license-file`, `license_dash_file`, `license_file`, `licenseFile`, `license_capital_file`, `forced-target`, `forced_dash_target`, `autobins`, `autotests`, `autoexamples`, `autobenches`, `publish`, `metadata`, `keywords`, `categories`, `exclude`, `include` |
size | 0 |
A plugin for tauri@v2 to listen some events on iOS and Android.
Platform | Supported |
---|---|
Linux | ❌ |
Windows | ❌ |
macOS | ❌ |
Android | ✅ |
iOS | ✅ |
For desktop platforms, please use @tauri-apps/api/event or the JavaScript method keydown event.
Install the app-events
plugin to get started.
Run the following command in the src-tauri
folder to add the plugin to the project’s dependencies in Cargo.toml
:
cargo add tauri-plugin-app-events@0.2 --target 'cfg(any(target_os = "android", target_os = "ios"))'
Modify lib.rs
to initialize the plugin:
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
tauri::Builder::default()
.setup(|app| {
+ #[cfg(mobile)]
+ app.handle().plugin(tauri_plugin_app_events::init())?;
Ok(())
})
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
Modify src-tauri/capabilities/mobile.json
to Allow the frontend to execute the registerListener
command.
{
"$schema": "../gen/schemas/mobile-schema.json",
"identifier": "mobile",
"description": "Capability for the main window on mobile platform",
"windows": ["main"],
"permissions": [
+ "app-events:default"
],
"platforms": ["android", "iOS"]
}
If you want to support key event listeners on the Android platform, you'll need to modify the MainActivity.kt
file located at src-tauri/gen/android/app/src/main/java/com/tauri/dev/MainActivity.kt
. The content should be updated as follows:
package com.tauri.dev
import android.view.KeyEvent
import android.webkit.WebView
class MainActivity : TauriActivity() {
private lateinit var wv: WebView
override fun onWebViewCreate(webView: WebView) {
wv = webView
}
private val keyEventMap = mapOf(
KeyEvent.KEYCODE_BACK to "back",
KeyEvent.KEYCODE_MENU to "menu",
KeyEvent.KEYCODE_SEARCH to "search",
KeyEvent.KEYCODE_VOLUME_DOWN to "volume_down",
KeyEvent.KEYCODE_VOLUME_UP to "volume_up"
)
override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
val jsCallbackName = keyEventMap[keyCode]
wv.evaluateJavascript(
"""
try {
window.__tauri_android_on_${if (jsCallbackName != null) "${jsCallbackName}_" else ""}key_down__(${if (jsCallbackName != null) "" else keyCode})
} catch (_) {
true
}
""".trimIndent()
) { result ->
run {
if (result != "false") {
super.onKeyDown(keyCode, event)
}
}
}
return true
}
}
Install the JavaScript Guest bindings using your preferred JavaScript package manager:
pnpm add tauri-plugin-app-events-api@0.2
Api | Android | iOS |
---|---|---|
onResume | ✅ | ✅ |
onPause | ✅ | ✅ |
onBackKeyDown | ✅ | ❌ |
onMenuKeyDown | ✅ | ❌ |
onSearchKeyDown | ✅ | ❌ |
onVolumeDownKeyDown | ✅ | ❌ |
onVolumeUpKeyDown | ✅ | ❌ |
onKeyDown | ✅ | ❌ |
import {
onResume,
onPause,
onBackKeyDown,
onMenuKeyDown,
onSearchKeyDown,
onVolumeDownKeyDown,
onVolumeUpKeyDown,
onKeyDown,
} from "tauri-plugin-app-events-api";
All listener APIs only support a single callback, so repeated calls will cause the previous listener to be overridden.
Therefore, if you want to cancel the listener, you can pass an empty parameter in functions like onResume()
.
In keydown event
listeners of Android, if the callback function returns false
, the default handling logic will be prevented. If it returns any other value or doesn't return anything, the default handling logic will continue.
The resume
event fires when the system pulls the application out from the background.
onResume(() => {
console.log("App resume");
});
tauri::Builder::default()
.invoke_handler(tauri::generate_handler![greet])
.setup(|app| {
#[cfg(mobile)]
{
let app_handle = app.handle();
app_handle.plugin(tauri_plugin_app_events::init())?;
let app_cloned = app_handle.clone();
app_handle
.app_events()
.set_resume_handler(Channel::new(move |_| {
// The app has returned to the foreground.
app_cloned.emit("js-log", "set_resume_handler")?;
Ok(())
}))?;
let app_cloned = app_handle.clone();
app_handle
.app_events()
.set_pause_handler(Channel::new(move |_| {
// The app has switched to the background.
app_cloned.emit("js-log", "set_pause_handler")?;
Ok(())
}))?;
}
Ok(())
})
.run(tauri::generate_context!())
.expect("error while running tauri application");
Note that executing
println!("some log")
in the handler callback in Rust will have no effect.
The pause
event fires when the system puts the application into the background, typically when the user switches to a different application.
onResume(() => {
console.log("App pause");
});
In Rust
, refer to the instructions mentioned above in onResume
.
The event fires when the user presses the back button on Android.
onBackKeyDown(() => {
console.log("Back key triggered");
return false;
});
The event fires when the user presses the menu button on Android.
onMenuKeyDown(() => {
console.log("Menu key triggered");
return false;
});
The event fires when the user presses the search button on Android.
onSearchKeyDown(() => {
console.log("Search key triggered");
return false;
});
The event fires when the user presses the volume down button on Android.
onVolumeDownKeyDown(() => {
console.log("Volume down key triggered");
return false;
});
The event fires when the user presses the volume up button on Android.
onVolumeUpKeyDown(() => {
console.log("Volume up key triggered");
return false;
});
If you want to listen for the events of pressing other buttons, you can use onKeyDown
. Note that this does not include the aforementioned button events.
onKeyDown((keyCode) => {
console.log(`Key ${keyCode} triggered`);
return false;
});
Regarding keyCode
, you can refer to the Android documentation.