本文介绍了publishProgress从doInBackground函数里面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的AsyncTask来执行一个漫长的过程。

I use an AsyncTask to perform a long process.

我不想直接把我漫长的过程code里面doInBackground。相反,我漫长的过程code位于另一个类,我在doInBackground打电话。

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.

我希望能够从longProcess函数中调用publishProgress。在C ++中我会回调指针publishProgress传递给我的longProcess功能。

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.

我如何做到这一点在Java中?

How do I do that in java ?

编辑:

我漫长的过程code:

My long process code:

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

我的AsyncTask 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;
        }
    }

编辑#2在漫长的过程方法,也可以是非静态的,被称为是这样的:

EDIT #2The 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.

推荐答案

困难的是, publishProgress 保护的最后所以,即使你通过静态办法叫你仍然不能称之为 publishProgress 直接

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

如果这个工程,请让我知道!请注意,调用 doProgress 从比已经从 doInBackground 调用的方法,其他任何地方几乎肯定会导致错误。

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.

感觉pretty的脏我,其他人有更好的办法吗?

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

这篇关于publishProgress从doInBackground函数里面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 01:44