在后台android中每5分钟运行一次凌空请求 [英] Run volley request every 5 minutes in background android

查看:111
本文介绍了在后台android中每5分钟运行一次凌空请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Volley库与我的应用程序中的服务器连接。现在,当应用未运行(被用户杀死)时,我也必须每5分钟在后台发送一次请求。我该怎么办?借助后台服务, AlarmManager (谷歌表示这不是网络操作的不错选择)还是其他?

I use Volley library to connect with server in my app. Now, I have to send request in background every 5 minutes also when app is not running (killed by user). How should I do it? With background services, AlarmManager (Google says that it isn't good choice for network operations) or something else?

也许SyncAdapter会更好?

Or maybe SyncAdapter will be good for it?

推荐答案

您可以将TimerTask与 scheduleAtFixedRate 一起使用一个服务类来实现这一点,这里是一个服务类的示例,您可以使用它

You can use a TimerTask with scheduleAtFixedRate in a service class to achieve this, here is an example of Service class, you can use it

public class ScheduledService extends Service 
{

private Timer timer = new Timer();


@Override
public IBinder onBind(Intent intent) 
{
    return null;
}

@Override
public void onCreate() 
{
    super.onCreate();
    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            sendRequestToServer();   //Your code here
        }
    }, 0, 5*60*1000);//5 Minutes
}

@Override
public void onDestroy() 
{
    super.onDestroy();
}

}

您可以使用 sendRequestToServer 方法与服务器连接。
这是服务的清单声明。

You can use sendRequestToServer method to connect with the server. Here is the manifest declaration of the Service.

<service android:name=".ScheduledService" android:icon="@drawable/icon" android:label="@string/app_name" android:enabled="true"/>

要从MainActivity启动服务,

To start the service from MainActivity,

// use this to start and trigger a service
Intent i= new Intent(context, ScheduledService.class);
context.startService(i);

这篇关于在后台android中每5分钟运行一次凌空请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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