When I print infoList in the following code, the program prints an empty list. But I opened so many system application in my phone. I expect that it would return the name of application and the time that is spent on each of those application.
import 'package:flutter/material.dart';
import 'package:app_usage/app_usage.dart';
import 'package:permission_handler/permission_handler.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() {
return _MyAppState();
}
}
class _MyAppState extends State<MyApp> {
List<AppUsageInfo> _infos = [];
@override
void initState() {
super.initState();
}
void getUsageStats() async {
try {
DateTime endDate = DateTime.now();
DateTime startDate = endDate.subtract(const Duration(days: 10));
List<AppUsageInfo> infoList = await AppUsage().getAppUsage(startDate, endDate);
print(infoList);
setState(() => _infos = infoList);
for (var info in infoList) {
// print(info.toString());
}
} on AppUsageException catch (exception) {
print(exception);
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Screen Timing'),
backgroundColor: Colors.green,
),
body: ListView.builder(
itemCount: _infos.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(_infos[index].appName),
trailing: Text(_infos[index].usage.toString()));
}),
floatingActionButton: FloatingActionButton(
onPressed: getUsageStats, child: Icon(Icons.file_download)),
),
);
}
}
The
app_usagepackage requires you to allow usage access for your application. To do this, make sure you have added the required permission in yourAndroidManifest.xmlas stated in the package description, so the start of your manifest file should look like this:At the first time the
getAppUsagefunction is triggered, the system may open the "App with usage access" settings, and you should find your app and set "Permit usage access" to on.If you are currently running the app, make sure to stop and run the app again as hot reloading won't work.