繁体   English   中英

Android:无法从扩展Thread的类中调用新活动

[英]Android: Can't call new activity from class that extends Thread

编辑:更改了代码以反映建议的答案...仍然认为我缺少了一些东西

我正在扩展Thread的类中运行游戏,并希望能够调用在特定时间执行图形的类。 为此,我试图使用意图打开类,但无法使其正常工作。 这是代码:

NewGameThread.java:

import android.content.Context;

public class NewGameThread extends Thread {

private Context context;

public GameView mGameView;

public NewGameThread(GameView gameView, Context context) {      
    mGameView = gameView;
    this.context = context;
}   
}

NewTheGame.java:

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class NewTheGame extends NewGameThread {


private Bitmap mBall;
private float mSmileyBallX = -100;
private float mSmileyBallY = -100;

public NewTheGame(GameView gameView) {

    super(gameView);
    //Set up my bitmaps
    mBall = BitmapFactory.decodeResource
            (gameView.getContext().getResources(), 
                    R.drawable.small_red_ball);

}
protected void updateGame(float secondsElapsed) {
    if(mSmileyBallX == mSmileyBallY) { //it actually calls another function that I removed for simplicity
        Intent intent = new Intent(context,Launcher.class);
        context.startActivity(intent);
    }
}

您需要活动类的上下文,因此在NewGameThread需要一个构造NewGameThread

Context context;

public NewGameThread(Context context)
{
   this.context = context;
}

然后在您的代码中,您必须使用以下上下文:

Intent intent = new Intent (context, Launcher.class);
context.startActivity(intent);

上下文应从活动中传递。 当您从Activity中创建类NewGameThread的对象时,请在构造函数中传递活动的上下文。 在意图调用中使用该上下文。

public class NewGameThread extends Thread {

    public NewGameThread(Context c){
        this.context = c;
    }  

    protected void getActTwo() {        
        Intent intent = new Intent(this.context,ActivityTwo.class);
        context.startActivity(intent);
    }
}

暂无
暂无

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

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