我需要在后台每小时执行web服务。
每小时,将检查互联网是否可用,然后执行一个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;
}发布于 2014-06-14 06:01:30
其想法是每小时使用AlarmManager启动一个后台服务。
设置警报管理器,每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;
}发布于 2014-06-14 06:09:00
在计时器任务的运行方法中添加调用webservice的代码,如下所示
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); https://stackoverflow.com/questions/24217011
复制相似问题