Why I am getting empty list when I am using app usage package in flutter?

68 Views Asked by At

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)),
      ),
    );
  }
}
1

There are 1 best solutions below

0
Dhafin Rayhan On

The app_usage package requires you to allow usage access for your application. To do this, make sure you have added the required permission in your AndroidManifest.xml as stated in the package description, so the start of your manifest file should look like this:

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

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

At the first time the getAppUsage function 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.