如何使用 flutter 查看应用程序使用情况

How to see apps usage using flutter

我正在尝试使用 flutter 开发一个应用程序,我想在移动设备上使用所有应用程序,我一直在为此目的搜索一些软件包,但没有找到用于此特定目的的东西。

您可以复制粘贴运行下面的完整代码
您可以使用包 https://pub.dev/packages/usage_stats
在工作演示中你可以看到 packageevent timestamp 历史,然后你可以做总结
第 1 步:AndroidManifest.xml,添加 xmlns:toolsandroid.permission.PACKAGE_USAGE_STATS

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="your package name" xmlns:tools="http://schemas.android.com/tools">

<uses-permission
    android:name="android.permission.PACKAGE_USAGE_STATS"
    tools:ignore="ProtectedPermissions" />

第 2 步:Permit usage access,请参阅左侧的工作演示图片

工作演示

完整代码

import 'package:flutter/material.dart';
import 'dart:async';
import 'package:usage_stats/usage_stats.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  List<EventUsageInfo> events = [];

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      initUsage();
    });
  }

  Future<void> initUsage() async {
    UsageStats.grantUsagePermission();
    DateTime endDate = new DateTime.now();
    DateTime startDate = DateTime(2020, 1, 1, 0, 0, 0);

    List<EventUsageInfo> queryEvents =
        await UsageStats.queryEvents(startDate, endDate);

    this.setState(() {
      events = queryEvents.reversed.toList();
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text("Usage Stats"),
        ),
        body: Container(
            child: ListView.separated(
                itemBuilder: (context, index) {
                  return ListTile(
                    title: Text(events[index].packageName),
                    subtitle: Text(
                        "Last time used: ${DateTime.fromMillisecondsSinceEpoch(int.parse(events[index].timeStamp)).toIso8601String()}"),
                    trailing: Text(events[index].eventType),
                  );
                },
                separatorBuilder: (context, index) => Divider(),
                itemCount: events.length)),
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            initUsage();
          },
          child: Icon(
            Icons.refresh,
          ),
          mini: true,
        ),
      ),
    );
  }
}