BroadcastReceiver 是否足够异步以使其工作
想要停止线程进行一些下载。
当我只有 stopNow = true;
并且没有发生阻塞时,下面的代码工作正常。
我创建了 boolean stopNow = false;
作为 IntentService 中的一个字段。
由于 stopNow
仅当连接在 while
循环中进行时才起作用
但如果 f.ex 连接陈旧并开始阻塞,它就不起作用。
我想添加这段代码来真正阻止阻塞。
if(socket != null){
socket.shutdownOutput();
socket.shutdownInput();
}
问题是这是否是异步的,因此执行是否正在while
循环 stopNow = true;
将停止它,我可以在 stopNow = true;
之后放置一个 sleep(5000),然后是 <仅当 stopNow
无效时,code>if(socket != null) 才会为 true。
希望你关注我..
位于 run()
内的 BroadcastReceiver
:
private class MyIncomingListener extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(Consts.COM_CARLSBERG_STOPOUTGOING)) {
String b = intent.getStringExtra(Consts.COM_CARLSBERG_BATCHUUID);
if(b != null){
if(b.equals(batch.batchUuid)){
stopNow = true;
// sleep(5000) wait for stopNow to take effect
// if socket=null then stopNow did it's job
// if socket is alive then there is blocking to unblock
try{
if(socket != null){
socket.shutdownOutput();
socket.shutdownInput();
}
} catch (Exception e) {}
}
}
}
}
}
Wanted to stop a thread doing some downloads.
The code below work fine when i only have the stopNow = true;
and no blocking occur.
I create the boolean stopNow = false;
as a field in my IntentService.
Since stopNow
only work when the connection is ongoing in the while
loop
but it does not work if f.ex connection stales and start to block.
I wanted to add this code to really stop the blocking.
if(socket != null){
socket.shutdownOutput();
socket.shutdownInput();
}
The question is if this is asynchronous so if the execution is ongoing in thewhile
loop the stopNow = true;
will stop it and i can put a sleep(5000) after the stopNow = true;
and then the if(socket != null)
will be true only if the stopNow
had no effect.
hope you follow me..
BroadcastReceiver
that are located inside the run()
:
private class MyIncomingListener extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(Consts.COM_CARLSBERG_STOPOUTGOING)) {
String b = intent.getStringExtra(Consts.COM_CARLSBERG_BATCHUUID);
if(b != null){
if(b.equals(batch.batchUuid)){
stopNow = true;
// sleep(5000) wait for stopNow to take effect
// if socket=null then stopNow did it's job
// if socket is alive then there is blocking to unblock
try{
if(socket != null){
socket.shutdownOutput();
socket.shutdownInput();
}
} catch (Exception e) {}
}
}
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
到目前为止这实际上运作良好
this is actually working good so far