Writing a Capacitor plugin and use of "context"

I’m trying to write a capacitor plugin following this explanation. The Plugin should make use of Androids usageStatsManager.

With the code further below, I’m getting the following error in Android Studio:

error: cannot find symbol UsageStatsManager usm = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
symbol: variable context
location: class echoPlugin

So it seems somehow I’m not using context correctly.

My code in echoPlugin.java:

package com.echo.capacitor;

import com.getcapacitor.JSObject;
import com.getcapacitor.Plugin;
import com.getcapacitor.PluginMethod;
import com.getcapacitor.annotation.CapacitorPlugin;
import android.content.Context;
import android.util.Log;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;

import java.util.Calendar;
import java.util.List;

@CapacitorPlugin(name = "echo")
public class echoPlugin extends Plugin {    

    @PluginMethod    
    public void getStats(Context call) {
        Log.i("Method: ", "getStats");           

        UsageStatsManager usm = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
        long now  = Calendar.getInstance().getTimeInMillis();       
        List<UsageStats> stats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, 0, now);

         JSObject ret = new JSObject();
         ret.put("my Stats",stats);

        call.resolve(ret);

 }
}

I have to add that I’m a complete Java beginner. I’m normally doing Apps with Vue+Ionic+Capacitor, but because there is no implementation of the UsageStatsManager in Capacitor I’m trying to find a way to make it work.

1 Like

Replace context.getSystemService with getContext().getSystemService

2 Likes