繁体   English   中英

thread.sleep突然停止工作

[英]thread.sleep has suddenly stopped working

我目前正在Android上的Finals项目中工作。 该项目是关于SimonSays游戏的:在我的Simon Says游戏中,有一个部分应该让应用程序进入睡眠状态,但确实如此,我认为这是因为我的老师添加了所有这些try and catch

功能,我该如何解决?

    package com.gabie212.simonsays;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;

public class GameActivity extends AppCompatActivity implements View.OnClickListener,View.OnLongClickListener {

    private int i = 0, pNum = 0, pIndex = 0,score;
    private Thread t = new Thread();
    private Thread bt = new Thread();
    private Button greenButton;
    private Button redButton;
    private Button blueButton;
    private Button yellowButton;
    private Button startButton;
    private TextView Score;
    private boolean startActivated = false;
    private MediaPlayer greenBeep;
    private MediaPlayer redBeep;
    private MediaPlayer blueBeep;
    private MediaPlayer yellowBeep;

    private ArrayList<Integer> userColors = new ArrayList<Integer>();
    // change backgroud
    final String imagefile = "savedImageLocation";//for background
    private ImageButton btPhoto;  // for background
    private android.support.constraint.ConstraintLayout background; // for background
    private int yellowish = Color.rgb(0, 191, 255);// for background
    private Handler handler = new Handler();

    final int SECOND_ACTIVITY = 10;

    // game manager
    private GameManger gm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        setContentView(R.layout.activity_game);

        Score = (TextView) findViewById(R.id.ScoreNum);
        greenButton = (Button) findViewById(R.id.btnGreen);
        redButton = (Button) findViewById(R.id.btnRed);
        blueButton = (Button) findViewById(R.id.btnBlue);
        yellowButton = (Button) findViewById(R.id.btnYellow);
        startButton = (Button) findViewById(R.id.btnStart);
        greenButton.setOnClickListener(this);
        redButton.setOnClickListener(this);
        blueButton.setOnClickListener(this);
        yellowButton.setOnClickListener(this);
        startButton.setOnClickListener(this);
        greenBeep = MediaPlayer.create(this, R.raw.greenbeep);
        redBeep  = MediaPlayer.create(this, R.raw.redbeep);
        blueBeep =   MediaPlayer.create(this, R.raw.bluebeep);
        yellowBeep =  MediaPlayer.create(this, R.raw.yellowbeep);
        greenButton.setOnLongClickListener(this);
        redButton.setOnLongClickListener(this);
        blueButton.setOnClickListener(this);
        yellowButton.setOnClickListener(this);
     /*
        SharedPreferences sp = getSharedPreferences("score", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.clear();
        editor.apply();

     */


        // for change background
        btPhoto = (ImageButton) findViewById(R.id.btPhoto);
        btPhoto.setOnLongClickListener(this);
        background = (android.support.constraint.ConstraintLayout) findViewById(R.id.background);
    }

    public void start() {
        startActivated=true;
        gm = new GameManger(this);
        Score.setText("0");
        lightUp(0);
    }

    public void beepStop(){
        greenBeep.stop();
        redBeep.stop();
        blueBeep.stop();
        yellowBeep.stop();

    }


    public void lightUp(final int i) {

        android.os.Handler handler = new android.os.Handler();
        if (i < gm.getRandomColors().size())  //light up code
        {
            switch (gm.getRandomColors().get(i)) {
                case 1:
                    greenButton.setBackgroundResource(R.drawable.greenlightup);
                    greenBeep.start();
                    handler.postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            greenButton.setBackgroundResource(R.drawable.green);
                            lightUp(i+1);
                        }
                    }, 500);


                    break;
                case 2:
                    redButton.setBackgroundResource(R.drawable.redlightup);
                    redBeep.start();
                    handler.postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            redButton.setBackgroundResource(R.drawable.red);
                            lightUp(i+1);
                        }
                    }, 500);


                    break;
                case 3:
                    blueButton.setBackgroundResource(R.drawable.bluelightup);
                    blueBeep.start();
                    handler.postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            blueButton.setBackgroundResource(R.drawable.blue);
                            lightUp(i+1);
                        }
                    }, 500);


                    break;
                case 4:
                    yellowButton.setBackgroundResource(R.drawable.yellowlightup);
                    yellowBeep.start();
                    handler.postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            yellowButton.setBackgroundResource(R.drawable.yellow);
                            lightUp(i+1);
                        }
                    }, 500);


                    break;
            }

        }
        pIndex = 0;
    }


    @Override
    public void onClick(View v) {
        if (v.getId() == startButton.getId()) {
            start();
        } else {
            if (startActivated) {
                if (v.getId() == greenButton.getId()) {
                    greenBeep.start();
                    pNum = 1;
                }
                if (v.getId() == redButton.getId()) {
                    redBeep.start();
                    pNum = 2;
                }
                if (v.getId() == blueButton.getId()) {
                    blueBeep.start();
                    pNum = 3;
                }
                if (v.getId() == yellowButton.getId()) {
                    yellowBeep.start();
                    pNum = 4;

                }
                if (!gm.check(pNum, pIndex)) {
                    beepStop();
                    SharedPreferences sp = getSharedPreferences("score", Context.MODE_PRIVATE);
                    Intent i = null;
                    score = gm.getRandomColors().size()-1;
                    if(score > sp.getInt("scoreP3",0)) {
                         i = new Intent(GameActivity.this, InsertScoreActivity.class);
                        i.putExtra("score", gm.getRandomColors().size() - 1);
                        startActivity(i);
                    }
                    else {
                        i = new Intent(GameActivity.this, GameOverActivity.class);
                        i.putExtra("score", gm.getRandomColors().size() - 1);
                        startActivity(i);
                    }
                }
                pIndex++;
                if (pIndex == gm.getRandomColors().size()) {
                    Score.setText("" + gm.getRandomColors().size() + "");
                    gm.addColor();
                    //this is the sleep that doesn't work
                    try {                              
                        t.sleep(500);
                        // Do some stuff                 
                    } catch (Exception e) {
                        e.getLocalizedMessage();
                    }
                    //this is the sleep that doesn't work
                    lightUp(0);
                }
            }

        }

    }
    // for background
    public void getPhoto(View v)
    {
        //brings user to gallery to select image for background of screen
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"),0);
    }
    //for background
    @Override
    public boolean onLongClick(View view)
    {
        AlertDialog.Builder info = new AlertDialog.Builder(this);
        info.setTitle("Remove Background Image?");
        info.setMessage("Are you sure you wish to revert to the default background?");
        info.setCancelable(true);
        info.setPositiveButton("Yes", new DialogInterface.OnClickListener()
        {
            public void onClick(DialogInterface dialog, int id)
            {   //erases current background image location

                try {
                    FileOutputStream fos = openFileOutput(imagefile, Context.MODE_PRIVATE);
                    OutputStreamWriter osw = new OutputStreamWriter(fos);
                    BufferedWriter writer = new BufferedWriter(osw);

                    writer.close();
                    osw.close();
                    fos.close();

                    background.setBackgroundColor(yellowish);
                }
                catch (Exception e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
        info.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
        {
            public void onClick(DialogInterface dialog, int id)
            {
                dialog.cancel();
            }
        });

        info.show();

        return false;
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if(requestCode == 0 && resultCode == RESULT_OK)
        {
            try
            {
                Uri selectedImage = data.getData();

                grantUriPermission("com.example.memorygame", selectedImage,
                        Intent.FLAG_GRANT_READ_URI_PERMISSION);

                InputStream imageStream;
                imageStream = getContentResolver().openInputStream(selectedImage);
                Bitmap bitmap = BitmapFactory.decodeStream(imageStream);
                Drawable image = new BitmapDrawable(getResources(), bitmap);
                background.setBackground(image);

                //saves location of background image
                try
                {

                    FileOutputStream fos = openFileOutput(imagefile, Context.MODE_PRIVATE);
                    OutputStreamWriter osw = new OutputStreamWriter(fos);
                    BufferedWriter writer = new BufferedWriter(osw);

                    String imageUri = selectedImage.toString();
                    writer.append(imageUri);

                    writer.close();
                    osw.close();
                    fos.close();

                }
                catch (Exception e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            catch (FileNotFoundException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }



        }
    }

}

所以这是我的代码,我将在thread.sleep上放两个注释,这对我不起作用。 基本上,我具有此功能,该功能可以点亮一系列按钮(按特定顺序切换其颜色),然后具有接收用户输入(用户按下了哪些按钮以及按什么顺序)的功能。 我想通过睡眠来做的是在颜色输入的结束(当用户完成按东西时)和点灯的开始(当按钮点灯/更改其颜色)之间稍作休息。 我认为问题出在所有这些try and catch函数中,或者它们被称为(对不起,我是一个初学者),但是我不知道该如何克服这个问题。

在android中,您可以使用Handler来等待尽可能多的时间,这是2秒(2000毫秒)延迟的示例:

Handler handler = new Handler(); 
    handler.postDelayed(new Runnable() {
         @Override 
         public void run() { 
              // this code will run after 2 seconds
         } 
    }, 2000); 

只需在需要等待/休眠线程的任何地方插入此代码。

您应该避免Thread.sleep() 使用处理程序执行与UI相关的操作。

new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
    @Override
    public void run() {
        //Do something here
    }
}, 5000);

如果您有时间,请通过以下链接。 这将给出处理程序和线程的概念。 Android,Handler是在主线程还是其他线程中运行?

最好使用Handler代替Thread.sleep();

只要替换这个

 //this is the sleep that doesn't work
                    try {
                        t.sleep(500);
                        // Do some stuff
                    } catch (Exception e) {
                        e.getLocalizedMessage();
                    }
                    //this is the sleep that doesn't work

  Handler handler1=new Handler();
                    handler1.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            lightUp(0);
                        }
                    },500);

暂无
暂无

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

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