2012-02-11 61 views
0

想要停止执行一些下载的线程。
下面的代码工作正常,当我只有stopNow = true;,并没有发生阻塞。
我在我的IntentService中创建了一个字段boolean stopNow = false;BroadcastReceiver是否足够异步执行此操作

由于stopNow只有当连接在while
是正在进行的工作,但它不一样,如果f.ex连接stales工作,并开始堵塞。

我想添加此代码来真正阻止阻塞。

if(socket != null){ 
    socket.shutdownOutput(); 
    socket.shutdownInput(); 
} 

的问题是,如果这是异步的,所以如果执行是在
while循环持续的stopNow = true;将停止它,我可以在stopNow = true;,然后if(socket != null)将是真正的后放睡眠(5000)只有在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

这实际上是工作的好为止

stopNow = true; 

try{ 
    if(socket != null){ 
     socket.shutdownOutput(); 
     socket.shutdownInput(); 
    } 
} catch (Exception e) {}  
-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(); 
       } 
+0

谢谢男人不知道该说什么:) – Erik 2012-02-18 21:49:33