My app has a background Service. In the Service I need to detect and log all app launches. For example: whether the user opens Facebook or Google+ or Twitter (any app) - I want a receiver in my Service to catch it for me to perform an action.
The only way I have been able to come up to do this - is to have a Timer running in the onCreate() function of my Service. My concern is that this 1 second timer may drain battery.
Things I have tried:
(1) My Service code with the TimerTask. My trigger action code will be placed inside the "run()" function of the TimerTask.
public class KillService extends Service {
ActivityManager mActivityManager;
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onDestroy() {
unregisterReceiver(receiver);
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
@Override
public void onCreate() {
super.onCreate();
Timer timer = new Timer();
TimerTask refresher = new TimerTask() {
public void run() {
//PLACING MY TRIGGER ACTION HERE
};
};
//TIMER RUNS EVERY 1 SECOND
timer.scheduleAtFixedRate(refresher, 1000,1000);
}
}
(2) Reviewed Available Broadcast Actions I reviewed the broadcast_actions.txt that comes in the SDK Folder (sdk\platforms\android-19\data), but I did not find any Intent that will be appropriate for this use case. Link to file
All I want is to know when any App Activity is started (i.e. in the Foreground) so that I dont have to continually check with Timer (afraid that it may drain battery)
Perhaps my answer in this question might help you. Android how to know an app has been started and range apps priority according the starting times
Place that code inside your background service.
Based on the package name of the activity in the foreground, you can detect that app name by checking all the apps on the phone and matching it with the app that has the same package name.
Since you want a continuous check, you could use an AsyncTask()
, and in the doInBackground()
function, just keep getting the list of running activities in each iteration, like I have suggested in that link, and the first item in the taskInfo list will have the activity/app in the foreground. You can also provide another button in your app which on click you stop this , by keeping a bool variable in shared preferences (which you poll for in the while condition in doInBackGround()
function of the AsyncTask()
).
I have done something similar in the past, and it worked for me.