Android – every time a web service is executed in the background

I need to execute the web service in the background every hour

Every hour, the Internet is checked for availability, then the web service is executed and the data is updated

How can I do this?

My backstage service

public class MyService extends Service {

   String tag="TestService";
   @Override
   public void onCreate() {
       super.onCreate();
       Toast.makeText(this, "Service created...", Toast.LENGTH_LONG).show();      
       Log.i(tag, "Service created...");
   }

   @Override
   public void onStart(Intent intent, int startId) {      
       super.onStart(intent, startId);  
       if(isInternet)
       {
           AsyTask web= new AsyTask();
           web.execute();
       }
       Log.i(tag, "Service started...");
   }
   @Override
   public void onDestroy() {
       super.onDestroy();
       Toast.makeText(this, "Service destroyed...", Toast.LENGTH_LONG).show();
   }

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

   }

resolvent:

Our idea is to use AlarmManager to start the background service every hour

Set the alarm manager to start the background service every 60 minutes. This can be done in any activity

    startServiceIntent = new Intent(context,
            WebService.class);
    startWebServicePendingIntent = PendingIntent.getService(context, 0,
            startServiceIntent, 0);

    alarmManager = (AlarmManager) context
            .getSystemService(Context.ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
            System.currentTimeMillis(), 60*1000*60,
            startWebServicePendingIntent);

Create a WebService class that extends service, and then add a method to synchronize data with the server in the onstartcommand () method of the service. In addition, don't forget to declare the service in the list

Edit 1:

public class WebService extends Service {

   String tag="TestService";
   @Override
   public void onCreate() {
       super.onCreate();
       Toast.makeText(this, "Service created...", Toast.LENGTH_LONG).show();      
       Log.i(tag, "Service created...");
   }

   @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
       super.onStart(intent, startId);  
       if(isInternet)
       {
           AsyTask web= new AsyTask();
           web.execute();
       }
       Log.i(tag, "Service started...");
   }
   @Override
   public void onDestroy() {
       super.onDestroy();
       Toast.makeText(this, "Service destroyed...", Toast.LENGTH_LONG).show();
   }

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

   }

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>