publishProgress from inside a function in doInBackground?

前端 未结 5 753
名媛妹妹
名媛妹妹 2020-12-15 17:20

I use an AsyncTask to perform a long process.

I don\'t want to place my long process code directly inside doInBackground. Instead my long process code is located in

相关标签:
5条回答
  • 2020-12-15 17:46

    The difficulty is that publishProgress is protected final so even if you pass this into your static method call you still can't call publishProgress directly.

    I've not tried this myself, but how about:

    public class LongOperation extends AsyncTask<String, Integer, String> {
        ...
    
        @Override
        protected String doInBackground(String... params) {
            SomeClass.doStuff(this);
            return null;
        }
        ...
    
        public void doProgress(int value){
            publishProgress(value);
        }
    }
    ...
    public class SomeClass {
        public static void doStuff(LongOperation task){
            // do stuff
            task.doProgress(1);
            // more stuff etc
        }
    }
    

    If this works please let me know! Note that calling doProgress from anywhere other than a method that has been invoked from doInBackground will almost certainly cause an error.

    Feels pretty dirty to me, anyone else have a better way?

    0 讨论(0)
  • 2020-12-15 17:46

    If this works please let me know! Note that calling doProgress from anywhere other than a method that has been invoked from doInBackground will almost certainly cause an error.

    Yes, it works. I extended it so that you don't need to pass the AsyncTask as a parameter to your method. This is particularly useful if (like me) you've already written all your methods before deciding that actually you do need to publish some progress, or in my case, update the UI from an AsyncTask:

    public abstract class ModifiedAsyncTask<A,B,C> extends AsyncTask<A,B,C>{
    
        private static final HashMap<Thread,ModifiedAsyncTask<?,?,?>> threads 
                 = new HashMap<Thread,ModifiedAsyncTask<?,?,?>>();
    
        @Override
        protected C doInBackground(A... params) {
            threads.put(Thread.currentThread(), this);
            return null;        
        }
    
        public static <T> void publishProgressCustom(T... t) throws ClassCastException{
            ModifiedAsyncTask<?, T, ?> task = null;
            try{
                task = (ModifiedAsyncTask<?, T, ?>) threads.get(Thread.currentThread());
            }catch(ClassCastException e){
                throw e;
            }
            if(task!=null)
                task.publishProgress(t);
        }
    }
    
    public class testThreadsActivity extends Activity {
    
    /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);        
        }
    
        public void Button1Clicked(View v){
            MyThread mthread = new MyThread();
            mthread.execute((Void[])null);      
        }
    
        private class MyThread extends ModifiedAsyncTask<Void, Long, Void>{
    
            @Override
            protected Void doInBackground(Void... params) {
                super.doInBackground(params);
    
                while(true){
                    myMethod(System.currentTimeMillis());               
                    try {
                        Thread.sleep(1000L);
                    } catch (InterruptedException e) {                  
                        return null;
                    }
                }           
            }
    
            protected void onProgressUpdate(Long... progress) {
                //Update UI
                ((TextView) findViewById(R.id.textView2)).setText("The Time is:" + progress[0]);
            }
    
    
        }
    
        private void myMethod(long l){
    
            // do something
    
            // request UI update
            ModifiedAsyncTask.publishProgressCustom(new Long[]{l});
        }
    
    }
    

    Feels pretty dirty to me, anyone else have a better way?

    My way is probably worse. I'm calling a static method for doProgress (which I called publishProgressCustom). It can be called from anywhere without producing an error (as if the thread has no corresponding AsyncTask in the hashMap, it won't call publishProgress). The down side is that you have to add the Thread-AsyncTask mapping yourself after the thread has started. (You can't override AsyncTask.execute() sadly as this is final). I've done it here by overriding doInBackground() in the super class, so that anyone extending it just has to put super.doInBackground() as the first line in their own doInBackground().

    I don't know enough about Threads and AsyncTask to know what happens to the HashMap references once the Thread and/or AsyncTask comes to an end. I suspect bad things happen, so I wouldn't suggest anyone try my solution as part of their own unless they know better

    0 讨论(0)
  • 2020-12-15 17:49

    A solution could be placing a simple public class inside the AsyncTask (make sure the task you define is also public) which has a public method that calls publishProgress(val). Passing that class should be available from any other package or class.

    public abstract class MyClass {
    
        public MyClass() {
            // code...
        }
    
        // more code from your class...
    
        public class Task extends AsyncTask<String, Integer, Integer> {
            private Progress progress;
    
            protected Task() {
                this.progress = new Progress(this);
            }
    
            // ...
    
            @Override
            protected Integer doInBackground(String... params) {
                // ...
                SomeClass.doStuff(progress);
                // ...
            }
    
            // ...
    
            @Override
            protected void onProgressUpdate(Integer... progress) {
                // your code to update progress
            }
    
            public class Progress {
                private Task task;
    
                public Progress(Task task) {
                    this.task = task;
                }
    
                public void publish(int val) {
                    task.publishProgress(val);
                }
            }
        }
    }
    

    and then in the other class:

    public class SomeClass {
        public static void doStuff(Progress progress){
            // do stuff
            progress.publish(20);
            // more stuff etc
        }
    }
    

    This worked for me.

    0 讨论(0)
  • 2020-12-15 18:03

    Split up the longProcess() function into smaller functions.

    Sample code:

    @Override
    protected Boolean doInBackground(Void... params) {
        YourClass.yourStaticMethodOne();
        publishProgress(1);
        YourClass.yourStaticMethodTwo();
        publishProgress(2);
        YourClass.yourStaticMethodThree();
        publishProgress(3);
    
        // And so on...
        return true;
    }
    
    0 讨论(0)
  • 2020-12-15 18:08

    When you say "my long process code is located in another class that I call in doInBackground", do you mean "located in another method that I call in doInBackground"?

    If so, you could make that method a private method of your AsynTask class. Then you could call publishProgress inside the method whenever needed.

    0 讨论(0)
提交回复
热议问题