Android:打开文件过多错误

Laz*_*nja 5 android httpurlconnection android-file

我有以下每3秒运行一次的操作。
基本上,它从服务器下载文件,然后每3秒将其保存到本地文件中。
以下代码可以完成一段时间。

public class DownloadTask extends AsyncTask<String, Void, String>{

    @Override
    protected String doInBackground(String... params) {
        downloadCommandFile( eventUrl);
        return null;
    }


}

private void downloadCommandFile(String dlUrl){
    int count;
    try {
        URL url = new URL( dlUrl );
        NetUtils.trustAllHosts();
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
        con.setDoInput(true);
        con.setDoOutput(true);
        con.connect();
        int fileSize = con.getContentLength();
        Log.d(TAG, "Download file size = " + fileSize );
        InputStream is = url.openStream();
        String dir = Environment.getExternalStorageDirectory() + Utils.DL_DIRECTORY;
        File file = new File( dir );
        if( !file.exists() ){
            file.mkdir();
        }

        FileOutputStream fos = new FileOutputStream(file + Utils.DL_FILE);
        byte data[] = new byte[1024];
        long total = 0;

        while( (count = is.read(data)) != -1 ){
            total += count;
            fos.write(data, 0, count);
        }

        is.close();
        fos.close();
        con.disconnect(); // close connection


    } catch (Exception e) {
        Log.e(TAG, "DOWNLOAD ERROR = " + e.toString() );
    }

}
Run Code Online (Sandbox Code Playgroud)

一切正常,但是如果我让它运行5至10分钟,则会出现以下错误。

06-04 19:40:40.872:E / NativeCrypto(6320):AppData :: create pipe(2)失败:打开文件过多06-04 19:40:40.892:E / NativeCrypto(6320):AppData :: create pipe(2)失败:打开的文件太多06-04 19:40:40.892:E / EventService(6320):下载错误= javax.net.ssl.SSLException:无法创建应用程序数据

最近两天我一直在做一些研究。
有建议表明它们有许多连接处于打开状态,例如/sf/answers/979334331/,但我仍然无法弄清问题所在。
有什么想法可能导致问题吗?
提前致谢。

luk*_*kas 6

我认为您收到此错误是因为您同时打开了太多文件,这意味着您同时运行了太多异步任务(每个异步任务都打开了一个文件),如果您说您运行了一个每3秒更新一次。

您应该尝试使用线程池执行程序来限制同时运行的异步任务的数量。

  • 如果您不支持Android 2.x,则可以通过提供自己的线程池执行程序执行执行异步任务:“执行程序e = Executors.newFixedThreadPool(3)”,然后运行异步任务:“ executeOnExecutor(e);”。 (3认同)
  • 感谢您提供宝贵的信息。知道如何限制同时运行的异步任务的数量吗? (2认同)