gpt4 book ai didi

android - 每隔一段时间在后台执行网络服务

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:25:11 25 4
gpt4 key购买 nike

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

每隔一小时,将检查 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 每小时启动一次后台服务。

将警报管理器设置为每 60 分钟启动一次后台服务。这可以在任何 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);

创建一个扩展 ServiceWebService 类,然后在 Service 的 onStartCommand() 方法中添加与服务器同步数据的方法.另外,不要忘记在 list 中声明服务。

编辑 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 - 每隔一段时间在后台执行网络服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24217011/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com