在AsyncTask中无法让doInBackground工作。

问题描述 投票:0回答:1

我是AsyncTask的新手,如果我的问题很愚蠢,请提前道歉。长话短说,我有一个处理一些文件的方法,我想在后台运行它。我的类如下,问题是,当直接调用该方法时,该方法工作正常,但当我试图通过doInBackground调用它时,绝对不会发生任何事情。

这个方法可以工作。AttachFilesFromFolder.attach(files);

而这个不行new AttachFilesFromFolder().execute(files);

这个类的问题是:

public class AttachFilesFromFolder extends AsyncTask<File[], Void, Void> {
    @Override
    protected Void doInBackground(File[]... files) {
        try {
            attach(files[0]);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void attach(File[] files) throws InterruptedException {
        for (File file : files) {
            log("For loop started.");
            File targetLocation = new File(Environment.getDataDirectory() + "/data/org.p4.epo.android/" + file.getName());

            Thread t1 = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        InputStream in = new FileInputStream(file);
                        OutputStream out = new FileOutputStream(targetLocation);

                        byte[] buf = new byte[1024];
                        int len;

                        while ((len = in.read(buf)) > 0) {
                            out.write(buf, 0, len);
                        }

                        buf = null;
                        in.close();
                        in = null;
                        out.close();
                        out = null;
                        log("Copied file " + targetLocation.toString() + " successfully.");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });

            Thread t2 = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        SdkManager.sharedInstance().addAttachment(targetLocation.toString(), file.getName(), AttachMode.asNewPage, 1, false);
                        log("Attached " + file.getName());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });

            log("Thread T1 started.");
            t1.start();
            t1.join();
            log("Thread T2 started.");
            t2.start();
            t2.join();
        }
    }
}
java android android-asynctask
1个回答
0
投票

通过使用executor来解决。这样就解决了。

© www.soinside.com 2019 - 2024. All rights reserved.