如何从 Activity 发出定期休息请求?
我的活动之一定期更新附近的朋友,该位置是从休息服务获取的。
目前我使用 postDelay:
private Runnable updateNearbyFriendsTask = new Runnable() {
@Override
public void run() {
list = api.getNearby(.....)
handler.postDelayed(this, UPDATE_RATE);
}
};
问题是 postDelayed 在 UI 线程上执行,因此这个可运行的任务会阻止 ui 的互联网连接较差。
从活动中定期发出后台休息请求的正确方法是什么?我不想为此创建服务,因为此休息方法仅在此活动中使用。
编辑
目前已切换为使用 ScheduledExecutor
this.scheduledExecutor.scheduleWithFixedDelay(new UpdateNearbyFriendsTask(), 0, UPDATE_RATE, TimeUnit.MILLISECONDS);
private class UpdateNearbyFriendsTask implements Runnable() {
@Override
public void run() {
list = api.getNearby(.....)
runOnUiThread(.....)
}
};
One of my activity periodically updates nearby friends, which location is obtained from rest service
Currently I use postDelay:
private Runnable updateNearbyFriendsTask = new Runnable() {
@Override
public void run() {
list = api.getNearby(.....)
handler.postDelayed(this, UPDATE_RATE);
}
};
The problem is that postDelayed executed on UI thread, so this runnable task block ui with poor internet connection.
What is the right way to make periodic background rest requests from activity? I don't want to create service for that, because this rest method is used only in this activity.
EDIT
Currently switched to using ScheduledExecutor
this.scheduledExecutor.scheduleWithFixedDelay(new UpdateNearbyFriendsTask(), 0, UPDATE_RATE, TimeUnit.MILLISECONDS);
private class UpdateNearbyFriendsTask implements Runnable() {
@Override
public void run() {
list = api.getNearby(.....)
runOnUiThread(.....)
}
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不明白创建服务有什么问题,即使它仅用于此活动。
话虽如此,请查看 TimerTask。它似乎做你想做的事。
I don't see what the problem is with creating a Service, even if it is only used for this activity.
That being said, have a look at the TimerTask. It seems to do what you want.
使用警报管理器的广播接收器怎么样.. http://developer.android.com/参考/android/app/AlarmManager.html
How about BroadCast receiver using Alarm manager.. http://developer.android.com/reference/android/app/AlarmManager.html
由于它是一项长期运行且持续的任务,您是否想要编写一个服务或一个意图服务来为您完成后台工作。
只要时间一到,您就可以 ping 服务,让服务执行网络活动,从而释放 UI 线程以执行其他操作。您始终可以查询服务以了解状态,或者服务本身可以响应您的 UI 线程。
为了勾选计时器,您可以使用警报管理器,或者其他东西(我不擅长:P)
Since its a long running and on going task, would you want to write a Service or an Intent service which does the background job for you.
You can just ping the service whenever your time ticks and let the service do the network activity, freeing up the UI thread for something else. you can always query the service to know the status, or the service itself can respond back to your UI thread.
For ticking the timer, you can use the alarm manager, or perhaps something else (I am not good at any :P )