Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List<UsageStats> return empty

I want to get diary use for all apps installed in phone, but always an empty list is returned. Below is the code i am using.

Here app.js from react-native call apps information from native code java

loadApps = async () => {
    await ReturnAppsInformations.getApps()
    .then(response => {
      console.log(response); // only [] <----
      this.setState({ apps });
    })
    .catch(error => {
      console.warn(error);
    });
}

Here is my simple native code to return array with data

UsageStatsManager manager = (UsageStatsManager) this.reactContext.getSystemService(this.reactContext.USAGE_STATS_SERVICE);
List<UsageStats> stats =manager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY,1729196, System.currentTimeMillis());
WritableArray list2 = Arguments.createArray();

for (int i = 0; i < stats.size(); i++) {
    UsageStats usageStats = stats.get(i);
    WritableMap appInfo2 = Arguments.createMap();

    appInfo2.putString("packageName", usageStats.getPackageName());
    appInfo2.putDouble("firsTimeStamp", usageStats.getFirstTimeStamp());
    appInfo2.putDouble("getTotalTimeInForeground", 
    usageStats.getTotalTimeInForeground());
    list2.pushMap(appInfo2);
}
promise.resolve(list2);

What am I doing wrong? This is my first app so I do not have much knowledge

  1. Updated as suggested by Julien, but still results in a empty array.

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
            package="com.returnappsinformations" 
            xmlns:tools="http://schemas.android.com/tools">
        <uses-permission
            android:name="android.permission.PACKAGE_USAGE_STATS"
            tools:ignore="ProtectedPermissions" />
    </manifest>
    

Ok, i found those gits about it...

https://github.com/mvincent7891/UsageStatsModule

https://github.com/shimatai/react-native-android-datausage

https://github.com/lucasferreira/react-native-android-permissions

Tonight im gonna to read them... But i belive, that resolve the problem to me!! Thanks for support!!!

like image 467
Camilo Melges Avatar asked Sep 06 '25 09:09

Camilo Melges


1 Answers

Have you asked and set the necessary permissions to use UsageStatsManager?

UsageStatsManager's documentation states that you need to declare android.permission.PACKAGE_USAGE_STATS in your Manifest and that it needs to be turned on in the Settings of your phone for your particular application.

EDIT:
Permission to add in your Manifest:

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

That special permission can't be granted through the normal permissions API of Android. So you'll need to redirect your users to the Settings page where they can grant it manually. You can open the right Settings screen via the Intent:

Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
like image 120
Julien Arzul Avatar answered Sep 09 '25 05:09

Julien Arzul