如何将输出至Logcat的printUsageStats方法改写为输出至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
setTextcall inrunOnUiThread(for Activities):runOnUiThread(() -> { if (statsTextView != null) { statsTextView.setText(statsBuilder.toString()); } }); - Scrollable Content: Add
android:scrollbars="vertical"to your TextView in XML, and thesetMovementMethodline 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

