Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
439 views
in Technique[技术] by (71.8m points)

android - publishProgress from inside a function in doInBackground?

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 another class, that I call in doInBackground.

I would like to be able to call publishProgress from inside the longProcess function. In C++ I would pass a callback pointer to publishProgress to my longProcess function.

How do I do that in java ?

EDIT:

My long process code:

public class MyLongProcessClass
    {
    public static void mylongProcess(File filetoRead)
        {
        // some code...
        // here I would like to call publishProgress
        // some code...
        }
    }

My AsyncTask code:

private class ReadFileTask extends AsyncTask<File, Void, Boolean>
    {
    ProgressDialog  taskProgress;

    @Override
    protected Boolean doInBackground(File... configFile)
        {
        MyLongProcessClass.mylongProcess(configFile[0]);
        return true;
        }
    }

EDIT #2 The long process method could also be non-static and called like this:

MyLongProcessClass fileReader = new MyLongProcessClass();
fileReader.mylongProcess(configFile[0]);

But that does not change my problem.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...