Run volley request every 5 minutes in background android

前端 未结 2 1975
盖世英雄少女心
盖世英雄少女心 2021-02-04 21:52

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 i

2条回答
  •  无人及你
    2021-02-04 22:18

    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();
    }
    
    }
    

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

    
    

    To start the service from MainActivity,

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

提交回复
热议问题