I build an application that co开发者_运维技巧llects data about the battery. In order to collect this data I need my application to run on the background in order to be able to collect this data. How can I do it?
You need to change your activities into Service
if you're against using a service for whatever reason you can have it thread off, then get the data when the user calls the application to the front.
you can use the onStart, onPause, onResume functions as well as making the application single instance so when you run it again, it mearly pulls it up from memory (assuming Android doesn't kill it for some reason).
You can use ongoing notification to prevent it from being killed in the background and moveTaskToBack.
But as pentium10 says, the intended way to handle background processes is through a service which gathers the data you are looking for, then when the activity comes back to the front, it gets the data from the service and displays it.
- @Override public int onStartCommand(Intent intent, int flags, int
startId) {
handleCommand(intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY; }
精彩评论