我声明了一个服务,它将充当一个队列。因此,我有一个变量告诉服务它是第一次启动,另一个变量存储一个值。
代码如下所示:
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();
}
}
好的,问题是,这个服务是从一个接收器启动的。每次启动时,lastvol
和 isFirstStart
都会重置。我想,如果服务已经创建,然后以 Intent 启动,它只会再次调用 onStartCommand()
而不会重置所有内容。
我还尝试在 onCreate()
中仅声明变量并将它们设置为默认值,但效果相同。
我还尝试用 IntentService
替换 Service
,但这也无济于事,同样的问题。
我想避免使用 SharedPreferences
,因为我认为在这种情况下不一定需要它。 (而且我不想浪费用户的写入周期)。
我错过了什么吗?我想这不是因为 private
声明,是吗?
最佳答案
这肯定与成员私有(private)无关。
我不确定问题出在哪里,但我可以想象这些候选人之一:
- 服务在第二个请求到达之前终止。
Receiver
生成一个新进程,因为它响应“系统 Intent ”。
您可以通过让您的服务定期记录一些内容来评估这种猜测。
关于android - 我的 Service/IntentService 中的变量在每次启动时都会重置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8931753/