package com.appkystudio.appusagetracker;
import android.app.AppOpsManager;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.Intent;
import android.provider.Settings;
import com.google.appinventor.components.annotations.*;
import com.google.appinventor.components.common.ComponentCategory;
import com.google.appinventor.components.runtime.*;
import java.util.Calendar;
import java.util.List;
@DesignerComponent(
version = 1,
description = "Tracks app usage time using Usage Access permission. Use it to reward users based on time spent in apps like YouTube or Facebook.",
category = ComponentCategory.EXTENSION,
nonVisible = true,
iconName = ""
)
@SimpleObject(external = true)
@UsesPermissions(permissionNames = "android.permission.PACKAGE_USAGE_STATS")
@UsesLibraries(libraries = "")
public class AppUsageTracker extends AndroidNonvisibleComponent {
private final Context context;
public AppUsageTracker(ComponentContainer container) {
super(container.$form());
this.context = container.$context();
}
@SimpleFunction(description = "Check if Usage Access permission is granted.")
public boolean IsUsageAccessGranted() {
try {
AppOpsManager appOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
int mode = appOps.checkOpNoThrow("android:get_usage_stats",
android.os.Process.myUid(), context.getPackageName());
return mode == AppOpsManager.MODE_ALLOWED;
} catch (Exception e) {
return false;
}
}
@SimpleFunction(description = "Open Usage Access settings screen for the user to grant permission.")
public void OpenUsageAccessSettings() {
Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
@SimpleFunction(description = "Returns total time (in seconds) that the given package has been in foreground today.")
public int GetAppUsageTime(String packageName) {
UsageStatsManager usm = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
long endTime = System.currentTimeMillis();
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
long startTime = calendar.getTimeInMillis();
List<UsageStats> usageStatsList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, startTime, endTime);
for (UsageStats usageStats : usageStatsList) {
if (usageStats.getPackageName().equals(packageName)) {
return (int)(usageStats.getTotalTimeInForeground() / 1000);
}
}
return 0;
}
}
please check and reply my code is good or not if not than what chnange need to do.
help.