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

时间:2014-11-28 19:48:07

标签: java android android-asynctask

请帮助我,我正在尝试使用AsyncTask类创建随机按钮更改颜色for for循环(对于未来的游戏)但我不知道为什么它不能正常工作,当“RUN”显然按下按钮只执行一次而不是20次,因为其他按钮只改变一次颜色。这是我的代码:(谢谢)

<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>

代码:

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);
                        }
                    }
                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我不知道这是否能解决您的问题,但您的异步中存在很大的错误。

您正在尝试在onPreExecute方法中读取wichOne值,而在onBackground中定义了值!

您应该为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);
    }
}