线程之间的通信有问题

时间:2015-05-22 20:25:12

标签: android multithreading

我在构建游戏和使用多线程方面的第一次尝试大部分进展顺利,但我现在陷入困境。

这是一个简单的Whack一个鼹鼠克隆,所以我在layout.xml中声明了一个3x4网格的鼹鼠ImageViews,然后我用setContentView(R.layout.layout)来建立它,然后是一个单独的线程来制作其中一个出现一秒钟,然后消失。这是我的活动onCreate()

public class WAM_Activity extends Activity {

private static final int MAKE_VISIBLE = 1;
private static final int MAKE_INVISIBLE = 0;
private ImageView[] mole = new ImageView[11];
private ImageView currentMole;
private int[] moleId = {R.id.mole1, R.id.mole3, R.id.mole4, R.id.mole5, R.id.mole6, R.id.mole7, R.id.mole8, R.id.mole9, R.id.mole10, R.id.mole11, R.id.mole12};
private boolean running = true;
private int randomInt = 0;
private Random rand = new Random();
private Handler handler;
//private WAM_Thread wamthread = new WAM_Thread();
private Context cont = this;
private static Handler h;
Message msg;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.wam_view_layout);

    //add ImageViews declared in R.layout.wam_view_layout to ImageView objects
    for (int i = 0; i < 11; i++) {
        mole[i] = (ImageView) findViewById(moleId[i]);
        mole[i].setVisibility(View.INVISIBLE);
        mole[i].setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(cont, "You clicked one!", Toast.LENGTH_SHORT).show();
            }
        });
    }

    handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch(msg.what) {
                case MAKE_VISIBLE:
                    currentMole = (ImageView) msg.obj;
                    currentMole.setVisibility(View.VISIBLE);
                    break;
                case MAKE_INVISIBLE:
                    currentMole = (ImageView) msg.obj;
                    currentMole.setVisibility(View.INVISIBLE);
            }
        }
    };

    Runnable runnable = new Runnable() {
        public void run() {
            while (running) {
                randomInt = rand.nextInt(11);
                msg = handler.obtainMessage();
                msg.obj = mole[randomInt];
                msg.what = MAKE_VISIBLE;
                handler.sendMessage(msg);
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        msg = handler.obtainMessage();
                        msg.obj = mole[randomInt];
                        msg.what = MAKE_INVISIBLE;
                    }
                }, 1000);
            }
        }
    };
    Thread thread = new Thread(runnable);
    thread.start();
}

默认情况下,布局xml文件中声明所有的痣都是不可见的,所以这段代码应该使其中一个可见,等待一秒,然后让他再次看不见,然后让另一个看得见并重复。相反,它使它们始终可见。他们仍然对水龙头做出反应,但就是这样。

任何人都能看到我做错了什么?自昨晚以来,我一直在努力解决这个问题,但我真的很接近于做对了。

1 个答案:

答案 0 :(得分:1)

两件事:

  • 在您的runnable结束时,添加Thread.sleep(1000)以便后台线程在看到一件事后暂停
  • 在postDelayed runnable中,您不是在调用handler.sendMessage