向AsynchTask doInBackground添加更多参数(Params ... params)

时间:2014-12-23 03:53:21

标签: android android-asynctask

我正在尝试使文件操作类在后台异步调用其函数。我希望能够使用AsyncTask的doInBackground方法在文件操作之间切换,但是当添加一个int参数用作开关时,我收到错误。

class Files extends AsyncTask<String[], Void, Boolean> {
    private static final int COPY   = 0;
    private static final int DELETE = 1;

    public boolean copy(String[] copyDir, String[] pasteDir) {
        return doInBackground(COPY, copyDir, pasteDir);
    }

    public boolean delete(String[] files) {
        return doInBackground(DELETE, files);
    }

    //Async operation handler
    protected Boolean doInBackground(int o, String[]...files) {
        Boolean task = false;
        try {
            //Operation switch
            switch (o) {
                case COPY:
                    task = copyFiles(files[0], files[1]);
                    break;
                case DELETE:
                    task = deleteFiles(files[0]);
                    break;
            }
        } catch(IOException e) {
            e.printStackTrace();
        }
        return task;
    }

    public boolean copyFiles(String[] inputPaths, String[] outputPaths) throws IOException {
        //Copy Logic
    }

    public boolean deleteFiles(String[] paths) throws IOException {
        //Delete Logic
    }
}

是否可以采用类似于此实现的方法?如果没有,那么抽象方法有什么不允许这样的东西?

1 个答案:

答案 0 :(得分:0)

使用多个构造函数/ setter传递要传递给的参数组,并在 doInBackground 方法中根据您通过setter方法传递给AsyncTask的操作类型。