我正在开发一个 Android 应用程序,它需要每隔一小时左右在后台进行一些更新。我有一个后台服务,我已经将其设为 Sticky。我正在使用 Timer.scheduleAtFixedRate 来安排更新。
这似乎工作正常。但是我注意到,当我关闭应用程序时,下次运行计划的更新时,它会导致 Application.onCreate 再次被调用。
这是一个问题,因为 Application.onCreate 是我从准备显示给用户的 API 获取数据的地方。我不希望这发生在后台。
这是预期的行为吗?如果是这样,也许我需要在 onCreate 中添加一个检查以查看应用程序是否首先在前台?或者,也许我有什么设置错误?
谢谢!
ps 这是运行 Jelly Bean 4.2.1 的 Galaxy Samsung
后台服务代码:
@EService
public class BackgroundService extends Service {
...
private Timer timer = new Timer();
private void performUpdate() {
// Do the stuff here that we need to do on a schedule...
Log.i(LOG_CONTEXT, "Perform scheduled update");
...
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(LOG_CONTEXT, "Background thread started");
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
performUpdate();
}
}, 0, UPDATE_INTERVAL);
// Sticky means service will continue running until explicitly stopped
return START_STICKY;
}
@Override
public void onDestroy() {
Log.d(LOG_CONTEXT, "Background thread stopped");
timer.cancel();
}
}
申请代码:
@EApplication
public class MyApplication extends Application {
...
@Override
public void onCreate() {
super.onCreate();
initApp();
}
private void initApp() {
// This is where I want to do stuff when the app is actually
// opened by the user, not every time the background service
// update occurs!
Log.i(LOG_CONTEXT, "Initialise. Why does this happen again after app's closed?");
...
}
...
日志:
12-09 16:28:15.828: I/MyApplication(3049): Initialise. Why does this happen again after app's closed?
[Now I close the app, by pressing the Recent Apps menu button and swiping it away]
12-09 16:28:16.015: I/BackgroundService(3049): Perform scheduled update
12-09 16:28:33.875: I/MyApplication(3080): Initialise. Why does this happen again after app's closed?