简体   繁体   中英

AlertDialog in a Thread

I have a MainActivity Class and a Class that extends

public void run()
{
    while(true)
    {
        this.person.movePerson();

        checkWin();
        checkHit();



        this.gameview.postInvalidate();

        try
        {
            sleep(4);
        }
        catch(InterruptedException e)
        {
            e.printStackTrace();
        }
    }
}

This is my Thread. In The function 'CheckWin' the game need to check if the user won or not and then show a dialog. But i can't show a dialog because of a handler problem. so i tried to add a handler to the tread, the problem that i always getting a syntax problems -- i am new to developing.

I passed a handler from the MainActivity, and tried to do this:

hand.post(new Runnable{
@Override
public void run()
{
    while(true)
    {
        this.person.movePerson();

        checkWin();
        checkHit();



        this.gameview.postInvalidate();

        try
        {
            sleep(4);
        }
        catch(InterruptedException e)
        {
            e.printStackTrace();
        }
    }
}});

And everything that i get is only a syntax errors.

This is my AlertDialog Code:

AlertDialog.Builder alert = new AlertDialog.Builder(gameview.getContext());
                alert.setTitle("Game Over");
                alert.setMessage("Your Score is: " + result.score);
                alert.setNeutralButton("Again!!", null);
                alert.create();
                alert.show();

I don't know what syntax error you get, but here is a little explanation on the working with threads in Android . First of all, if you are using plain Thread I suggest you to switch to HandlerThread . It's Android-specific Thread class built with Looper . Secondly, when you create a new Handler it will be attached to the thread from which it was created. If you are going to update UI, Handler which is responsible for posting UI updates to the MessageQueue should be created from UI thread. Alternatively you can pass a Thread -specific Looper to the Handler 's constructor.

But I suppose you get syntax error on using this since it's pointing to a wrong object. If person and gameview are the fields of MainActivity class, for example, you can try to reference them by calling MainActivity.this.person...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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