简体   繁体   English

如何使我的android应用在后台运行?

[英]How can I make my android app run on the background?

I build an application that collects 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? 我该怎么做?

您需要将您的活动更改为“ 服务”

 - @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; }

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). 您可以使用onStart,onPause,onResume函数以及将应用程序设为单个实例,因此当您再次运行它时,它会从内存中拉出它(假设Android由于某种原因没有将其杀死)。

You can use ongoing notification to prevent it from being killed in the background and moveTaskToBack. 您可以使用正在进行的通知来防止它在后台和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. 但是正如pentium10所说,处理后台进程的预期方式是通过服务收集所需的数据,然后当活动回到最前面时,它将从服务中获取数据并显示出来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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