通读 Android page on Services他们展示了一个基本的 IntentService 实现的例子。我计划实现类似的东西,因为它需要绑定(bind)。但是,我很困惑为什么他们需要使用下面的同步块(synchronized block)。如果有人可以阐明这一点,我将不胜感激。
// Handler that receives messages from the thread
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
// Normally we would do some work here, like download a file.
// For our sample, we just sleep for 5 seconds.
long endTime = System.currentTimeMillis() + 5*1000;
while (System.currentTimeMillis() < endTime) {
synchronized (this) {
try {
wait(endTime - System.currentTimeMillis());
} catch (Exception e) {
}
}
}
// Stop the service using the startId, so that we don't stop
// the service in the middle of handling another job
stopSelf(msg.arg1);
}
}
最佳答案
示例试图模拟真实的 IntentService
,例如下载文件。考虑这个故事:
你要求它下载一个文件,正如它在代码中所注释的那样,它通过等待 5ms 来模拟。为了调用等待函数,您需要一个同步块(synchronized block)。为什么?
因为如果你不这样做,它会抛出 IllegalMonitorStateException
关于android - 为什么这里需要synchronized?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26081203/