从线程开始新活动

时间:2014-07-13 14:15:20

标签: android android-intent android-activity runnable

我需要从这样的线程类调用一个新活动:
   Intent i = new Intent(getContext(),GameOver.class);
当我打电话给startActivity(i)时,它给我一个错误,说我的班级没有定义该方法 谁能告诉我如何解决这个问题呢? 谢谢!
这是线程的完整运行方法:

/*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);
                }
            }

其中lose();是代码在开始时的意图(意图)。

1 个答案:

答案 0 :(得分:0)

首先,startActivity是Contex的一种方法,因此您需要将引用传递给有效的上下文。

第二件事是,据我所知,活动只能从主(GUI)线程启动。有几种方法可以做到,其中一种方法就是这样:

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

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