如何安排的机器人服务以固定速率执行 [英] How to schedule an android service to execute at a fixed rate

查看:116
本文介绍了如何安排的机器人服务以固定速率执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的工作应该下载从网络上每X秒,以检查是否有任何变化的文件的应用程序,我用一个服务要做到这一点,但它的执行是不固定的延时率,这里是我的code代表服务:

I am working on an application that should download a file from the network every X seconds to check for any change, I use a service to do that, but its execution is not fixed with the delay time rate, here is my code for the service:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
    checkUpdate();
    return START_STICKY;
}

private Void checkUpdate() {
    timer.scheduleAtFixedRate(new TimerTask() {
            public void run() {
                Log.i("Service", String.valueOf(++counter));
                if(Helper.isNetworkAvailable(getBaseContext())) {
                      // download file
                } else {
                        Log.e("ServiceHandler", "Couldn't get any data from the url");
                    }
                }else {
                    Log.e("Connection", "No connection");
                }
            }
        }, 10000, 10000);
    return null;
}


的输出是不固定的,它应该每10秒运行,同时运行的服务运行以随机方式


The output isn't fixed, it is supposed to run every 10 seconds, while running the service run in a random manner

推荐答案

如何在IntentService内设立AlarmManager?更精确。

How about setting up an AlarmManager within an IntentService? Much more accurate.

 Intent intent = new Intent(context, YourClass.class);
 PendingIntent pi = PendingIntent.getService(context, 0, intent, 0);
 AlarmManager am = (AlarmManager) c.getSystemService(Context.ALARM_SERVICE);
 am.setRepeating(AlarmManager.RTC, System.currentTimeMillis(), 10*1000, pi);

在YourClass.class(这是一个IntentService)确保,把你的逻辑在handleIntent(意向意图),这将是每10秒的的PendingIntent由AlarmManager发送调用。

Make sure within YourClass.class (which is an IntentService), put your logic in the handleIntent(Intent intent), which will be called every 10 seconds by the PendingIntent sent by the AlarmManager.

P.S。更新清单

希望它能帮助

这篇关于如何安排的机器人服务以固定速率执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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