Reputation: 37
I have referred a few forums and discussions and wrote this code to find the top running activity and start an intent for another activity.
package com.example.neondude.ietproject;
import android.app.Service;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.Toast;
import java.util.List;
import java.util.SortedMap;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TreeMap;
public class BlockService extends Service
{
private static Timer timer = new Timer();
public String pActivity="";
public IBinder onBind(Intent arg0)
{
return null;
}
public void onCreate()
{
super.onCreate();
startService();
}
private void startService()
{
timer.scheduleAtFixedRate(new mainTask(), 0, 500);
}
private class mainTask extends TimerTask
{
public void run()
{
toastHandler.sendEmptyMessage(0);
}
}
public void onDestroy()
{
super.onDestroy();
Toast.makeText(this, "Service Stopped ...", Toast.LENGTH_SHORT).show();
}
private final Handler toastHandler = new Handler()
{
@Override
public void handleMessage(Message msg) {
String topPackageName = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
UsageStatsManager mUsageStatsManager = (UsageStatsManager) getSystemService(USAGE_STATS_SERVICE);
long time = System.currentTimeMillis();
//We get usage stats for the last 10 seconds
List<UsageStats> stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 10, time);
// Sort the stats by the last time used
if (stats != null) {
SortedMap<Long, UsageStats> mySortedMap = new TreeMap<>();
for (UsageStats usageStats : stats) {
mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
}
if (!mySortedMap.isEmpty()) {
topPackageName = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
}
}
}
if (!topPackageName.equals("com.example.neondude.MainActivity") || !topPackageName.equals("com.example.neondude.BlockService")) {
Intent i = new Intent(BlockService.this, BlockActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
Toast.makeText(BlockService.this, pActivity, Toast.LENGTH_LONG).show();
}
}
};
}
}
but I am having a problem when using the USAGE_STATS_SERVICE
UsageStatsManager mUsageStatsManager = (UsageStatsManager) getSystemService(USAGE_STATS_SERVICE);
Error: cannot resolve symbol USAGE_STATS_SERVICE
I have also tried using:
UsageStatsManager mUsageStatsManager = (UsageStatsManager) getSystemService("usagestats");
this also shows the same error
Please tell me how to correct this error.
Upvotes: 1
Views: 571
Reputation: 1007359
Make sure that your compileSdkVersion
is set to 22 or higher, as that is the API level where USAGE_STATS_SERVICE
was added.
Upvotes: 1