I need to be able to do this for pre-5.0 Android devices. Would anyone be able to assist me in how to get started doing this? I searched all over Stack Overflow for possible solutions and the most promising provided a lot of code from a working application, but after fixing some errors so that the app doesn't crash, when the service is run, only a blank white screen shows up and nothing else, so I decided to abandon it. Is there any available resource to help me accomplish this? Thanks!
Asked
Active
Viewed 961 times
-2
-
Asking for off-site resources is considered off-topic for Stack Overflow. If you want help with your prior attempt, feel free to post a separate question where you show your code and explain your symptoms. However, bear in mind that Android continually tightens its security, and so solutions that may have worked on older devices may be blocked on newer ones. – CommonsWare Jul 15 '15 at 18:49
1 Answers
1
To get the currently running app on pre-5.0, you can poll ActivityManager
:
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(Integer.MAX_VALUE);
ActivityManager.RunningTaskInfo task = tasks.get(0);
String pkg = task.topActivity.getPackageName();
You'll have to record this info how you want to measure time spent on an app.
Now you probably want to do this periodically, using a timer:
new Timer().schedule(new TimerTask() {
@Override
public void run() {
// Poll ActivityManager
}
}, 250, 250); // Runs every 250 ms.
A ScheduledExecutorService would be better by the way, but a Timer will do.
Now you want to create this in a service:
public class MyService extends Service {
@Override
public void onCreate() {
// Create TimerTask here
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
You have to register this service in your manifest:
<service android:name=".MyService" />
And finally, you can explicitly start it in your activity:
startService(new Intent(context, ServiceSystemControl.class));
That's all you need! You'll need to keep track of the top app and have some sort of running count of time spent on everything on the device.
To improve this, you can make the service register a persistant notification, so the system won't kill it when low on memory.

Anubian Noob
- 13,426
- 6
- 53
- 75