android - 我的 Service/IntentService 中的变量在每次启动时都会重置

标签 android variables constructor android-service intentservice

我声明了一个服务,它将充当一个队列。因此,我有一个变量告诉服务它是第一次启动,另一个变量存储一个值。

代码如下所示:

public class TTSQueue extends Service {

private Integer lastvol = 0;
private Boolean isFirstStart = true;

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Bundle b = intent.getExtras();
    Integer vol = b.getInt(TTS.PARAM_LAST_VOL, 0);
    if (vol > lastvol) {
        lastvol = vol;
    }
    if (isFirstStart) {
        isFirstStart = false;
        startAnotherService();
    } else {
        waitForAnEventAndThen_startAnotherService();
    }

}

好的,问题是,这个服务是从一个接收器启动的。每次启动时,lastvolisFirstStart 都会重置。我想,如果服务已经创建,然后以 Intent 启动,它只会再次调用 onStartCommand() 而不会重置所有内容。

我还尝试在 onCreate() 中仅声明变量并将它们设置为默认值,但效果相同。 我还尝试用 IntentService 替换 Service,但这也无济于事,同样的问题。

我想避免使用 SharedPreferences,因为我认为在这种情况下不一定需要它。 (而且我不想浪费用户的写入周期)。

我错过了什么吗?我想这不是因为 private 声明,是吗?

最佳答案

这肯定与成员私有(private)无关。

我不确定问题出在哪里,但我可以想象这些候选人之一:

  • 服务在第二个请求到达之前终止。
  • Receiver 生成一个新进程,因为它响应“系统 Intent ”。

您可以通过让您的服务定期记录一些内容来评估这种猜测。

关于android - 我的 Service/IntentService 中的变量在每次启动时都会重置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8931753/

相关文章:

android - 在耳机和听筒之间切换

php - 将 jquery 变量传递给 php

function - 在 MATLAB 中,哪些 ASCII 字符可以出现在函数名中?

javascript - 通过父构造函数创建 Backbone 继承 View

android - Android 中按钮组的 onLongClick 监听器

android - 在Android Canvas 透明矩形上绘制双色正方形

java - Top Trumps 卡的类结构

python - 为什么 python pyttsx3 忽略我的第三个输入?

java - 哈希集作为 Java 中的构造函数参数

java - 为具有非默认构造函数和依赖注入(inject)的类创建 Mockito 测试