简体   繁体   English

使用thread.join从surfaceview结束android活动

[英]ending android activity from surfaceview using thread.join

I'm working on my first app for android - snake. 我正在为Android开发第一个应用程序-snake。 Right now I'm trying to implement 'game over' for that app. 现在,我正在尝试为该应用实施“游戏结束”。 So basically when the snake hits the wall, app should ask your name and put it witch your score on HiScore. 因此,基本上,当蛇撞到墙上时,应用程序应该询问您的名字,并将其分数记录在HiScore上。 Well i'm stuk on hitting the wall fragment. 好吧,我在砸墙碎片。 Im experimenting with threads and so far I've found no way to stop it without getting errors. 我正在尝试线程,到目前为止,我还没有找到停止错误的方法。

I googled a lot, and everyone is saying that thread.join(); 我在Google上搜索了很多,每个人都在说thread.join();。 is waiting for thread to end, so how long does it take to end the thread that is drawing simple squares once per half second? 正在等待线程结束,那么结束每半秒绘制一次简单正方形的线程需要多长时间? When im hitting the back button on my phone while playing, pause(); 当我在播放时按下手机上的后退按钮时,pause(); function works perfectly. 功能完美运行。 Log "game has ended" appears on LogCat. 日志“游戏已结束”出现在LogCat上。

So the problem is that i cant stop this activity when snake hits the wall, Log "game has ended" never occurs. 因此,问题在于当蛇撞到墙上时,我无法停止此活动,永远不会发生“游戏已结束”日志。 Why is that? 这是为什么?

My code: 我的代码:

public class SnakeCage extends SurfaceView implements Runnable{

    // blah blah .. functions that draw and stuff ..


    public void pause() {
        isRunning = false;
        while(true){
            try {
                aThread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            break;
        }
        aThread = null;
    Log.d("pause()","game has ended"); // <<<<<<<<<THIS ONE>>>>>>>>>
    }

    public void resume() {
        isRunning = true;       
        aThread = new Thread(this);
        aThread.start();
    }

    public void init(){
        // blah blah...
    }


    private void gameOver() {
    int pHeadX = snakeHead.posX;
    int pHeadY = snakeHead.posY;

        Log.d("gameOver()", "checking");

        if(pHeadY<0 || pHeadX<0 || pHeadX>23 || pHeadY>19){

            Log.d("gameOver()", "game now will end");
            gameOver = true;
        }
    }

    public void run() {

        while (isRunning){
            if(!aHolder.getSurface().isValid())
                continue;

            canvas = aHolder.lockCanvas();

            // drawing

            gameOver();
            if(gameOver) break;

            // more drawing 


            aHolder.unlockCanvasAndPost(canvas);
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        if(gameOver){
                 pause();
        }
    }

and the activity class: 和活动类:

public class PlayingActivity extends Activity implements OnClickListener{

    SnakeCage v;
    Button snakeGoUp;
    Button snakeGoDown;
    Button snakeGoLeft;
    Button snakeGoRight;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);     

        setContentView(R.layout.frame_layout);
        v = (SnakeCage)findViewById(R.id.sView);

        // listeners and stuff

    }


    @Override
    protected void onPause() {
        super.onPause();
        v.pause();
    }


    @Override
    protected void onResume() {
        super.onResume();
        v.resume();
    }


    @Override
    public void onClick(View view) {
        switch(view.getId()){

        case R.id.snakeUp:
            v.move(1);
            break;

        case R.id.snakeDown:
            v.move(2);
            break;

        case R.id.snakeLeft:
            v.move(3);
            break;

        case R.id.snakeRight:
            v.move(4);
            break;
        }

    }
}

i just did: 我已经做了:

Context context = getContext();
((PlayingActivity)context).finish();

from: 从:

How can I end an activity from inside a SurfaceView class or nested thread 如何从SurfaceView类或嵌套线程内部结束活动

although it does not satisfy me... its enough for now 虽然它不令我满意...就目前而言

I would suggest using a LocalBroadcastManager to send a message to the Activity , to notify it to kill itself. 我建议使用LocalBroadcastManager将消息发送到Activity ,以通知它杀死自己。 You can have an inner class in the Activity to receive the broadcast and call a private method in the Activity which will end it. 您可以在Activity有一个内部类来接收广播,并在Activity调用一个私有方法以结束广播。

public class MyActivity extends Activity {

    public void onCreate(Bundle state) {
        LocalBroadcastManager.getInstance(this).registerReceiver(new MessageHandler(),
                                                             new IntentFilter("kill"));
    }

    private void killActivity() {
        finish();
    }

    public class MessageHandler extends BroadcastReceiver {
        onReceive(Context context, Intent intent) {
            killActivity();
        }

}

Then in your SurfaceView all you need to do is: 然后,在SurfaceView您所需要做的就是:

Intent intent = new Intent("kill");
LocalBroadcastManager.getInstance(getContext()).sendBroadcast(intent);

Its a little more code but its a lot cleaner IMHO. 它的代码多一点,但恕我直言。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM