简体   繁体   English

从线程开始新活动

[英]Starting a new activity from a thread

I need to call a new activity from a thread class like this: 我需要从这样的线程类调用新的活动:
Intent i = new Intent(getContext(),GameOver.class);
and when i call startActivity(i) it gives me an error saying that the method is undefined for my class. 当我调用startActivity(i)它给我一个错误,指出该方法未为我的课程定义。
Can anyone tell me how do resolve this issue? 谁能告诉我如何解决这个问题?
Thanks! 谢谢!
Here is the full run method of the thread: 这是线程的完整运行方法:

/*starts running the thread*/
    @Override
    public void run(){
        while(run){
            Canvas c = null;
            try {
                c = surfaceHolder.lockCanvas(null);
                synchronized (surfaceHolder) {
                    if (mode == STATE_RUNNING){
                        /*if user has no more lives, he lost*/
                        if(Global.lives == 0) lose();
                        doDraw(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) {
                    /*unlocks the canvas and shows the image drawn by the doDraw method*/
                    surfaceHolder.unlockCanvasAndPost(c);
                }
            }

Where lose(); 在哪里lose(); is the method who's code is on the start( intent ). 是谁的代码在start(intent)上的方法。

First of all, startActivity is a method of Contex, so you will need to pass reference to a valid Context.. 首先,startActivity是Contex的一种方法,因此您需要将引用传递给有效的Context。

Second thing is, that as far as I know, activity can be started only from main (GUI) thread. 第二件事,据我所知,活动只能从主(GUI)线程开始。 There is several ways how to do it, one of them is for example something like this: 有几种方法可以做到这一点,例如:

Handler handler = new Handler(Looper.getMainLooper());

handler.post(new Runnable() {
    @Override
    public void run() {
        Intent intent = new Intent (MyActivity.this, NextActivity.class);
        startActivity(intent);
    }
});

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

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