Kotlin实现按日期统计App使用时长

学习笔记作者:admin日期:2025-05-27点击:24

摘要:基于Kotlin语言,实现了一个函数getAppUsedTime,用于从数据库中按指定日期统计各App的使用时长及次数,并以JSON格式返回。

Kotlin实现按日期统计App使用时长

代码实现

import org.json.JSONArray
import org.json.JSONObject

// 获取指定日期的app使用时长
fun getAppUsedTime(riqi: String): JSONObject {
    try {
        val usageMap = mutableMapOf() // 存储每个app的使用时长(毫秒)
        val db = dbHelper.readableDatabase

        // 1. 获取指定日期的app切换记录
        val switchRecordsSql = """
            SELECT
                TITLE as appname,
                sum(cast(LINK as real)) as usedTime,
                count(*) as usedCount
            FROM shijian
            WHERE LEI='APP使用记录' 
              AND ID LIKE '$riqi%'
              AND TITLE is not null 
              AND LINK is not null
            GROUP BY TITLE
            ORDER BY sum(cast(LINK as real)) DESC
        """.trimIndent()

        // 执行 SQL 查询
        val cursor = db.rawQuery(switchRecordsSql, null)

        // 2. 解析查询结果
        val resultArray = JSONArray()
        if (cursor != null && cursor.moveToFirst()) {
            do {
                val appName = cursor.getString(cursor.getColumnIndexOrThrow("appname"))
                val usedTime = cursor.getLong(cursor.getColumnIndexOrThrow("usedTime"))
                val usedCount = cursor.getInt(cursor.getColumnIndexOrThrow("usedCount"))

                // 将数据存储到 JSON 对象中
                val appUsageJson = JSONObject()
                appUsageJson.put("appName", appName)
                appUsageJson.put("usedTime", usedTime)
                appUsageJson.put("usedCount", usedCount)

                // 添加到结果数组
                resultArray.put(appUsageJson)

                // 更新使用时长映射
                usageMap[appName] = usedTime
            } while (cursor.moveToNext())
        }

        // 关闭游标
        cursor?.close()

        // 3. 返回结果
        return JSONObject().put("data", resultArray)
    } catch (e: Exception) {
        e.printStackTrace()
        // 如果发生异常,返回空数据
        return JSONObject().put("data", JSONArray())
    }
}

解决方案

      该函数通过构造SQL语句查询指定日期内App的使用记录,提取出每个App的使用时长与次数,并以JSON格式返回。

      关键点在于正确构建SQL语句、处理Cursor结果集、以及异常处理。

注意事项

  • SQL注入防护:应采用参数化查询替代字符串拼接方式。
  • 资源管理:确保Cursor关闭,防止资源泄漏。
  • 线程安全性:如需多线程调用,请确保数据库操作同步。

关键词

  1. Kotlin
  2. SQLite
  3. JSON
  4. App使用统计
  5. 日期筛选

上一篇      下一篇