Android 抓取 App 使用时长大致分为4个步骤
1. 申明权限
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.xx.yy">
<uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" tools:ignore="ProtectedPermissions" />
</manifest>
2. 检查权限
因为该权限非常规权限,处理方式稍有不同
fun checkHasAppUsagePermission(context: Context?): Boolean {
var granted = false
if (context != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
try {
val appOps = context.getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager
val mode = appOps.checkOpNoThrow(
AppOpsManager.OPSTR_GET_USAGE_STATS,
Process.myUid(),
context.packageName
)
granted = if (mode == AppOpsManager.MODE_DEFAULT) {
val permissionUsage = "android.permission.PACKAGE_USAGE_STATS"
context.checkCallingOrSelfPermission(permissionUsage) == PackageManager.PERMISSION_GRANTED
} else {
mode == AppOpsManager.MODE_ALLOWED
}
} catch (e: Throwable) {
}
}
return granted
}
3. 打开权限
引导用户去设置页面打开权限
fun openPkgUsagePermission(context: Context?) {
if (context != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val intent = getIntent(context)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
try {
context.startActivity(intent)
} catch (e: Exception) {
e.printStackTrace()
}
}
}
4. 获取App使用时长
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
fun getPackageUsageStatsDatas(context: Context): List<UsageStats>? {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val calendar = Calendar.getInstance()
calendar.time = Date()
//完毕时刻
val endt = calendar.timeInMillis
//时刻间隔为两年
calendar.add(Calendar.DAY_OF_YEAR, -2)
//开端时刻
val statt = calendar.timeInMillis
val usageStatsManager =
context.getSystemService(Context.USAGE_STATS_SERVICE) as UsageStatsManager
var queryUsageStats: List<UsageStats>? = null
try {
queryUsageStats = usageStatsManager.queryUsageStats(
UsageStatsManager.INTERVAL_YEARLY,
statt,
endt
)
} catch (ignore: Throwable) {}
queryUsageStats
} else {
null
}
}