Skip to content

Commit

Permalink
基于binder的更快,更稳定的获取顶层软件pid实现
Browse files Browse the repository at this point in the history
  • Loading branch information
shadow3aaa committed Nov 24, 2023
1 parent d53ac79 commit 6d24f42
Showing 1 changed file with 31 additions and 16 deletions.
47 changes: 31 additions & 16 deletions fas-rs-fw/src/scheduler/topapp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,13 @@
* See the License for the specific language governing permissions and
* limitations under the License. */
use std::{
process::Command,
fs::{self, OpenOptions},
time::{Duration, Instant},
};

use binder::binder_impl::IBinderInternal;

const TOPAPP_TEMP: &str = "/dev/fas_rs_topapp_temp";
const REFRESH_TIME: Duration = Duration::from_secs(2);

pub struct TimedWatcher {
Expand All @@ -25,38 +28,50 @@ pub struct TimedWatcher {

impl TimedWatcher {
pub fn new() -> Self {
let cache = Self::get_top_pids().unwrap_or_default();
Self {
let cache = Vec::new();

let mut result = Self {
cache,
last_refresh: Instant::now(),
}
};

result.get_top_pids();
result
}

pub fn is_topapp(&mut self, pid: i32) -> bool {
if self.last_refresh.elapsed() > REFRESH_TIME {
self.cache = Self::get_top_pids().unwrap_or_default();
self.get_top_pids();
self.last_refresh = Instant::now();
}

self.cache.contains(&pid)
}

fn get_top_pids() -> Option<Vec<i32>> {
let dump = Command::new("dumpsys")
.args(["window", "visible-apps"])
.output()
.ok()?;
let dump = String::from_utf8_lossy(&dump.stdout).into_owned();
fn get_top_pids(&mut self) {
let temp = OpenOptions::new()
.write(true)
.truncate(true)
.create(true)
.open(TOPAPP_TEMP)
.unwrap();

Some(Self::parse_top_app(&dump))
}
let Some(mut service) = binder::get_service("window") else {
return;
};

if service.dump(&temp, &["visible-apps"]).is_err() {
return;
}

let dump = fs::read_to_string(TOPAPP_TEMP).unwrap();

fn parse_top_app(dump: &str) -> Vec<i32> {
dump.lines()
self.cache = dump
.lines()
.filter(|l| l.contains("Session{"))
.filter_map(|l| l.split_whitespace().nth(3))
.filter_map(|s| s.split(':').next())
.map(|p| p.trim().parse().unwrap())
.collect()
.collect();
}
}

0 comments on commit 6d24f42

Please sign in to comment.