每次在后台执行Web服务

时间:2014-06-14 05:52:27

标签: android android-background android-webservice

我需要在后台每小时执行一次网络服务

每小时都会检查互联网是否可用,然后执行网络服务并更新数据。

我该怎么做?

我的后台服务

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;

   }

2 个答案:

答案 0 :(得分:3)

这个想法是使用AlarmManager每小时启动一次后台服务。

设置Alarm Manager每60分钟启动一次后台服务。这可以在任何活动中完成。

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

创建扩展WebService的类Service,然后添加方法以与服务的onStartCommand()方法内的服务器同步数据。另外,不要忘记在清单中声明服务。

编辑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;

   }

答案 1 :(得分:0)

在timertask的run方法中添加调用Web服务的代码,如下所示

Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
   if(isInternet)
   {
       AsyTask web= new AsyTask();
       web.execute();
   }
   Log.i(tag, "Service started...");
}
}, 0, 3600000);