简体   繁体   English

如何在Android Java中的for循环内使用AsyncTask

[英]How to use AsyncTask inside of a for cycle in Android Java

Please help me, I'm trying to create random button change colors using AsyncTask class inside of a for cycle (for a future game) but I don't know why it doesn't work properly, when the "RUN" button is pressed apparently the cycle is executed only once instead of 20, because the other buttons change color only once. 请帮助我,我正在尝试在for周期内使用AsyncTask类创建随机的按钮更改颜色(以用于将来的游戏),但是我不知道为什么当按下“运行”按钮时它无法正常工作显然,该循环仅执行一次,而不是20,因为其他按钮仅更改一次颜色。 here is my code: (thanks) 这是我的代码:(谢谢)

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:paddingBottom="@dimen/activity_vertical_margin"

    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.mybuttons.MainActivity" >

    <Button
        android:id="@+id/btnOne"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/btnRun"
        android:layout_alignParentTop="true"
        android:text="BUTTON ONE" />

    <Button
        android:id="@+id/btnTwo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/btnOne"
        android:layout_below="@+id/btnOne"
        android:text="BUTTON TWO" />

    <Button
        android:id="@+id/btnThree"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/btnTwo"
        android:layout_below="@+id/btnTwo"
        android:text="BUTTON THREE" />

    <Button
        android:id="@+id/btnFour"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/btnThree"
        android:layout_below="@+id/btnThree"
        android:text="BUTTON FOUR" />

    <Button
        android:id="@+id/btnFive"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/btnFour"
        android:layout_below="@+id/btnFour"
        android:text="BUTTON FIVE" />

    <Button
        android:id="@+id/btnRun"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/btnFive"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="33dp"
        android:text="RUN" />

</RelativeLayout>

The code: 编码:

package com.myexercise;

import java.util.Random;

import android.app.Activity;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener {

    Button myOne;
    Button myTwo;
    Button myThree;
    Button myFour;
    Button myFive;
    Button myRun;
    int wichOne;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myOne=(Button)findViewById(R.id.btnOne);
        myTwo=(Button)findViewById(R.id.btnTwo);
        myThree=(Button)findViewById(R.id.btnThree);
        myFour=(Button)findViewById(R.id.btnFour);
        myFive=(Button)findViewById(R.id.btnFive);
        myRun=(Button)findViewById(R.id.btnRun);
        myRun.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        for(int i=0;i<20;i++){
            System.out.println("i="+i);
            MyAsyncTask runner = new MyAsyncTask(); 
            String sleepTime = "500";
            int myRandom=new Random().nextInt(5);
            String thisButton = Integer.toString(myRandom);
            runner.execute(sleepTime, thisButton);
        }
    }
    class MyAsyncTask extends AsyncTask<String, String, String> {
        private String resp;
        @Override
        protected String doInBackground(String... params) {
            try {
                int time = Integer.parseInt(params[0]);  
                wichOne = Integer.parseInt(params[1]);
                Thread.sleep(time);
            } catch (InterruptedException e) {
                e.printStackTrace();
                resp = e.getMessage();
            } catch (Exception e) {
                e.printStackTrace();
                resp = e.getMessage();
            }
            return resp;
        }
        @Override
        protected void onPostExecute(String result) {
            myOne.setBackgroundColor(Color.LTGRAY);
            myTwo.setBackgroundColor(Color.LTGRAY);
            myThree.setBackgroundColor(Color.LTGRAY);
            myFour.setBackgroundColor(Color.LTGRAY);
            myFive.setBackgroundColor(Color.LTGRAY);
        }
        @Override
        protected void onPreExecute() {
            if(wichOne==0){
                myOne.setBackgroundColor(Color.YELLOW);
            }else{
                if(wichOne==1){
                    myTwo.setBackgroundColor(Color.BLUE);
                } else {
                    if(wichOne==2){
                        myThree.setBackgroundColor(Color.CYAN);
                    } else{
                        if(wichOne==3){
                            myFour.setBackgroundColor(Color.RED);
                        } else{
                            myFive.setBackgroundColor(Color.DKGRAY);
                        }
                    }
                }
            }
        }
    }
}

I don't know if this will solve your issue, but there is a big error in your Async. 我不知道这是否可以解决您的问题,但是您的Async中有一个大错误。

You are attempting to read wichOne value in onPreExecute method while the value is defined in your onBackground! 当您在onBackground中定义值时,您正在尝试读取onPreExecute方法中的wichOne值!

You should use a constructor for your asynctask and pass arguments to it: 您应该为asynctask使用构造函数,并将参数传递给它:

@Override
public void onClick(View v) {
    for(int i=0;i<20;i++){
        System.out.println("i="+i); 
        int myRandom=new Random().nextInt(5);
        MyAsyncTask runner = new MyAsyncTask(500, myRandom);
        runner.execute();
    }
}
class MyAsyncTask extends AsyncTask<String, String, String> {
    private String resp;

    private int mWichOne;
    private int mTime;

    public MyAsyncTask(int time, int wich) {
        mTime = time;
        mWichOne = wich;
    }

    @Override
    protected void onPreExecute() {
        switch (mWichOne) {
            case 0: // do whatever you want with the mWichOne value
        }
    }

    @Override
    protected String doInBackground(String... params) {
        try {
            Thread.sleep(mTime); // Why you are doing this???
        } catch (InterruptedException e) {
            e.printStackTrace();
            resp = e.getMessage();
        } catch (Exception e) {
            e.printStackTrace();
            resp = e.getMessage();
        }
        return resp;
    }
    @Override
    protected void onPostExecute(String result) {
        myOne.setBackgroundColor(Color.LTGRAY);
        myTwo.setBackgroundColor(Color.LTGRAY);
        myThree.setBackgroundColor(Color.LTGRAY);
        myFour.setBackgroundColor(Color.LTGRAY);
        myFive.setBackgroundColor(Color.LTGRAY);
    }
}

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

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