安卓棒棒糖版本开始加强了安全性;有关更多细节,请参阅此文章:
getAppTask
您可以通过UsageStats类获取前台活动;首先,您必须在清单中添加此权限:
<uses-permission android:name="android.permission.PACKAGE_USAGE_STATS"
tools:ignore="ProtectedPermissions"/>
并且这个声明:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="your_application_package">
这将禁用警告,提示权限是系统级别的,不会授予第三方应用程序。设备用户可以通过“设置”应用程序授予权限。
因此,在您的MainActivity的onCreate()方法中,检查用户是否已授予此权限。
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
if(!hasPermission()){
startActivityForResult(
new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS),
Constant.MY_PERMISSIONS_REQUEST_PACKAGE_USAGE_STATS);
}
}
如果没有启用,请要求用户启用:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == Constant.MY_PERMISSIONS_REQUEST_PACKAGE_USAGE_STATS){
if (!hasPermission()){
startActivityForResult(
new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS),
Constant.MY_PERMISSIONS_REQUEST_PACKAGE_USAGE_STATS);
}
}
}
private boolean hasPermission() {
AppOpsManager appOps = (AppOpsManager)
getSystemService(Context.APP_OPS_SERVICE);
int mode = 0;
if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.KITKAT) {
mode = appOps.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS,
android.os.Process.myUid(), getPackageName());
}
return mode == AppOpsManager.MODE_ALLOWED;
}
最后,这里有一个片段可以放在后台服务中,它可以提供当前前台活动的包名:
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private String getUsageStatsForegroundActivityName() {
UsageStatsManager mUsageStatsManager = (UsageStatsManager) MyApplication.getInstance().getSystemService(Context.USAGE_STATS_SERVICE);
long endTime = System.currentTimeMillis();
long beginTime = endTime - 1000 * 60;
String topActivity = null;
List<UsageStats> stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, beginTime, endTime);
if (stats != null) {
SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>();
for (UsageStats usageStats : stats) {
mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
}
if (mySortedMap != null && !mySortedMap.isEmpty()) {
topActivity = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
logger.info("topActivity: " + topActivity);
}
}
if (topActivity != null)
return topActivity;
else
return Constant.ACTIVITY_NOT_FOUND;
}
Constant.MY_PERMISSIONS_REQUEST_PACKAGE_USAGE_STATS
。 - user3051460