2012-02-11 51 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