Firstly, I'm not looking for time spent on a given application. There is already "an app for that", com.android.settings/.UsageStats
, and a good deal of supporting code in the AOSP frameworks/base/services/java/com/android/server/am/UsageStatsService.java
, etc.
The code that I've examined so far does not seem to record elapsed time spent on particular <activity>
s. I have thought to get this information two ways, but feel there must be something cleaner and simpler, that leverages more existing code. The ideas have been:
- Instrument the base
Activity
classonPause()
andonResume()
, to hack in a timestamp, and log the info some place (probably a SQLite database.) - Instrument the
Context
class, to make note wheneverstartActivity()
and friends are called.
So what do you think -- anything better than those options? Thank you in advance!
So what do you think -- anything better than those options?
Anything is better than #2, which requires custom firmware.
#1 is your only option within the SDK for API Level 13 on down AFAIK.
API Level 14 (a.k.a., Android 4.0) added in Application.ActivityLifecycleCallbacks
, which you can register via registerActivityLifecycleCallbacks()
called on your Application
(e.g., getApplicationContext()
). I haven't used these yet, but it would appear that you can arrange for a single listener to be notified of activities coming and going, avoiding forcing you to extend some common base Activity
class with your desired logging.
来源:https://stackoverflow.com/questions/9778990/android-get-time-spent-per-activity