gpt4 book ai didi

Android粘性后台服务关闭后重新启动应用程序

转载 作者:行者123 更新时间:2023-11-29 21:53:39 25 4
gpt4 key购买 nike

我正在开发一个 Android 应用程序,它需要每隔一小时左右在后台进行一些更新。我有一个后台服务,我已将其设为 Sticky。我正在使用 Timer.scheduleAtFixedRate 来安排更新。

这似乎工作正常。但我注意到,当我关闭该应用程序时,下次计划的更新运行时,它会导致再次调用 Application.onCreate。

这是一个问题,因为 Application.onCreate 是我从准备显示给用户的 API 中抓取数据的地方。我不希望这种情况在后台发生。

这是预期的行为吗?如果是这样,也许我需要在 onCreate 中添加一个检查以查看该应用程序是否首先在前台?还是我设置有误?

谢谢!

附注这是运行 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?

最佳答案

您的服务作为应用程序的一部分运行,因此应用程序是为它创建的。

大多数应用不需要扩展Application。没有看到你所有的代码,我很确定你也不需要。只需为向用户显示内容的类扩展 Activity 并在其中执行 API 操作。服务运行时不会创建它。

关于Android粘性后台服务关闭后重新启动应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13789368/

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