我正在尝试获取当前在我的 android 手机中运行的所有应用程序名称,并将它们显示在 logcat 中。这是在后台完成的,所以我正在使用service
该类。我的代码如下:
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;
}
}
}
但是无论我运行多少应用程序,代码每次都会显示日志
“已执行的应用程序”、“######### 未找到应用程序##########”
我还在清单中添加了以下权限:
<uses-permission
android:name="android.permission.PACKAGE_USAGE_STATS"
tools:ignore="ProtectedPermissions" />
我在这里做错了什么?为什么它无法获取我设备上正在运行的应用程序?