在ASyncTask中更新TextView

时间:2017-06-22 15:02:06

标签: android android-asynctask

拖网多年后试图找到一个可以理解的解决方案来解决我的问题,我放弃了,来到这里看看你是否可以提供帮助。

我的目标:更新TextView,每秒计数1到99999,而不会挂掉主线程。

package com.myapp.counter;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myBackgroundThread myThread = new myBackgroundThread();

        myThread.execute();
    }


    private class myBackgroundThread extends AsyncTask<Void,Integer,Void>
    {


        int maxTimer = 99999;
        int i = 0;

        //Assign the textView in MainActivity to a variable myCounter.
        TextView myCounter = (TextView)findViewById(R.id.idCounter);

        @Override
        protected void onPreExecute() {
        }

        @Override
        protected Void doInBackground(Void... params) {

     //  Toast.makeText(getApplicationContext(),"InBackground",Toast.LENGTH_SHORT).show(); 
            //Tried Toasting a message upon this starting but just threw an error 
            //Guess because i tried to add a UI component in a background task.


            for(int i = 0; i < maxTimer; i++)
            {

                publishProgress(i);


            }

            return null;

        }

        //onProgressUpdate is never firing from publishProgress...
        protected void onProgressUpdate(Integer i) {


            Toast.makeText(getApplicationContext(),i,Toast.LENGTH_SHORT).show();
            //Updatet he counter from 000 to 1,2,3,4 etc.
            myCounter.setText(i);

        }

        protected void onPostExecute(Void result)
        {

        }

    }


    public void startTimer(View view)
    {


        TextView myText = (TextView)findViewById(R.id.textView);

       // Toast.makeText(this,"Started...", Toast.LENGTH_SHORT).show();

    }


    public void stopTimer(View view) {


        Toast.makeText(this, "Stopped...", Toast.LENGTH_SHORT).show();


    }

}

我似乎无法理解为什么publishProgress不会触发,我想从按下按钮执行ASyncTask。

我有3个元素2个按钮startTimer和stopTimer以及1个textview在后台更新。

非常感谢所有人。

1 个答案:

答案 0 :(得分:0)

这样的事情:

protected class InitTask extends AsyncTask<Context, Integer, String> {

        // -- run intensive processes here
        // -- notice that the datatype of the first param in the class definition matches the param passed to this
        // method
        // -- and that the datatype of the last param in the class definition matches the return type of this method
        @Override
        protected String doInBackground(Context... params) {
            // -- on every iteration
            // -- runs a while loop that causes the thread to sleep for 50 milliseconds
            // -- publishes the progress - calls the onProgressUpdate handler defined below
            // -- and increments the counter variable i by one
            int i = 0;
            while (i <= 50) {
                try {
                    Thread.sleep(50);
                    publishProgress(i);
                    i++;
                }
                catch (Exception e) {
                    Log.i("makemachine", e.getMessage());
                }
            }
            return "COMPLETE!";
        }

        // -- gets called just before thread begins
        @Override
        protected void onPreExecute() {
            Log.i("makemachine", "onPreExecute()");
            super.onPreExecute();
        }

        // -- called from the publish progress
        // -- notice that the datatype of the second param gets passed to this method
        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            Log.i("makemachine", "onProgressUpdate(): " + String.valueOf(values[0]));
            _percentField.setText((values[0] * 2) + "%");
            _percentField.setTextSize(values[0]);
        }

        // -- called if the cancel button is pressed
        @Override
        protected void onCancelled() {
            super.onCancelled();
            Log.i("makemachine", "onCancelled()");
            _percentField.setText("Cancelled!");
            _percentField.setTextColor(0xFFFF0000);
        }

        // -- called as soon as doInBackground method completes
        // -- notice that the third param gets passed to this method
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            Log.i("makemachine", "onPostExecute(): " + result);
            _percentField.setText(result);
            _percentField.setTextColor(0xFF69adea);
            _cancelButton.setVisibility(View.INVISIBLE);
        }
    }
}