Android: How can I pass parameters to AsyncTask's onPreExecute()?

前端 未结 4 1931
轻奢々
轻奢々 2020-12-02 04:32

I use an AsyncTask for loading operations that I implemented as an inner class.

In onPreExecute() I show a loading dialog which I then hid

4条回答
  •  自闭症患者
    2020-12-02 05:01

    You can either pass the parameter in the task constructor or when you call execute:

    AsyncTask
    

    The first parameter (Object) is passed in doInBackground. The third parameter (MyTaskResult) is returned by doInBackground. You can change them to the types you want. The three dots mean that zero or more objects (or an array of them) may be passed as the argument(s).

    public class MyActivity extends AppCompatActivity {
    
        TextView textView1;
        TextView textView2;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main2);    
            textView1 = (TextView) findViewById(R.id.textView1);
            textView2 = (TextView) findViewById(R.id.textView2);
    
            String input1 = "test";
            boolean input2 = true;
            int input3 = 100;
            long input4 = 100000000;
    
            new MyTask(input3, input4).execute(input1, input2);
        }
    
        private class MyTaskResult {
            String text1;
            String text2;
        }
    
        private class MyTask extends AsyncTask {
            private String val1;
            private boolean val2;
            private int val3;
            private long val4;
    
    
            public MyTask(int in3, long in4) {
                this.val3 = in3;
                this.val4 = in4;
    
                // Do something ...
            }
    
            protected void onPreExecute() {
                // Do something ...
            }
    
            @Override
            protected MyTaskResult doInBackground(Object... params) {
                MyTaskResult res = new MyTaskResult();
                val1 = (String) params[0];
                val2 = (boolean) params[1];
    
                //Do some lengthy operation    
                res.text1 = RunProc1(val1);
                res.text2 = RunProc2(val2);
    
                return res;
            }
    
            @Override
            protected void onPostExecute(MyTaskResult res) {
                textView1.setText(res.text1);
                textView2.setText(res.text2);
    
            }
        }
    
    }
    

提交回复
热议问题