编辑:更改了代码以反映建议的答案...仍然认为我遗漏了某些内容
我在扩展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);
}
}
答案 0 :(得分:4)
您需要活动类的上下文,因此在NewGameThread
Context context;
public NewGameThread(Context context)
{
this.context = context;
}
然后在你的代码中你必须使用这样的上下文:
Intent intent = new Intent (context, Launcher.class);
context.startActivity(intent);
答案 1 :(得分:1)
应该从活动传递上下文。从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);
}
}