You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将输出至Logcat的printUsageStats方法改写为输出至TextView?

How to Redirect Usage Stats Output from Logcat to a TextView

Got it, let's adjust your code to display the usage stats in a TextView instead of logging them to Logcat. Here's a straightforward, practical approach:

Step 1: Tweak the Method for UI Compatibility

First, we’ll update your printUsageStats method to accept a TextView as a parameter (since we need to update its content). I’d recommend dropping the static modifier if this method lives in an Activity/Fragment—static methods can complicate UI operations, and keeping it non-static makes it easier to work with your app's UI components.

Step 2: Build Output Efficiently with StringBuilder

Instead of logging each entry one by one, we’ll use a StringBuilder to concatenate all usage stats into a single string. This is way more efficient than repeated string concatenation with +, especially if your usage stats list is long.

Step 3: Update the TextView (and Handle Threading!)

Finally, we’ll set the built string to the TextView. Critical reminder: All UI operations must run on the main thread, so we’ll make sure that’s accounted for.

Modified Code Example

// Remove "static" if this is inside an Activity/Fragment
public void printUsageStats(List<UsageStats> usageStatsList, Context context, TextView statsTextView) {
    StringBuilder statsBuilder = new StringBuilder();
    PackageManager pm = context.getPackageManager();

    for (UsageStats u : usageStatsList) {
        try {
            PackageInfo foregroundAppPackageInfo = pm.getPackageInfo(u.getPackageName(), 0);
            // Get human-readable app name from PackageInfo
            String appName = foregroundAppPackageInfo.applicationInfo.loadLabel(pm).toString();
            
            // Customize this format to match how you want stats displayed
            statsBuilder.append("App Name: ").append(appName)
                       .append("\nPackage: ").append(u.getPackageName())
                       .append("\nTotal Foreground Time: ").append(u.getTotalTimeInForeground())
                       .append("\n-------------------------\n");
        } catch (PackageManager.NameNotFoundException e) {
            // Handle cases where the app package can't be found
            statsBuilder.append("Unknown App (Package: ").append(u.getPackageName())
                       .append(")\nError: ").append(e.getMessage())
                       .append("\n-------------------------\n");
            e.printStackTrace(); // Keep this for debugging if needed
        }
    }

    // Update TextView - ensure this runs on the main thread
    if (statsTextView != null) {
        // If calling from a background thread, wrap this in runOnUiThread()
        statsTextView.setText(statsBuilder.toString());
        // Optional: Make TextView scrollable for long content
        statsTextView.setMovementMethod(new ScrollingMovementMethod());
    }
}

Key Tips for Smooth Execution:

  • Main Thread Safety: If you’re calling this method from a background thread (like a coroutine or AsyncTask), wrap the setText call in runOnUiThread (for Activities):
    runOnUiThread(() -> {
        if (statsTextView != null) {
            statsTextView.setText(statsBuilder.toString());
        }
    });
    
  • Scrollable Content: Add android:scrollbars="vertical" to your TextView in XML, and the setMovementMethod line will let users scroll through long stats lists.
  • Formatting Flexibility: Adjust the statsBuilder.append() lines to tweak how stats are displayed—for example, convert raw milliseconds to minutes/hours for readability.

内容的提问来源于stack exchange,提问作者Mikkel Rosholm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:25:11