android– 每次在后台执行Web服务

android– 每次在后台执行Web服务,第1张

概述我需要在后台每小时执行一次Web服务每小时,将检查Internet是否可用,然后执行Web服务并更新数据.我怎样才能做到这一点?我的后台服务publicclassMyServiceextendsService{Stringtag="TestService";@OverridepublicvoidonCreate(){super.onCreate(

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

每小时,将检查Internet是否可用,然后执行Web服务并更新数据.

我怎样才能做到这一点?

我的后台服务

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

解决方法:

我们的想法是使用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);

创建一个扩展Service的类WebService,然后添加方法以与服务的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;   }
总结

以上是内存溢出为你收集整理的android – 每次在后台执行Web服务全部内容,希望文章能够帮你解决android – 每次在后台执行Web服务所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1119094.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-29
下一篇2022-05-29

发表评论

登录后才能评论

评论列表(0条)

    保存