该程序中的主线程出于任何原因都做过多的工作。我不知道如何在主线程上使用视图。我已经尝试过使用AsyncTask,但是我不知道该如何使用它。
Thread thread2 = new Thread(){
public void run(){
while(running){
runOnUiThread(new Runnable() {
@Override
public void run() {
try{
if(red){
buttons[ran].setImageResource(R.drawable.button_red);
buttons[ran].setTag("Red");
Thread.sleep(duration);
if(buttons[ran].getTag().equals("Red")){
buttons[ran].setTag("Black");
buttons[ran].setImageResource(R.drawable.button_null);
lifeLost();
red = false;
}
}else if(white){
buttons[ran].setImageResource(R.drawable.button_white);
buttons[ran].setTag("White");
Thread.sleep(duration);
if(buttons[ran].getTag().equals("White")){
buttons[ran].setTag("Black");
buttons[ran].setImageResource(R.drawable.button_null);
lifeLost();
white = false;
}
}
}catch(Exception e){
}
}
});
try {
sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
thread2.start();
此线程正在执行我可以给它的与UI相关的所有任务。代码本身实际上在此线程上工作。但是,它仅适用于较新的设备,而较旧的设备似乎可以发现该错误,而不是忽略它。
@Override
public void run() {
random = new Random();
random2 = new Random();
try{
Thread.sleep(1000);
while(running){
ran = random.nextInt(9);
type = random2.nextInt(3);
if(lives > 0){
if(type == 0 || type == 2){
red = true;
}else{
white = true;
}
if(lives == 0){
Thread.sleep(1000);
Intent overIntent = new Intent(this, OverActivity.class);
overIntent.putExtra("point", score);
startActivity(overIntent);
overridePendingTransition(0, 0);
}
if(score == 10){
duration -= 50;
}else if(score == 20){
duration -= 50;
}else if(score == 30){
duration -= 50;
}else if(score == 40){
duration -= 50;
}
}
}
}catch(Exception e){
e.printStackTrace();
}
}
答案 0 :(得分:0)
您可以创建一个课程
public class DoCalculationAsyncTask extends AsyncTask<Void, Void, DataType> {
@SuppressLint("StaticFieldLeak")
private Context mContext;
public DoCalculationAsyncTask(Context context) {
}
@Override
protected Bitmap doInBackground(Void... params) {
try {
} catch (Exception e) {
e.printStackTrace();
} finally {
}
return something;
}
@Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
} }
然后像这样调用类
try {
DoCalculationAsyncTask doCalculationAsyncTask = new
DoCalculationAsyncTask(value 1, value 2, value 3, ...);
doCalculationAsyncTask.execute();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
答案 1 :(得分:0)
runOnUiThread
命令中的所有内容都在UI线程上运行(顾名思义),其中包括对Thread.sleep(duration)
的调用(因此导致UI线程挂起/执行过多的工作) 。作为简单的第一步,请尝试将其分为几个runOnUiThread
调用,然后将Thread.sleep(duration)
语句置于它们之间而不是其中。