之前做的悬浮窗在5.0的手机上不好用了,经过研究发现5.0上面的获取顶层应用的方式和5.0以下的应用不同,主要使用UsageStatsManager 来获取顶层应用,但是使用UsageStatsManager 之前必须手动的在设置->安全->有权查看应用使用情况 中打开开关. 下面分享下验证开关打开的方式及验证是有存在 “有权查看应用使用情况”的模块,因为有一些5.0的rom,不包含“有权查看应用使用情况”模块。
1.是否存在“有权查看应用使用情况” 模块
/**
* has Apps with usage access module
* @return
*/
@SuppressLint("NewApi")
private boolean hasModule() {
PackageManager packageManager = getApplicationContext().getPackageManager();
Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
List<ResolveInfo> list = packageManager.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
- 用户是否已经打开开关
/**
* the user enabled my application
* @return
*/
@SuppressLint("NewApi")
private boolean hasEnable(){
long ts = System.currentTimeMillis();
UsageStatsManager usageStatsManager=(UsageStatsManager)getApplicationContext().getSystemService("usagestats");
List<UsageStats> queryUsageStats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST,0, ts);
if (queryUsageStats == null || queryUsageStats.isEmpty()) {
return false;
}
return true;
}
3.引导用户打开
Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
startActivity(intent);