2015-12-16 133 views
0

我有一個像下面這樣的活動。當活動暫停或停止時,我希望活動中的線程終止。我搜索並找到了不適合我的易變的布爾解決方案。當我把活動暫停或停止狀態時,下載繼續,我不想要它。Android,在活動暫停或停止時終止線程?

public class MyActivity extends Activity { 
//some code here 
    private void foo(){ 
    new Thread (new Runnable(){ 
     @Override 
     public void run() { 
      //download something from internet 
     } 
}).start(); 
} 
} 

我用這個模式,沒有工作:

public class MyActivity extends Activity { 
volatile Boolean state = true; 
//some code here 
    private void foo(){ 
    new Thread (new Runnable(){ 
     @Override 
     public void run() { 
     while (state) { 
      //download something from internet 
     } 
    } 
}).start(); 
} 
@Override 
public void onPause(){ 
super.onPause(); 
state = false; 
} 
@Override 
public void onStop(){ 
super.onStop(); 
state = false; 
} 
} 
+0

您必須手動完成。 *「從互聯網下載東西」*可以通過很多不同的方式實施,向您展示。 – m0skit0

+0

創建一個變量:Thread t;這將是類globalba –

+0

檢查[這](http://stackoverflow.com/questions/9458097/android-how-do-i-stop-runnable)之一。 http://stackoverflow.com/questions/9458097/android-how-do-i-stop-runnable –

回答

0

這裏的時候背部被擊中其停止線程的結構,這是我爲我做遊戲的例子(作品) 。一個關鍵的區別是你在你的Activity中使用一個線程,而在我的Activity中我調用一個View並在View中運行該線程。如果我回來了,我回到我的活動,並可以通過點擊「開始」再次調用線程。因爲我的線程的行爲方式也是你想要的,即使它發生在View中,我認爲你可能會覺得它有幫助。

我的同步發生的地方在於觸摸屏的值,並確保它們在線程和調用函數中更新。

除非您有保存狀態的方法(如果需要),否則線程將被完全刪除。

你的線程都需要與要控制等功能/與線程共享的價值觀,就像在onPause等同步..

**你需要有你的while循環裏面的一些同步測試值然後可以將狀態更改爲false,否則該線程將自行繼續,這是線程的要點。

public class GameView extends SurfaceView implements SurfaceHolder.Callback { 

private final GameActivity gameActivity; 
private GameThread _thread; 
private boolean previouslyRunning = false; 
private int width; //Screen width 
private int height; //Screen height 



private boolean newGame = true; 

public GameView(Context context) { 
    super(context); 
    getHolder().addCallback(this); 
    this.gameActivity = (GameActivity) context; 
    _thread = new GameThread(getHolder(), this); 
    setFocusable(true); 
    setFocusableInTouchMode(true); 
} 

@Override 
protected void onSizeChanged(int w, int h, int oldw, int oldh) { 
    width = w; 
    height = h; 

    super.onSizeChanged(w, h, oldw, oldh); 

    //_thread.initialize(); 
} 

@Override 
public void surfaceCreated(SurfaceHolder holder) { 
    if (!previouslyRunning) { 
     _thread = new GameThread(getHolder(), this); 
     _thread.initialize(); 
    } 

    _thread.setRunning(true); 
    _thread.start(); 
    previouslyRunning = true; 
} 

@Override 
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { 
    //TODO - this was an Auto-generated method stub... 
    //TODO - research what this might be useful for 
} 

@Override 
public void surfaceDestroyed(SurfaceHolder holder) { 

    //Put stuff that needs destructed here. 

    boolean retry = true; 
    _thread.setRunning(false); 
    while (retry) { 
     try { 
      _thread.join(); 
      retry = false; 
     } catch (InterruptedException e) { 
      // will will try again and again 
      //TODO: figure it out.... 
     } 
    } 

} 

public boolean onTouchEvent(MotionEvent event) { 

    int numPointers = event.getPointerCount(); 
    int ptrIdx = 0; 


    int touch = event.getActionMasked(); 

    if (touch == MotionEvent.ACTION_DOWN) { 

     while (ptrIdx < numPointers) { 
      int id = event.getPointerId(ptrIdx); 
      float xp = event.getX(ptrIdx)/width; 

      if (xp > 0.6) { 
       _thread.shieldFront = false; 
      } 

      if (xp > 0.6 && !attacks) { 
       attacks = true; 
       _thread.attackandDefendToggle(true); 
      } else if (xp > 0.6 && attacks) { 
       attacks = false; 
       _thread.attackandDefendToggle(false); 
      } else if ((xp < 0.4 && xp > 0.2) && !movedRight) { 
       movedRight = true; 
       _thread.moveRight(true); 
      } else if ((xp < 0.4 && xp > 0.2) && movedRight) { 
       movedRight = false; 
       _thread.moveRight(false); 
      } else if (xp < 0.2 && !movedLeft) { 
       movedLeft = true; 
       _thread.moveLeft(true); 
      } else if (xp < 0.2 && movedLeft) { 
       movedLeft = false; 
       _thread.moveLeft(false); 
      } 
      ptrIdx++; 
     } 
    } 

    if (touch == MotionEvent.ACTION_UP) { 
     _thread.moveLeft(false); 
     _thread.moveRight(false); 
     _thread.attackandDefendToggle(false); 
     attacks = false; 
     _thread.shieldFront = true; 
    } 



    return true; 
} 

class GameThread extends Thread { 

    /**************************** 
    * Public functions  * 
    ****************************/ 

    public GameThread(SurfaceHolder surfaceHolder, GameView panel) { 
     _surfaceHolder = surfaceHolder; 
     _panel = panel; 

     // put sounds here. 
     soundPool = new SoundPool(20, AudioManager.STREAM_MUSIC, 0); 
     //more sounds later 
     //TODO: create sounds 
    } 

    /************************************************ 
    * update() function updates all variables, * 
    * such as physics, Canvas draw points, score * 
    * life, etc.. It is called before draw.  * 
    ************************************************/ 
    private void update() { 
     // all the values I want updated with each callback 

    } 

    /************************************************ 
    * draw() function creates images on screen, * 
    * but it performs no logic.    * 
    ************************************************/ 
    private void draw(Canvas canvas) { 

     if (canvas == null) { 
      return; 
     } 
     //Draw stuff on screen 
    } 

    public void initialize() { 
     // Values I want the program to start with; 
    } 

    public void setRunning(boolean run) { 
     _run = run; 
    } 

    //Code below actually runs the thread. 
    @Override 
    public void run() { 
     Canvas c; 
     while (_run) { 
      c = null; 
      try { 
       c = _surfaceHolder.lockCanvas(null); 
       synchronized (_surfaceHolder) { 

        // Update the game state 
        update(); 

        // Draw image 
        draw(c); 
       } 

      } finally { 
       // do this in a finally so that if an exception is thrown 
       // during the above, we don't leave the Surface in an 
       // inconsistent state 

       if (c != null) { 
        _surfaceHolder.unlockCanvasAndPost(c); 
       } 
      } 
     } 
    } 
}