Android - 定期后台服务 - 建议 [英] Android - Periodic Background Service - Advice

查看:23
本文介绍了Android - 定期后台服务 - 建议的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个应用程序,它将有关其位置的信息中继到远程服务器.我打算通过向网络服务器发送一个简单的 HTTP 帖子来实现,一切都很简单.

I am working on an app that will relay information about its location to a remote server. I am intending to do it by doing a simple HTTP post to the web-server and all is simple and fine.

但根据规范,应用程序需要不时执行自身,例如每 30 分钟执行一次.独立于界面,意味着即使应用程序关闭它也需要运行.

But according to the spec, the app needs to execute itself from time to time, lets say once in every 30 mins. Be independent of the interface, meaning which it needs to run even if the app is closed.

我环顾四周,发现需要使用的是Android Services.我可以用什么来实现这样的系统.手机重启时服务(或其他机制)会重启吗?

I looked around and found out that Android Services is what needs to be used. What could I use to implement such a system. Will the service (or other mechanism) restart when the phone restarts?

提前致谢.

推荐答案

创建 Service 以将您的信息发送到您的服务器.据推测,你已经控制住了.

Create a Service to send your information to your server. Presumably, you've got that under control.

您的 Service 应该由 AlarmManager,您可以在其中指定间隔.除非您必须每 30 分钟准确报告一次数据,否则您可能需要不准确的警报,以便节省一些电池寿命.

Your Service should be started by an alarm triggered by the AlarmManager, where you can specify an interval. Unless you have to report your data exactly every 30 minutes, you probably want the inexact alarm so you can save some battery life.

最后,您可以通过设置 来注册您的应用以获取启动广播BroadcastReceiver 像这样:

Finally, you can register your app to get the bootup broadcast by setting up a BroadcastReceiver like so:

public class BootReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {  
        if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
            // Register your reporting alarms here.            
        }
    }
}

您需要将以下权限添加到您的 AndroidManifest.xml 中以使其工作.不要忘记在您正常运行应用程序时注册您的闹钟,否则它们只会在设备启动时注册.

You'll need to add the following permission to your AndroidManifest.xml for that to work. Don't forget to register your alarms when you run the app normally, or they'll only be registered when the device boots up.

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

这篇关于Android - 定期后台服务 - 建议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆