想要停止线程进行一些下载
当我只有stopNow = true;
并且没有阻塞时,下面的代码工作正常
我在我的IntentService中创建boolean stopNow = false;
字段。
由于stopNow
仅在while
循环中正在进行连接时才起作用
但如果f.ex连接stales并开始阻止它不起作用。
我想添加此代码以真正阻止阻止。
if(socket != null){
socket.shutdownOutput();
socket.shutdownInput();
}
问题是这是否是异步的,所以如果执行正在进行中
while
循环stopNow = true;
将停止它,我可以在stopNow = true;
之后暂停(5000),然后if(socket != null)
只有在stopNow
时才会为真没有效果。
BroadcastReceiver
内的 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) {}
}
}
}
}
}
答案 0 :(得分:0)
stopNow = true;
try{
if(socket != null){
socket.shutdownOutput();
socket.shutdownInput();
}
} catch (Exception e) {}
答案 1 :(得分:-1)
public final void stop ()
Since: API Level 1
This method is deprecated.
because stopping a thread in this manner is unsafe and can leave your application and the VM in an unpredictable state.
Requests the receiver Thread to stop and throw ThreadDeath. The Thread is resumed if it was suspended and awakened if it was sleeping, so that it can proceed to throw ThreadDeath.
try {
int waited = 0;
while(_active && (waited < _splashTime)) {
sleep(100);
if(_active) {
waited += 100;
}
}
} catch(InterruptedException e) {
// do nothing
} finally {
finish();
Intent intent= new Intent(SplashActivity.this,LoginViewController.class);
startActivity(intent);
stop();
}