Mah*_*esh 1 android usage-statistics usageevents
我想知道用户使用我的应用程序的时间。所以每当他打开我的应用程序时,我想知道时间,每当他关闭应用程序时,我想知道时间。当用户关闭应用程序时,我想将使用时间发送到服务器。我如何在 android 中跟踪使用时间?
我在下面提到的方式是一种非常有效的方式来获取用户在 android 中花费的总时间。实际上,我也使用这种方法来奖励我的用户花费的时间。首先,您需要一个自定义的ActivityLifecycleCallbacks,它负责在应用程序开始启动和停止时触发。您只需将ActivityLifecycleCallbacks注册到您的应用程序实例。这也将关心是否有任何用户暂停应用程序,因此您无需考虑它。自定义ActivityLifecycleCallbacks 类是 -
public class ApplicationTimeSpentTracker implements Application.ActivityLifecycleCallbacks {
private int activityReferences = 0;
private boolean isActivityChangingConfigurations = false;
private long startingTime;
private long stopTime;
/**startingTime is the UNIX timestamp (though I increased readability by converting into millisecond to second) your app is being foregrounded to the user and stopTime is when it is being backgrounded (Paused)*/
@Override
public void onActivityCreated(Activity activity, Bundle bundle) {
}
@Override
public void onActivityStarted(Activity activity) {
if (++activityReferences == 1 && !isActivityChangingConfigurations) {
// App enters foreground
startingTime=System.currentTimeMillis()/1000; //This is the starting time when the app began to start
}
}
@Override
public void onActivityResumed(Activity activity) {
}
@Override
public void onActivityPaused(Activity activity) {
}
@Override
public void onActivityStopped(Activity activity) {
isActivityChangingConfigurations = activity.isChangingConfigurations();
if (--activityReferences == 0 && !isActivityChangingConfigurations) {
// App enters background
stopTime = System.currentTimeMillis() / 1000;//This is the ending time when the app is stopped
long totalSpentTime= stopTime-startTime; //This is the total spent time of the app in foreground. Here you can post the data of total spending time to the server.
}
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
}
Run Code Online (Sandbox Code Playgroud)
最后,您需要像这样在MainActivity中将回调注册到您的应用程序实例-
activity.getApplication().registerActivityLifecycleCallbacks(new ApplicationTimeSpentTracker());
Run Code Online (Sandbox Code Playgroud)
如果您需要详细信息,这是我的帖子
| 归档时间: |
|
| 查看次数: |
3273 次 |
| 最近记录: |