I am trying to fetch all the application names that are currently running in my android phone, and display them in the logcat. This is done in the background, so I am using the service
class. My code is as following:
public class Timer extends Service {
public Timer() {
}
@Override
public void onCreate() {
if(!needPermissionForBlocking(getApplicationContext())) {
startActivity(new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS));
}
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
UsageStatsManager usm = (UsageStatsManager)this.getSystemService(Context.USAGE_STATS_SERVICE);
long time = System.currentTimeMillis();
List<UsageStats> appList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 10000*10000, time);
if (appList.size() == 0) {
Log.d("Executed app", "######### NO APP FOUND ##########" );
}
else {
SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>();
for (UsageStats usageStats : appList) {
Log.d("Executed app", "usage stats executed : " +usageStats.getPackageName() + "\t\t ID: ");
mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
if (!mySortedMap.isEmpty()) {
String currentApp = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
Log.d("app",currentApp);
}
}
}
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
public static boolean needPermissionForBlocking(Context context){
try {
PackageManager packageManager = context.getPackageManager();
ApplicationInfo applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), 0);
AppOpsManager appOpsManager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
int mode = appOpsManager.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, applicationInfo.uid, applicationInfo.packageName);
return (mode != AppOpsManager.MODE_ALLOWED);
} catch (PackageManager.NameNotFoundException e) {
return true;
}
}
}
But no matter how many apps I run, the code shows the log everytime
"Executed app", "######### NO APP FOUND ##########"
I have also added the following permission in my manifest:
<uses-permission
android:name="android.permission.PACKAGE_USAGE_STATS"
tools:ignore="ProtectedPermissions" />
What am I doing wrong here? Why can't it fetch the running apps on my device?