Help to extension

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.

Changes:

Return long instead of int

getTotalTimeInForeground() returns long milliseconds, and casting it to int could cause overflow if usage time is high (more than ~24 days)
:white_check_mark: Fix:
Change your method return type:

@SimpleFunction(description = "Returns total time (in seconds)...")
public long GetAppUsageTime(String packageName) {
    ...
    return usageStats.getTotalTimeInForeground() / 1000L;
}

i check short time in seconds i need i give user a task and i check user use app for 20 - 30 seconds .

Sure Can you please clarify what kind of extension you need help with

i share my extension code .

i just comform this good is good and follow google play policy.

i give some task to want user do or not
i want only data in seconds

But to follow Google Play policies, you MUST do these things:
Show a clear explanation to users before asking for usage access permission. Example:

“We need access to your app usage time so we can reward you based on how long you use certain apps. We do not share or sell this data

Avoid incentivized installs or actions, from your side

If you don’t do the above, your app could be rejected or removed from Google Play.

Technically, your code is good. you already compiled it?

1 Like

thanks bro. i do as your suggestion.

yes i make extension and test .

Make sure it works reliably across devices.

ok. i try
thanks