在后台android中每5分钟运行一次截击请求

在后台android中每5分钟运行一次截击请求,android,background,alarmmanager,android-volley,Android,Background,Alarmmanager,Android Volley,我使用截击库与应用程序中的服务器连接。现在,我必须每5分钟在后台发送一次请求,也就是当应用程序没有运行时(被用户杀死)。我该怎么做?有了后台服务,AlarmManager(谷歌说它不是网络运营的好选择)还是别的什么 或者SyncAdapter可能对它有好处?您可以在服务类中使用带有scheduleAtFixedRate的TimerTask来实现这一点,这里是服务类的一个示例,您可以使用它 public class ScheduledService extends Service { priv

我使用截击库与应用程序中的服务器连接。现在,我必须每5分钟在后台发送一次请求,也就是当应用程序没有运行时(被用户杀死)。我该怎么做?有了后台服务,
AlarmManager
(谷歌说它不是网络运营的好选择)还是别的什么


或者SyncAdapter可能对它有好处?

您可以在服务类中使用带有scheduleAtFixedRate的TimerTask来实现这一点,这里是服务类的一个示例,您可以使用它

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方法连接服务器。 这是服务的清单声明

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

我更喜欢使用Android处理程序,因为默认情况下它是在UI线程中执行的

import android.os.Handler;

// Create the Handler object (on the main thread by default)
Handler handler = new Handler();
// Define the code block to be executed
private Runnable runnableCode = new Runnable() {
    @Override
    public void run() {

       sendVolleyRequestToServer(); // Volley Request 

      // Repeat this the same runnable code block again another 2 seconds
      handler.postDelayed(runnableCode, 2000);
    }
};
// Start the initial runnable task by posting through the handler
handler.post(runnableCode);

当然,一旦设备进入睡眠状态,它就会停止工作
import android.os.Handler;

// Create the Handler object (on the main thread by default)
Handler handler = new Handler();
// Define the code block to be executed
private Runnable runnableCode = new Runnable() {
    @Override
    public void run() {

       sendVolleyRequestToServer(); // Volley Request 

      // Repeat this the same runnable code block again another 2 seconds
      handler.postDelayed(runnableCode, 2000);
    }
};
// Start the initial runnable task by posting through the handler
handler.post(runnableCode);