简体   繁体   中英

How much time user spend in certain activity of fragment?

I want to get the number of times that user spend in certain activity or fragment in my application and save it to my database. Is there any way?

Someone say use Firebase Google Analytic but I want to do it inside my app.

Try this Simple steps without any timer or service. I do this things for many of my applications. Hope this help you out.

1.) Declare two objects start, end on each activity which you want to add time to database. For Eg

long startTime;
long endTime;

2.) Now inside activity onCreate() do something like this.

startTime = System.currentTimeMillis();

3.) Now When you close the activity and move to another activity inside onDestroty() do something like this.

@Override
protected void onDestroy()
{
   endTime = System.currentTimeMillis();
   long timeSpend = endTime - startTime;
   // Insert timeSpend in databse.
   // you can also convert the timeSpend to hours, minutes, seconds.
   super.onDestroy();
}

You can also use the above code inside onStop() if you don't want to code inside onDestroy().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM