gpt4 book ai didi

每小时运行一次的 Android 服务,从 Webservice 获取数据并更新 localStorage webview chromeclinet

转载 作者:行者123 更新时间:2023-11-29 21:00:22 24 4
gpt4 key购买 nike

在我的 Android 应用程序中,我从 localStorage 检索数据并显示在 listview 中。现在我希望它即使在应用程序关闭时也能从网络服务获取更新的数据。

我正在使用 webchromeclient。我尝试过服务,但它只从应用程序开始,当应用程序关闭或销毁时我无法与 localStorage 交互,我试图在警报时触发服务

代码:

@Override
public void onReceive(Context context, Intent intent) {
WakefulIntentService.acquireStaticLock(context);
context.startService(new Intent(context, AppService.class));
}

最佳答案

例如,如果我需要每 3 秒运行一次服务,请使用以下代码:

Calendar cal = Calendar.getInstance();
Intent intent = new Intent(this, LockService.class);
PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 3*1000, pintent);

手机重启时结束需要BroadcastReceiver,如下代码:

public class MyScheduleReceiver extends BroadcastReceiver {

private static final long REPEAT_TIME = 1000 * 60;

@Override
public void onReceive(Context context, Intent intent) {
AlarmManager service = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, MyStartServiceReceiver.class);
PendingIntent pending = PendingIntent.getBroadcast(context, 0, i,
PendingIntent.FLAG_CANCEL_CURRENT);
Calendar cal = Calendar.getInstance();

cal.add(Calendar.SECOND, 60);

service.setInexactRepeating(AlarmManager.RTC_WAKEUP,
cal.getTimeInMillis(), REPEAT_TIME, pending);

}
}

和帮助类:

public class MyStartServiceReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, LocalWordService.class);
context.startService(service);
}
}

并需要许可

并在 list 上定义服务和 BroadcastReceiver

关于每小时运行一次的 Android 服务,从 Webservice 获取数据并更新 localStorage webview chromeclinet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26311948/

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