1

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

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

代码:

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

1 回答 1

2

例如,如果我需要每 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);
  }
}

并且需要许可

并在清单上定义服务和广播接收器

于 2014-10-11T07:00:23.150 回答