Skip to content
This repository has been archived by the owner on Dec 5, 2024. It is now read-only.

Commit

Permalink
Fix: Fixed the usage time
Browse files Browse the repository at this point in the history
Closes #571
  • Loading branch information
CreativeCodeCat committed Nov 23, 2024
1 parent 2744035 commit 34a3e55
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 54 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.github.droidworksstudio.mlauncher.helper

import android.annotation.SuppressLint
import android.app.usage.UsageStatsManager
import android.content.Context
import android.content.pm.ApplicationInfo
Expand All @@ -20,81 +21,83 @@ object AppDetailsHelper {
}
}

@SuppressLint("NewApi")
fun getUsageStats(context: Context, packageName: String): Long {
// Set calendar to midnight of today (start of the day)
val calendar = Calendar.getInstance().apply {
set(Calendar.HOUR_OF_DAY, 0)
set(Calendar.MINUTE, 0)
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
}

val startTime = calendar.timeInMillis
val endTime = System.currentTimeMillis()
val startTime = calendar.timeInMillis // Midnight today
val endTime = System.currentTimeMillis() // Current time

// Get UsageStatsManager system service
val usageStatsManager = context.getSystemService(Context.USAGE_STATS_SERVICE) as? UsageStatsManager

// Query usage stats for the specific time range (startTime to endTime)
val usageStatsList = usageStatsManager?.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, startTime, endTime)

val usageStatsManager =
context.getSystemService(Context.USAGE_STATS_SERVICE) as? UsageStatsManager
val usageStatsList =
usageStatsManager?.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, startTime, endTime)
var totalUsageTime: Long = 0

// Iterate through the stats to get the specific package usage
usageStatsList?.let { statsList ->
for (usageStats in statsList) {
if (usageStats.packageName == packageName) {
totalUsageTime = usageStats.totalTimeInForeground
// Use totalTimeInForeground for actual usage time
if (usageStats.totalTimeVisible > 0) {
totalUsageTime += usageStats.totalTimeVisible
}
}
}
}

return totalUsageTime
}


@SuppressLint("NewApi")
fun getTotalScreenTime(context: Context): Long {
// Get the current time
// Get the start of the current day (midnight)
val calendar = Calendar.getInstance().apply {
set(Calendar.HOUR_OF_DAY, 0) // Set to the start of the day
set(Calendar.HOUR_OF_DAY, 0)
set(Calendar.MINUTE, 0)
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
}

// Define the start and end time range for stats
val start = calendar.timeInMillis
val end = System.currentTimeMillis()
val startTime = calendar.timeInMillis
val endTime = System.currentTimeMillis()

// Get the UsageStatsManager system service
val usm = context.getSystemService(Context.USAGE_STATS_SERVICE) as UsageStatsManager

// Query usage stats for the given time range
val usageStatsList = usm.queryUsageStats(UsageStatsManager.INTERVAL_BEST, start, end)
// Query usage stats for today (from midnight to current time)
val usageStatsList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, startTime, endTime)

if (usageStatsList.isEmpty()) {
Log.w("getTotalScreenTime", "No usage stats available.")
return 0L
}

// Sort the stats based on last used time in descending order
usageStatsList.sortWith(compareByDescending { it.lastTimeUsed })

// Calculate the total screen time for all apps (excluding the current app)
var totalScreenTime: Long = 0
val packageName = context.packageName

for (usageStats in usageStatsList) {
if (usageStats.packageName != packageName) {
if (usageStats.totalTimeInForeground.toInt() != 0) {
Log.d(
"usageStatsList",
"App: ${usageStats.packageName}, Foreground time: ${usageStats.totalTimeInForeground}"
)
totalScreenTime += usageStats.totalTimeInForeground
// Only consider apps with non-zero foreground time
if (usageStats.totalTimeVisible > 0) {
totalScreenTime += usageStats.totalTimeVisible
}
}
}

return totalScreenTime
}


fun formatMillisToHMS(millis: Long): String {
val hours = millis / (1000 * 60 * 60)
val minutes = (millis % (1000 * 60 * 60)) / (1000 * 60)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,11 @@ import android.os.Bundle
import android.os.Vibrator
import android.util.Log
import android.view.DragEvent
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.ScrollView
import android.widget.TextView
import androidx.annotation.RequiresApi
Expand Down Expand Up @@ -90,14 +91,6 @@ class FavoriteFragment : Fragment() {
@RequiresApi(Build.VERSION_CODES.Q)
private fun initObservers() {
with(viewModel) {
homeAppsAlignment.observe(viewLifecycleOwner) { (gravity, onBottom) ->
val horizontalAlignment = if (onBottom) Gravity.BOTTOM else Gravity.CENTER_VERTICAL
binding.homeAppsLayout.gravity = gravity.value() or horizontalAlignment

binding.homeAppsLayout.children.forEach { view ->
(view as TextView).gravity = gravity.value()
}
}
homeAppsCount.observe(viewLifecycleOwner) {
updateAppCount(it)
}
Expand Down Expand Up @@ -193,25 +186,48 @@ class FavoriteFragment : Fragment() {
} else if (diff < 0) {
val prefixDrawable: Drawable? =
context?.let { ContextCompat.getDrawable(it, R.drawable.ic_prefix_drawable) }
// add all missing apps to list

// Add all missing apps to the list
for (i in oldAppsNum until newAppsNum) {
// Create a LinearLayout with horizontal orientation
val horizontalLayout = LinearLayout(context).apply {
orientation = LinearLayout.HORIZONTAL
layoutParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
)
}

// Create the TextView
val view = layoutInflater.inflate(R.layout.home_app_button, null) as TextView
view.apply {
val appLabel =
prefs.getHomeAppModel(i).activityLabel.ifEmpty { getString(R.string.app) }
textSize = prefs.appSize.toFloat()
id = i
text = " $appLabel"
setCompoundDrawablesWithIntrinsicBounds(prefixDrawable, null, null, null)
text = appLabel

if (!prefs.extendHomeAppsArea) {
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
layoutParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
)
}
}

// Create the ImageView for the drawable
val imageView = ImageView(context).apply {
layoutParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
)
prefixDrawable?.let { setImageDrawable(it) }
}

// Add padding and other styling
val padding: Int = prefs.textPaddingSize
view.setPadding(0, padding, 0, padding)

binding.pageName.text = getString(R.string.favorite_apps)
binding.pageName.textSize = prefs.appSize * 1.5f

Expand All @@ -220,25 +236,32 @@ class FavoriteFragment : Fragment() {
view.setTextColor(fontColor)
}

binding.homeAppsLayout.addView(view)
// Add the TextView and ImageView to the horizontal layout
horizontalLayout.addView(view)
horizontalLayout.addView(imageView)

// Add the horizontal layout to the home apps layout
binding.homeAppsLayout.addView(horizontalLayout)
}
}

for (i in 0 until newAppsNum) {
val view = binding.homeAppsLayout.getChildAt(i) as TextView
view.setOnDragListener { v, event ->
handleDragEvent(event, v as TextView)
}
view.setOnLongClickListener { v ->
val dragData = ClipData.newPlainText("", "")
val shadowBuilder = View.DragShadowBuilder(v)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
v.startDragAndDrop(dragData, shadowBuilder, v, 0)
} else {
@Suppress("DEPRECATION")
v.startDrag(dragData, shadowBuilder, v, 0)
(0 until newAppsNum).forEach { i ->
val view = layoutInflater.inflate(R.layout.home_app_button, null) as TextView
view.apply {
setOnDragListener { v, event ->
handleDragEvent(event, v as TextView)
}
setOnLongClickListener { v ->
val dragData = ClipData.newPlainText("", "")
val shadowBuilder = View.DragShadowBuilder(v)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
v.startDragAndDrop(dragData, shadowBuilder, v, 0)
} else {
@Suppress("DEPRECATION")
v.startDrag(dragData, shadowBuilder, v, 0)
}
true
}
true
}
}

Expand Down

0 comments on commit 34a3e55

Please sign in to comment.