Android 每天在后台执行web服务
我需要在后台每小时执行一次web服务 每小时,将检查互联网是否可用,然后执行web服务并更新数据 我该怎么做 我的后台服务Android 每天在后台执行web服务,android,android-background,android-webservice,Android,Android Background,Android Webservice,我需要在后台每小时执行一次web服务 每小时,将检查互联网是否可用,然后执行web服务并更新数据 我该怎么做 我的后台服务 public class MyService extends Service { String tag="TestService"; @Override public void onCreate() { super.onCreate(); Toast.makeText(this, "Service created...", T
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);
创建一个扩展服务的类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;
}
在计时器任务的run方法中添加调用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);
你试过什么?显示您的代码。简而言之,只需使用AlarmManager
即每小时调用您必须使用服务,并在onStart服务方法中设置计时器,并调用webservice,因为我正在提供服务,但不知道如何执行每小时。我已在下面添加了代码示例,请尝试。谢谢回答,但AlarmManager是最好的或计时器?我已使用此,它工作得很好。所以你可以使用它。我认为AlamAnger还有很长的路要走,如果我们可以轻松地使用计时器,那么我们应该使用它。如何在服务中使用它?你将在应用程序的MainActivity中添加此代码,以便无论何时启动应用程序,报警管理器设置此重复报警。然后,我如何通过服务类连接此代码您正在通过PendingEvent(上面的StartWebServicePendingEvent)连接它,该PendingEvent使用启动服务(WebService.class)的意图(startServiceIntent)我是android新手,所以我不理解。请提供相同的代码或编辑我的服务类